diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java
index e736978a7a8..7297ab285e5 100644
--- a/agent/src/com/cloud/agent/AgentShell.java
+++ b/agent/src/com/cloud/agent/AgentShell.java
@@ -612,8 +612,8 @@ public class AgentShell implements IAgentShell {
public static void main(String[] args) {
try {
- LogUtils.initLog4j("log4j-cloud.xml");
-
+ LogUtils.initLog4j("log4j-cloud.xml");
+
AgentShell shell = new AgentShell();
shell.init(args);
shell.start();
diff --git a/client/tomcatconf/componentContext.xml.in b/client/tomcatconf/componentContext.xml.in
index aa0893d013b..456484eac4c 100644
--- a/client/tomcatconf/componentContext.xml.in
+++ b/client/tomcatconf/componentContext.xml.in
@@ -104,7 +104,14 @@
-
+
+
+
+
+
+
+
+
@@ -240,7 +248,7 @@
-
+
@@ -285,7 +293,7 @@
-
+
@@ -293,7 +301,7 @@
-
+
diff --git a/deps/install-non-oss.sh b/deps/install-non-oss.sh
index af495e7cc21..74575a8dbd1 100755
--- a/deps/install-non-oss.sh
+++ b/deps/install-non-oss.sh
@@ -8,7 +8,7 @@
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
-#
+#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@@ -26,10 +26,17 @@ if [ -e cloud-manageontap.jar ]; then mv cloud-manageontap.jar manageontap.jar;
mvn install:install-file -Dfile=manageontap.jar -DgroupId=com.cloud.com.netapp -DartifactId=manageontap -Dversion=4.0 -Dpackaging=jar
# From https://my.vmware.com/group/vmware/get-download?downloadGroup=VSDK41
-# Version: 4.1, Release-date: 2010-07-13, Build: 257238
+# Version: 4.1, Release-date: 2010-07-13, Build: 257238
if [ -e vmware-apputils.jar ]; then mv vmware-apputils.jar apputils.jar; fi
if [ -e vmware-vim.jar ]; then mv vmware-vim.jar vim.jar; fi
if [ -e vmware-vim25.jar ]; then mv vmware-vim25.jar vim25.jar; fi
mvn install:install-file -Dfile=vim25.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim25 -Dversion=4.1 -Dpackaging=jar
mvn install:install-file -Dfile=apputils.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-apputils -Dversion=4.1 -Dpackaging=jar
mvn install:install-file -Dfile=vim.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim -Dversion=4.1 -Dpackaging=jar
+
+#
+# From https://my.vmware.com/group/vmware/get-download?downloadGroup=VSP510-WEBSDK-510
+# Version: 5.1, Release-date: 2012-09-10, Build: 774886
+mvn install:install-file -Dfile=vim25_51.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim25 -Dversion=5.1 -Dpackaging=jar
+
+
diff --git a/plugins/hypervisors/vmware/pom.xml b/plugins/hypervisors/vmware/pom.xml
index 5d954f331e6..468e0a50599 100644
--- a/plugins/hypervisors/vmware/pom.xml
+++ b/plugins/hypervisors/vmware/pom.xml
@@ -38,18 +38,6 @@
${cs.vmware.api.version}
compile
-
- com.cloud.com.vmware
- vmware-vim
- ${cs.vmware.api.version}
- compile
-
-
- com.cloud.com.vmware
- vmware-apputils
- ${cs.vmware.api.version}
- compile
-
org.apache.axis
axis
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
index e6d708cbfed..94ba97d96a1 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
@@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
+// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware;
@@ -78,6 +78,7 @@ import com.cloud.utils.UriUtils;
import com.vmware.vim25.ClusterDasConfigInfo;
import com.vmware.vim25.ManagedObjectReference;
+
@Local(value = Discoverer.class)
public class VmwareServerDiscoverer extends DiscovererBase implements
Discoverer, ResourceStateAdapter {
@@ -113,41 +114,41 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
public VmwareServerDiscoverer() {
s_logger.info("VmwareServerDiscoverer is constructed");
}
-
- @Override
+
+ @Override
public Map extends ServerResource, Map> find(long dcId, Long podId, Long clusterId, URI url,
String username, String password, List hostTags) throws DiscoveryException {
-
+
if(s_logger.isInfoEnabled())
s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost());
-
+
if(podId == null) {
if(s_logger.isInfoEnabled())
- s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
- return null;
- }
-
- ClusterVO cluster = _clusterDao.findById(clusterId);
+ s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
+ return null;
+ }
+
+ ClusterVO cluster = _clusterDao.findById(clusterId);
if(cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) {
if(s_logger.isInfoEnabled())
- s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
- return null;
- }
-
- List hosts = _resourceMgr.listAllHostsInCluster(clusterId);
+ s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
+ return null;
+ }
+
+ List hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) {
int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(hosts.get(0).getHypervisorType(), hosts.get(0).getHypervisorVersion());
if (hosts.size() > maxHostsPerCluster) {
String msg = "VMware cluster " + cluster.getName() + " is too big to add new host now. (current configured cluster size: " + maxHostsPerCluster + ")";
- s_logger.error(msg);
- throw new DiscoveredWithErrorException(msg);
- }
+ s_logger.error(msg);
+ throw new DiscoveredWithErrorException(msg);
+ }
}
- String privateTrafficLabel = null;
- String publicTrafficLabel = null;
- String guestTrafficLabel = null;
- Map vsmCredentials = null;
+ String privateTrafficLabel = null;
+ String publicTrafficLabel = null;
+ String guestTrafficLabel = null;
+ Map vsmCredentials = null;
VirtualSwitchType defaultVirtualSwitchType = VirtualSwitchType.StandardVirtualSwitch;
@@ -204,30 +205,30 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
// Process traffic label information provided at zone level and cluster level
publicTrafficLabelObj = getTrafficInfo(TrafficType.Public, publicTrafficLabel, defaultVirtualSwitchType, paramPublicVswitchType, paramPublicVswitchName, clusterId);
- // Configuration Check: A physical network cannot be shared by different types of virtual switches.
- //
- // Check if different vswitch types are chosen for same physical network
- // 1. Get physical network for guest traffic - multiple networks
- // 2. Get physical network for public traffic - single network
- // See if 2 is in 1
- // if no - pass
- // if yes - compare publicTrafficLabelObj.getVirtualSwitchType() == guestTrafficLabelObj.getVirtualSwitchType()
- // true - pass
- // false - throw exception - fail cluster add operation
+ // Configuration Check: A physical network cannot be shared by different types of virtual switches.
+ //
+ // Check if different vswitch types are chosen for same physical network
+ // 1. Get physical network for guest traffic - multiple networks
+ // 2. Get physical network for public traffic - single network
+ // See if 2 is in 1
+ // if no - pass
+ // if yes - compare publicTrafficLabelObj.getVirtualSwitchType() == guestTrafficLabelObj.getVirtualSwitchType()
+ // true - pass
+ // false - throw exception - fail cluster add operation
- List extends PhysicalNetwork> pNetworkListGuestTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Guest);
- List extends PhysicalNetwork> pNetworkListPublicTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Public);
- // Public network would be on single physical network hence getting first object of the list would suffice.
- PhysicalNetwork pNetworkPublic = pNetworkListPublicTraffic.get(0);
- if (pNetworkListGuestTraffic.contains(pNetworkPublic)) {
- if (publicTrafficLabelObj.getVirtualSwitchType() != guestTrafficLabelObj.getVirtualSwitchType()) {
- String msg = "Both public traffic and guest traffic is over same physical network " + pNetworkPublic +
- ". And virtual switch type chosen for each traffic is different" +
- ". A physical network cannot be shared by different types of virtual switches.";
- s_logger.error(msg);
- throw new InvalidParameterValueException(msg);
- }
+ List extends PhysicalNetwork> pNetworkListGuestTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Guest);
+ List extends PhysicalNetwork> pNetworkListPublicTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Public);
+ // Public network would be on single physical network hence getting first object of the list would suffice.
+ PhysicalNetwork pNetworkPublic = pNetworkListPublicTraffic.get(0);
+ if (pNetworkListGuestTraffic.contains(pNetworkPublic)) {
+ if (publicTrafficLabelObj.getVirtualSwitchType() != guestTrafficLabelObj.getVirtualSwitchType()) {
+ String msg = "Both public traffic and guest traffic is over same physical network " + pNetworkPublic +
+ ". And virtual switch type chosen for each traffic is different" +
+ ". A physical network cannot be shared by different types of virtual switches.";
+ s_logger.error(msg);
+ throw new InvalidParameterValueException(msg);
}
+ }
} else {
// Distributed virtual switch is not supported in Basic zone for now.
// Private / Management network traffic is not yet supported over distributed virtual switch.
@@ -239,24 +240,24 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
}
privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware);
- if (privateTrafficLabel != null) {
+ if (privateTrafficLabel != null) {
s_logger.info("Detected private network label : " + privateTrafficLabel);
- }
+ }
if (nexusDVS) {
- if (zoneType != NetworkType.Basic) {
+ if (zoneType != NetworkType.Basic) {
publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
- if (publicTrafficLabel != null) {
+ if (publicTrafficLabel != null) {
s_logger.info("Detected public network label : " + publicTrafficLabel);
- }
- }
- // Get physical network label
+ }
+ }
+ // Get physical network label
guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
- if (guestTrafficLabel != null) {
+ if (guestTrafficLabel != null) {
s_logger.info("Detected guest network label : " + guestTrafficLabel);
- }
+ }
vsmCredentials = _vmwareMgr.getNexusVSMCredentialsByClusterId(clusterId);
- }
+ }
VmwareContext context = null;
try {
@@ -304,8 +305,8 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
} else {
ClusterMO clusterMo = new ClusterMO(context, morCluster);
ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig();
- if (dasConfig != null && dasConfig.getEnabled() != null
- && dasConfig.getEnabled().booleanValue()) {
+ if (dasConfig != null && dasConfig.isEnabled() != null
+ && dasConfig.isEnabled().booleanValue()) {
clusterDetails.put("NativeHA", "true");
_clusterDetailsDao.persist(clusterId, clusterDetails);
}
@@ -329,7 +330,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
details.put("url", hostMo.getHostName());
details.put("username", username);
details.put("password", password);
- String guid = morHost.getType() + ":" + morHost.get_value()
+ String guid = morHost.getType() + ":" + morHost.getValue()
+ "@" + url.getHost();
details.put("guid", guid);
@@ -385,7 +386,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
if (morCluster == null) {
for (ManagedObjectReference morHost : morHosts) {
ManagedObjectReference morParent = (ManagedObjectReference) context
- .getServiceUtil().getDynamicProperty(morHost, "parent");
+ .getVimClient().getDynamicProperty(morHost, "parent");
if (morParent.getType().equalsIgnoreCase(
"ClusterComputeResource"))
return false;
@@ -393,12 +394,12 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
} else {
for (ManagedObjectReference morHost : morHosts) {
ManagedObjectReference morParent = (ManagedObjectReference) context
- .getServiceUtil().getDynamicProperty(morHost, "parent");
+ .getVimClient().getDynamicProperty(morHost, "parent");
if (!morParent.getType().equalsIgnoreCase(
"ClusterComputeResource"))
return false;
- if (!morParent.get_value().equals(morCluster.get_value()))
+ if (!morParent.getValue().equals(morCluster.getValue()))
return false;
}
}
@@ -464,6 +465,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
}
}
+
@Override
public HostVO createHostVOForConnectedAgent(HostVO host,
StartupCommand[] cmd) {
@@ -499,6 +501,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
_resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
return new DeleteHostAnswer(true);
+
}
@Override
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
index 60b5ce4d4cd..9d29abf8d35 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
@@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
+// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware.manager;
@@ -67,6 +67,8 @@ import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper;
import com.cloud.hypervisor.vmware.mo.TaskMO;
import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType;
import com.cloud.hypervisor.vmware.mo.VmwareHostType;
+import com.cloud.utils.ssh.SshHelper;
+import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.network.CiscoNexusVSMDeviceVO;
import com.cloud.network.NetworkModel;
@@ -91,7 +93,6 @@ import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SshHelper;
import com.cloud.vm.DomainRouterVO;
import com.google.gson.Gson;
-import com.vmware.apputils.vim25.ServiceUtil;
import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.HostConnectSpec;
import com.vmware.vim25.ManagedObjectReference;
@@ -316,10 +317,10 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
}
s_logger.info("Preparing network on host " + hostMo.getContext().toString() + " for " + privateTrafficLabel);
- HypervisorHostHelper.prepareNetwork(vSwitchName, "cloud.private", hostMo, vlanId, null, null, 180000, false);
+ HypervisorHostHelper.prepareNetwork(vSwitchName, "cloud.private", hostMo, vlanId, null, null, 180000, false);
}
-
+
@Override
public List addHostToPodCluster(VmwareContext serviceContext, long dcId, Long podId, Long clusterId,
String hostInventoryPath) throws Exception {
@@ -336,27 +337,28 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
List returnedHostList = new ArrayList();
if(mor.getType().equals("ComputeResource")) {
- ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getServiceUtil().getDynamicProperty(mor, "host");
- assert(hosts != null);
+ List hosts = (List)serviceContext.getVimClient().getDynamicProperty(mor, "host");
+ assert(hosts != null && hosts.size() > 0);
// For ESX host, we need to enable host firewall to allow VNC access
- HostMO hostMo = new HostMO(serviceContext, hosts[0]);
+ HostMO hostMo = new HostMO(serviceContext, hosts.get(0));
+
prepareHost(hostMo, privateTrafficLabel);
- returnedHostList.add(hosts[0]);
+ returnedHostList.add(hosts.get(0));
return returnedHostList;
} else if(mor.getType().equals("ClusterComputeResource")) {
- ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getServiceUtil().getDynamicProperty(mor, "host");
+ List hosts = (List)serviceContext.getVimClient().getDynamicProperty(mor, "host");
assert(hosts != null);
- if (hosts.length > 0) {
- AboutInfo about = (AboutInfo)(serviceContext.getServiceUtil().getDynamicProperty(hosts[0], "config.product"));
+ if (hosts.size() > 0) {
+ AboutInfo about = (AboutInfo)(serviceContext.getVimClient().getDynamicProperty(hosts.get(0), "config.product"));
String version = about.getApiVersion();
int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(HypervisorType.VMware, version);
- if (hosts.length > maxHostsPerCluster) {
+ if (hosts.size() > maxHostsPerCluster) {
String msg = "vCenter cluster size is too big (current configured cluster size: " + maxHostsPerCluster + ")";
- s_logger.error(msg);
- throw new DiscoveredWithErrorException(msg);
- }
+ s_logger.error(msg);
+ throw new DiscoveredWithErrorException(msg);
+ }
}
for(ManagedObjectReference morHost: hosts) {
@@ -373,7 +375,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
returnedHostList.add(mor);
return returnedHostList;
} else {
- s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.get_value() + " from inventory path: " + hostInventoryPath);
+ s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.getValue() + " from inventory path: " + hostInventoryPath);
return null;
}
}
@@ -386,8 +388,8 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
private ManagedObjectReference addHostToVCenterCluster(VmwareContext serviceContext, ManagedObjectReference morCluster,
String host, String userName, String password) throws Exception {
- ServiceUtil serviceUtil = serviceContext.getServiceUtil();
- ManagedObjectReference morHost = serviceUtil.getDecendentMoRef(morCluster, "HostSystem", host);
+ VmwareClient vclient = serviceContext.getVimClient();
+ ManagedObjectReference morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host);
if(morHost == null) {
HostConnectSpec hostSpec = new HostConnectSpec();
hostSpec.setUserName(userName);
@@ -395,16 +397,16 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
hostSpec.setHostName(host);
hostSpec.setForce(true); // forcely take over the host
- ManagedObjectReference morTask = serviceContext.getService().addHost_Task(morCluster, hostSpec, true, null, null);
- String taskResult = serviceUtil.waitForTask(morTask);
- if(!taskResult.equals("sucess")) {
+ ManagedObjectReference morTask = serviceContext.getService().addHostTask(morCluster, hostSpec, true, null, null);
+ boolean taskResult = vclient.waitForTask(morTask);
+ if(!taskResult) {
s_logger.error("Unable to add host " + host + " to vSphere cluster due to " + TaskMO.getTaskFailureInfo(serviceContext, morTask));
throw new CloudRuntimeException("Unable to add host " + host + " to vSphere cluster due to " + taskResult);
}
serviceContext.waitForTaskProgressDone(morTask);
// init morHost after it has been created
- morHost = serviceUtil.getDecendentMoRef(morCluster, "HostSystem", host);
+ morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host);
if(morHost == null) {
throw new CloudRuntimeException("Successfully added host into vSphere but unable to find it later on?!. Please make sure you are either using IP address or full qualified domain name for host");
}
@@ -422,6 +424,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
@Override
public String getSecondaryStorageStoreUrl(long dcId) {
+
List secStorageHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dcId);
if(secStorageHosts.size() > 0)
return secStorageHosts.get(0).getStorageUrl();
@@ -492,6 +495,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
s_logger.info("Inject SSH key pairs before copying systemvm.iso into secondary storage");
_configServer.updateKeyPairs();
+
try {
FileUtil.copyfile(srcIso, destIso);
} catch(IOException e) {
@@ -533,11 +537,11 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
if (url != null) {
isoFile = new File(url.getPath());
}
-
+
if(isoFile == null || !isoFile.exists()) {
isoFile = new File("/usr/share/cloudstack-common/vms/systemvm.iso");
}
-
+
assert(isoFile != null);
if(!isoFile.exists()) {
s_logger.error("Unable to locate systemvm.iso in your setup at " + isoFile.toString());
@@ -552,7 +556,6 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
if ( url != null ){
keyFile = new File(url.getPath());
}
-
if (keyFile == null || !keyFile.exists()) {
keyFile = new File("/usr/share/cloudstack-common/scripts/vm/systemvm/id_rsa.cloud");
}
@@ -838,7 +841,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
vsmMapVO = _vsmMapDao.findByClusterId(clusterId);
long vsmId = 0;
if (vsmMapVO != null) {
- vsmId = vsmMapVO.getVsmId();
+ vsmId = vsmMapVO.getVsmId();
s_logger.info("vsmId is " + vsmId);
nexusVSM = _nexusDao.findById(vsmId);
s_logger.info("Fetching nexus vsm credentials from database.");
@@ -846,7 +849,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
else {
s_logger.info("Found empty vsmMapVO.");
return null;
- }
+ }
Map nexusVSMCredentials = new HashMap();
if (nexusVSM != null) {
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
index c7b7cd3bcba..8be76e8fff2 100644
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
@@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
+// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware.manager;
@@ -83,24 +83,24 @@ import com.vmware.vim25.VirtualSCSISharing;
public class VmwareStorageManagerImpl implements VmwareStorageManager {
private static final Logger s_logger = Logger.getLogger(VmwareStorageManagerImpl.class);
-
+
private final VmwareStorageMount _mountService;
private final StorageLayer _storage = new JavaStorageLayer();
-
+
private int _timeout;
-
+
public VmwareStorageManagerImpl(VmwareStorageMount mountService) {
assert(mountService != null);
_mountService = mountService;
}
-
+
public void configure(Map params) {
s_logger.info("Configure VmwareStorageManagerImpl");
-
+
String value = (String)params.get("scripts.timeout");
_timeout = NumbersUtil.parseInt(value, 1440) * 1000;
}
-
+
@Override
public Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd) {
String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
@@ -130,18 +130,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
templateName = cmd.getName();
}
-
+
VmwareContext context = hostService.getServiceContext(cmd);
try {
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
-
- String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().get_value()).getBytes()).toString();
+
+ String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().getValue()).getBytes()).toString();
// truncate template name to 32 chars to ensure they work well with vSphere API's.
- templateUuidName = templateUuidName.replace("-", "");
-
+ templateUuidName = templateUuidName.replace("-", "");
+
DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true);
-
+
if (templateMo == null) {
if(s_logger.isInfoEnabled())
s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName);
@@ -167,7 +167,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
return new PrimaryStorageDownloadAnswer(msg);
}
}
-
+
@Override
public Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd) {
Long accountId = cmd.getAccountId();
@@ -198,15 +198,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
if (vmMo == null) {
if(s_logger.isDebugEnabled())
s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter");
-
+
vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName());
if(vmMo == null) {
dsMo = new DatastoreMO(hyperHost.getContext(), morDs);
-
+
workerVMName = hostService.getWorkerName(context, cmd, 0);
-
+
// attach a volume to dummay wrapper VM for taking snapshot and exporting the VM for backup
- if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier._otherGuest.toString(), morDs, false)) {
+ if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier.OTHER_GUEST.value(), morDs, false)) {
String msg = "Unable to create worker VM to execute BackupSnapshotCommand";
s_logger.error(msg);
throw new Exception(msg);
@@ -216,17 +216,17 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName);
}
workerVm = vmMo;
-
+
// attach volume to worker VM
String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath);
vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs);
- }
- }
-
+ }
+ }
+
if (!vmMo.createSnapshot(snapshotUuid, "Snapshot taken for " + cmd.getSnapshotName(), false, false)) {
throw new Exception("Failed to take snapshot " + cmd.getSnapshotName() + " on vm: " + cmd.getVmName());
}
-
+
snapshotBackupUuid = backupSnapshotToSecondaryStorage(vmMo, accountId, volumeId, cmd.getVolumePath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid,
hostService.getWorkerName(context, cmd, 1));
@@ -234,7 +234,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
if (success) {
details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage.";
}
-
+
} finally {
if(vmMo != null){
ManagedObjectReference snapshotMor = vmMo.getSnapshotMor(snapshotUuid);
@@ -242,7 +242,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
vmMo.removeSnapshot(snapshotUuid, false);
}
}
-
+
try {
if (workerVm != null) {
// detach volume and destroy worker vm
@@ -251,7 +251,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
} catch (Throwable e) {
s_logger.warn("Failed to destroy worker VM: " + workerVMName);
- }
+ }
}
} catch (Throwable e) {
if (e instanceof RemoteException) {
@@ -278,7 +278,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
VmwareContext context = hostService.getServiceContext(cmd);
try {
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
-
+
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
if (vmMo == null) {
if(s_logger.isDebugEnabled())
@@ -294,7 +294,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Ternary result = createTemplateFromVolume(vmMo,
accountId, templateId, cmd.getUniqueName(),
- secondaryStoragePoolURL, volumePath,
+ secondaryStoragePoolURL, volumePath,
hostService.getWorkerName(context, cmd, 0));
return new CreatePrivateTemplateAnswer(cmd, true, null,
@@ -344,7 +344,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
return new CreatePrivateTemplateAnswer(cmd, false, details);
}
}
-
+
@Override
public Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd) {
Long volumeId = cmd.getVolumeId();
@@ -393,64 +393,64 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
return new CopyVolumeAnswer(cmd, false, "CopyVolumeCommand failed due to exception: " + StringUtils.getExceptionStackInfo(e), null, null);
}
}
-
+
@Override
- public Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd) {
+ public Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd) {
- String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
- Long accountId = cmd.getAccountId();
- Long volumeId = cmd.getVolumeId();
- String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
- String backedUpSnapshotUuid = cmd.getSnapshotUuid();
+ String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel();
+ Long accountId = cmd.getAccountId();
+ Long volumeId = cmd.getVolumeId();
+ String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
+ String backedUpSnapshotUuid = cmd.getSnapshotUuid();
- String details = null;
- boolean success = false;
- String newVolumeName = UUID.randomUUID().toString().replaceAll("-", "");
+ String details = null;
+ boolean success = false;
+ String newVolumeName = UUID.randomUUID().toString().replaceAll("-", "");
- VmwareContext context = hostService.getServiceContext(cmd);
- try {
- VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
+ VmwareContext context = hostService.getServiceContext(cmd);
+ try {
+ VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
ManagedObjectReference morPrimaryDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost,
primaryStorageNameLabel);
- if (morPrimaryDs == null) {
- String msg = "Unable to find datastore: " + primaryStorageNameLabel;
- s_logger.error(msg);
- throw new Exception(msg);
- }
+ if (morPrimaryDs == null) {
+ String msg = "Unable to find datastore: " + primaryStorageNameLabel;
+ s_logger.error(msg);
+ throw new Exception(msg);
+ }
- DatastoreMO primaryDsMo = new DatastoreMO(hyperHost.getContext(), morPrimaryDs);
- details = createVolumeFromSnapshot(hyperHost, primaryDsMo,
- newVolumeName, accountId, volumeId, secondaryStorageUrl, backedUpSnapshotUuid);
- if (details == null) {
- success = true;
- }
- } catch (Throwable e) {
- if (e instanceof RemoteException) {
- hostService.invalidateServiceContext(context);
- }
-
- s_logger.error("Unexpecpted exception ", e);
- details = "CreateVolumeFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e);
- }
+ DatastoreMO primaryDsMo = new DatastoreMO(hyperHost.getContext(), morPrimaryDs);
+ details = createVolumeFromSnapshot(hyperHost, primaryDsMo,
+ newVolumeName, accountId, volumeId, secondaryStorageUrl, backedUpSnapshotUuid);
+ if (details == null) {
+ success = true;
+ }
+ } catch (Throwable e) {
+ if (e instanceof RemoteException) {
+ hostService.invalidateServiceContext(context);
+ }
- return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName);
- }
+ s_logger.error("Unexpecpted exception ", e);
+ details = "CreateVolumeFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e);
+ }
+
+ return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName);
+ }
// templateName: name in secondary storage
// templateUuid: will be used at hypervisor layer
private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl,
String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception {
-
- s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: "
+
+ s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: "
+ secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage
+ ", templateName: " + templateName);
-
+
String secondaryMountPoint = _mountService.getMountPoint(secondaryStorageUrl);
s_logger.info("Secondary storage mount point: " + secondaryMountPoint);
-
- String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage +
+
+ String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage +
templateName + "." + ImageFormat.OVA.getFileExtension();
-
+
String srcFileName = getOVFFilePath(srcOVAFileName);
if(srcFileName == null) {
Script command = new Script("tar", 0, s_logger);
@@ -465,40 +465,40 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
throw new Exception(msg);
}
}
-
+
srcFileName = getOVFFilePath(srcOVAFileName);
- if(srcFileName == null) {
- String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
+ if(srcFileName == null) {
+ String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
String vmName = templateUuid;
hyperHost.importVmFromOVF(srcFileName, vmName, datastoreMo, "thin");
-
+
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
if(vmMo == null) {
- String msg = "Failed to import OVA template. secondaryStorage: "
+ String msg = "Failed to import OVA template. secondaryStorage: "
+ secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage
+ ", templateName: " + templateName + ", templateUuid: " + templateUuid;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
if(vmMo.createSnapshot("cloud.template.base", "Base snapshot", false, false)) {
vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, templateUuid);
vmMo.markAsTemplate();
} else {
vmMo.destroy();
- String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid;
+ String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid;
s_logger.error(msg);
throw new Exception(msg);
}
}
-
- private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName,
+
+ private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName,
String secStorageUrl, String volumePath, String workerVmName) throws Exception {
-
+
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId);
String installFullPath = secondaryMountPoint + "/" + installPath;
@@ -506,16 +506,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Script command = new Script(false, "mkdir", _timeout, s_logger);
command.add("-p");
command.add(installFullPath);
-
+
String result = command.execute();
if(result != null) {
- String msg = "unable to prepare template directory: "
+ String msg = "unable to prepare template directory: "
+ installPath + ", storage: " + secStorageUrl + ", error msg: " + result;
s_logger.error(msg);
throw new Exception(msg);
}
}
-
+
VirtualMachineMO clonedVm = null;
try {
Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false);
@@ -524,15 +524,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
s_logger.error(msg);
throw new Exception(msg);
}
-
+
if(!vmMo.createSnapshot(templateUniqueName, "Temporary snapshot for template creation", false, false)) {
String msg = "Unable to take snapshot for creating template from volume. volume path: " + volumePath;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
// 4 MB is the minimum requirement for VM memory in VMware
- vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
+ vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);
if(clonedVm == null) {
@@ -540,9 +540,9 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
s_logger.error(msg);
throw new Exception(msg);
}
-
+
clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false);
-
+
long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length();
VmdkProcessor processor = new VmdkProcessor();
Map params = new HashMap();
@@ -552,54 +552,54 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);
return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize);
-
+
} finally {
if(clonedVm != null) {
clonedVm.detachAllDisks();
clonedVm.destroy();
}
-
+
vmMo.removeSnapshot(templateUniqueName, false);
}
}
-
- private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName,
+
+ private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName,
String secStorageUrl, long volumeId, String backedUpSnapshotUuid) throws Exception {
-
+
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId);
String installFullPath = secondaryMountPoint + "/" + installPath;
String installFullName = installFullPath + "/" + templateUniqueName + ".ova";
- String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId)
+ String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId)
+ "/" + backedUpSnapshotUuid + ".ova";
String result;
Script command;
-
+
synchronized(installPath.intern()) {
command = new Script(false, "mkdir", _timeout, s_logger);
command.add("-p");
command.add(installFullPath);
-
+
result = command.execute();
if(result != null) {
- String msg = "unable to prepare template directory: "
+ String msg = "unable to prepare template directory: "
+ installPath + ", storage: " + secStorageUrl + ", error msg: " + result;
s_logger.error(msg);
throw new Exception(msg);
}
}
-
+
try {
command = new Script(false, "cp", _timeout, s_logger);
command.add(snapshotFullName);
command.add(installFullName);
result = command.execute();
if(result != null) {
- String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath;
+ String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
// untar OVA file at template directory
command = new Script("tar", 0, s_logger);
command.add("--no-same-owner");
@@ -608,12 +608,12 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
s_logger.info("Executing command: " + command.toString());
result = command.execute();
if(result != null) {
- String msg = "unable to untar snapshot " + snapshotFullName + " to "
- + installFullPath;
+ String msg = "unable to untar snapshot " + snapshotFullName + " to "
+ + installFullPath;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length();
VmdkProcessor processor = new VmdkProcessor();
Map params = new HashMap();
@@ -623,45 +623,45 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);
return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize);
-
+
} catch(Exception e) {
// TODO, clean up left over files
throw e;
}
}
-
- private void postCreatePrivateTemplate(String installFullPath, long templateId,
+
+ private void postCreatePrivateTemplate(String installFullPath, long templateId,
String templateName, long size, long virtualSize) throws Exception {
// TODO a bit ugly here
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties")));
- out.write("filename=" + templateName + ".ova");
+ out.write("filename=" + templateName + ".ova");
out.newLine();
- out.write("description=");
+ out.write("description=");
out.newLine();
- out.write("checksum=");
+ out.write("checksum=");
out.newLine();
- out.write("hvm=false");
+ out.write("hvm=false");
out.newLine();
- out.write("size=" + size);
+ out.write("size=" + size);
out.newLine();
- out.write("ova=true");
+ out.write("ova=true");
out.newLine();
- out.write("id=" + templateId);
+ out.write("id=" + templateId);
out.newLine();
- out.write("public=false");
+ out.write("public=false");
out.newLine();
- out.write("ova.filename=" + templateName + ".ova");
+ out.write("ova.filename=" + templateName + ".ova");
out.newLine();
out.write("uniquename=" + templateName);
out.newLine();
- out.write("ova.virtualsize=" + virtualSize);
+ out.write("ova.virtualsize=" + virtualSize);
out.newLine();
- out.write("virtualsize=" + virtualSize);
+ out.write("virtualsize=" + virtualSize);
out.newLine();
- out.write("ova.size=" + size);
+ out.write("ova.size=" + size);
out.newLine();
} finally {
if(out != null)
@@ -669,21 +669,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
}
- private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
+ private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
long accountId, long volumeId, String secStorageUrl, String snapshotBackupUuid) throws Exception {
-
- restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName,
+
+ restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName,
secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), snapshotBackupUuid);
return null;
}
-
- private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
+
+ private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
String secStorageUrl, String secStorageDir, String backupName) throws Exception {
-
+
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
- String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/"
+ String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/"
+ backupName + "." + ImageFormat.OVA.getFileExtension();
-
+
String srcFileName = getOVFFilePath(srcOVAFileName);
if(srcFileName == null) {
Script command = new Script("tar", 0, s_logger);
@@ -698,21 +698,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
throw new Exception(msg);
}
}
-
+
srcFileName = getOVFFilePath(srcOVAFileName);
if(srcFileName == null) {
- String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
+ String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
VirtualMachineMO clonedVm = null;
try {
hyperHost.importVmFromOVF(srcFileName, newVolumeName, primaryDsMo, "thin");
clonedVm = hyperHost.findVmOnHyperHost(newVolumeName);
if(clonedVm == null)
throw new Exception("Unable to create container VM for volume creation");
-
+
clonedVm.moveAllVmDiskFiles(primaryDsMo, "", false);
clonedVm.detachAllDisks();
} finally {
@@ -722,24 +722,24 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
}
}
-
- private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId,
- String volumePath, String snapshotUuid, String secStorageUrl,
+
+ private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId,
+ String volumePath, String snapshotUuid, String secStorageUrl,
String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception {
-
+
String backupUuid = UUID.randomUUID().toString();
- exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl,
+ exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl,
getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName);
return backupUuid;
}
-
- private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath,
+
+ private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath,
String secStorageUrl, String secStorageDir, String exportName,
String workerVmName) throws Exception {
-
+
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
String exportPath = secondaryMountPoint + "/" + secStorageDir;
-
+
synchronized(exportPath.intern()) {
if(!new File(exportPath).exists()) {
Script command = new Script(false, "mkdir", _timeout, s_logger);
@@ -752,16 +752,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
VirtualMachineMO clonedVm = null;
try {
-
+
Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false);
if(volumeDeviceInfo == null) {
String msg = "Unable to find related disk device for volume. volume path: " + volumePath;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
// 4 MB is the minimum requirement for VM memory in VMware
- vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
+ vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);
if(clonedVm == null) {
@@ -769,7 +769,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
s_logger.error(msg);
throw new Exception(msg);
}
-
+
clonedVm.exportVm(exportPath, exportName, true, true);
} finally {
if(clonedVm != null) {
@@ -778,7 +778,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
}
}
-
+
private String deleteSnapshotOnSecondaryStorge(long accountId, long volumeId, String secStorageUrl, String backupUuid) throws Exception {
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
@@ -787,18 +787,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
if(file.exists()) {
if(file.delete())
return null;
-
+
} else {
return "Backup file does not exist. backupUuid: " + backupUuid;
}
-
+
return "Failed to delete snapshot backup file, backupUuid: " + backupUuid;
}
-
- private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd,
- String vmName, long volumeId, String poolId, String volumePath,
+
+ private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd,
+ String vmName, long volumeId, String poolId, String volumePath,
String secStorageUrl, String workerVmName) throws Exception {
-
+
String volumeFolder = String.valueOf(volumeId) + "/";
VirtualMachineMO workerVm=null;
VirtualMachineMO vmMo=null;
@@ -822,21 +822,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
vmConfig.setName(workerVmName);
vmConfig.setMemoryMB((long) 4);
vmConfig.setNumCPUs(1);
- vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString());
+ vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value());
VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
vmConfig.setFiles(fileInfo);
// Scsi controller
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
- scsiController.setSharedBus(VirtualSCSISharing.noSharing);
+ scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
scsiController.setBusNumber(0);
scsiController.setKey(1);
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
scsiControllerSpec.setDevice(scsiController);
- scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
- vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec });
-
+ scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+ vmConfig.getDeviceChange().add(scsiControllerSpec);
+
hyperHost.createVm(vmConfig);
workerVm = hyperHost.findVmOnHyperHost(workerVmName);
if (workerVm == null) {
@@ -844,7 +844,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
s_logger.error(msg);
throw new Exception(msg);
}
-
+
//attach volume to worker VM
String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath);
workerVm.attachDisk(new String[] { datastoreVolumePath }, morDs);
@@ -853,7 +853,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
vmMo.createSnapshot(exportName, "Temporary snapshot for copy-volume command", false, false);
- exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName,
+ exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName,
hostService.getWorkerName(hyperHost.getContext(), cmd, 1));
return new Pair(volumeFolder, exportName);
@@ -867,16 +867,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
}
- private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId,
+ private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId,
DatastoreMO dsMo, String secStorageUrl, String exportName) throws Exception {
String volumeFolder = String.valueOf(volumeId) + "/";
String newVolume = UUID.randomUUID().toString().replaceAll("-", "");
restoreVolumeFromSecStorage(hyperHost, dsMo, newVolume, secStorageUrl, "volumes/" + volumeFolder, exportName);
-
+
return new Pair(volumeFolder, newVolume);
}
-
+
private String getOVFFilePath(String srcOVAFileName) {
File file = new File(srcOVAFileName);
assert(_storage != null);
@@ -891,11 +891,11 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
return null;
}
-
+
private static String getTemplateRelativeDirInSecStorage(long accountId, long templateId) {
return "template/tmpl/" + accountId + "/" + templateId;
}
-
+
private static String getSnapshotRelativeDirInSecStorage(long accountId, long volumeId) {
return "snapshots/" + accountId + "/" + volumeId;
}
@@ -912,18 +912,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Map mapNewDisk = new HashMap();
try {
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
-
+
// wait if there are already VM snapshot task running
ManagedObjectReference taskmgr = context.getServiceContent().getTaskManager();
- ManagedObjectReference[] tasks = (ManagedObjectReference[]) context.getServiceUtil().getDynamicProperty(taskmgr, "recentTask");
+ ManagedObjectReference[] tasks = (ManagedObjectReference[]) context.getVimClient().getDynamicProperty(taskmgr, "recentTask");
for (ManagedObjectReference taskMor : tasks) {
- TaskInfo info = (TaskInfo) (context.getServiceUtil().getDynamicProperty(taskMor, "info"));
+ TaskInfo info = (TaskInfo) (context.getVimClient().getDynamicProperty(taskMor, "info"));
if(info.getEntityName().equals(cmd.getVmName()) && info.getName().equalsIgnoreCase("CreateSnapshot_Task")){
s_logger.debug("There is already a VM snapshot task running, wait for it");
- context.getServiceUtil().waitForTask(taskMor);
+ context.getVimClient().waitForTask(taskMor);
}
}
-
+
vmMo = hyperHost.findVmOnHyperHost(vmName);
if(vmMo == null)
vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
@@ -952,7 +952,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
mapNewDisk.put(s[0], vmdkName);
}
}
-
+
// update volume path using maps
for (VolumeTO volumeTO : volumeTOs) {
String parentUUID = volumeTO.getPath();
@@ -1003,7 +1003,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
}
s_logger.debug("snapshot: " + vmSnapshotName + " is removed");
- // after removed snapshot, the volumes' paths have been changed for the VM, needs to report new paths to manager
+ // after removed snapshot, the volumes' paths have been changed for the VM, needs to report new paths to manager
VirtualDisk[] vdisks = vmMo.getAllDiskDevice();
for (int i = 0; i < vdisks.length; i++) {
@SuppressWarnings("deprecation")
@@ -1045,18 +1045,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
Map mapNewDisk = new HashMap();
try {
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
-
+
// wait if there are already VM revert task running
ManagedObjectReference taskmgr = context.getServiceContent().getTaskManager();
- ManagedObjectReference[] tasks = (ManagedObjectReference[]) context.getServiceUtil().getDynamicProperty(taskmgr, "recentTask");
+ ManagedObjectReference[] tasks = (ManagedObjectReference[]) context.getVimClient().getDynamicProperty(taskmgr, "recentTask");
for (ManagedObjectReference taskMor : tasks) {
- TaskInfo info = (TaskInfo) (context.getServiceUtil().getDynamicProperty(taskMor, "info"));
+ TaskInfo info = (TaskInfo) (context.getVimClient().getDynamicProperty(taskMor, "info"));
if(info.getEntityName().equals(cmd.getVmName()) && info.getName().equalsIgnoreCase("RevertToSnapshot_Task")){
s_logger.debug("There is already a VM snapshot task running, wait for it");
- context.getServiceUtil().waitForTask(taskMor);
+ context.getVimClient().waitForTask(taskMor);
}
}
-
+
HostMO hostMo = (HostMO) hyperHost;
vmMo = hyperHost.findVmOnHyperHost(vmName);
if(vmMo == null)
@@ -1113,7 +1113,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
}
}
-
+
private VirtualMachineMO createWorkingVM(DatastoreMO dsMo, VmwareHypervisorHost hyperHost) throws Exception {
String uniqueName = UUID.randomUUID().toString();
VirtualMachineMO workingVM = null;
@@ -1121,20 +1121,20 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
vmConfig.setName(uniqueName);
vmConfig.setMemoryMB((long) 4);
vmConfig.setNumCPUs(1);
- vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString());
+ vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString());
VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
vmConfig.setFiles(fileInfo);
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
- scsiController.setSharedBus(VirtualSCSISharing.noSharing);
+ scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
scsiController.setBusNumber(0);
scsiController.setKey(1);
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
scsiControllerSpec.setDevice(scsiController);
- scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
+ scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
- vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec });
+ vmConfig.getDeviceChange().add(scsiControllerSpec);
hyperHost.createVm(vmConfig);
workingVM = hyperHost.findVmOnHyperHost(uniqueName);
return workingVM;
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java
index 8324bcf0d30..5db9da3c02d 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java
@@ -23,12 +23,10 @@ import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.hypervisor.vmware.manager.VmwareManager;
-import com.cloud.hypervisor.vmware.manager.VmwareManagerImpl;
+import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.utils.StringUtils;
-import com.cloud.utils.component.ComponentContext;
-import com.vmware.apputils.version.ExtendedAppUtil;
@Component
public class VmwareContextFactory {
@@ -56,15 +54,15 @@ public class VmwareContextFactory {
assert(vCenterPassword != null);
String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService";
- String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword };
+ //String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword };
if(s_logger.isDebugEnabled())
s_logger.debug("initialize VmwareContext. url: " + serviceUrl + ", username: " + vCenterUserName + ", password: " + StringUtils.getMaskedPasswordForDisplay(vCenterPassword));
- ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params);
+ VmwareClient vimClient = new VmwareClient(vCenterAddress + "-" + s_seq++);
+ vimClient.connect(serviceUrl, vCenterUserName, vCenterPassword);
- appUtil.connect();
- VmwareContext context = new VmwareContext(appUtil, vCenterAddress);
+ VmwareContext context = new VmwareContext(vimClient, vCenterAddress);
context.registerStockObject(VmwareManager.CONTEXT_STOCK_NAME, s_vmwareMgr);
context.registerStockObject("serviceconsole", s_vmwareMgr.getServiceConsolePortGroupName());
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 3c008ef98d5..83226a41db4 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
+// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware.resource;
@@ -24,6 +24,7 @@ import java.net.URI;
import java.nio.channels.SocketChannel;
import java.rmi.RemoteException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@@ -247,7 +248,9 @@ import com.vmware.vim25.PerfMetricSeries;
import com.vmware.vim25.PerfQuerySpec;
import com.vmware.vim25.PerfSampleInfo;
import com.vmware.vim25.RuntimeFault;
+import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.ToolsUnavailable;
+import com.vmware.vim25.ToolsUnavailableFaultMsg;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualDeviceConfigSpec;
@@ -270,7 +273,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
protected String _name;
protected final long _ops_timeout = 900000; // 15 minutes time out to time
- protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown
+
+ protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown
// out an operation
protected final int _retry = 24;
@@ -297,7 +301,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
protected boolean _reserveMem = false;
protected boolean _recycleHungWorker = false;
- protected DiskControllerType _rootDiskController = DiskControllerType.ide;
+ protected DiskControllerType _rootDiskController = DiskControllerType.ide;
protected ManagedObjectReference _morHyperHost;
protected VmwareContext _serviceContext;
@@ -313,9 +317,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
protected static HashMap s_statesTable;
static {
s_statesTable = new HashMap();
- s_statesTable.put(VirtualMachinePowerState.poweredOn, State.Running);
- s_statesTable.put(VirtualMachinePowerState.poweredOff, State.Stopped);
- s_statesTable.put(VirtualMachinePowerState.suspended, State.Stopped);
+ s_statesTable.put(VirtualMachinePowerState.POWERED_ON, State.Running);
+ s_statesTable.put(VirtualMachinePowerState.POWERED_OFF, State.Stopped);
+ s_statesTable.put(VirtualMachinePowerState.SUSPENDED, State.Stopped);
}
public VmwareResource() {
@@ -324,6 +328,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
@Override
public Answer executeRequest(Command cmd) {
+
if(s_logger.isTraceEnabled())
s_logger.trace("Begin executeRequest(), cmd: " + cmd.getClass().getSimpleName());
@@ -481,14 +486,14 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
synchronized (this) {
try {
- JmxUtil.registerMBean("VMware " + _morHyperHost.get_value(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean);
+ JmxUtil.registerMBean("VMware " + _morHyperHost.getValue(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean);
_cmdMBeans.add(mbean);
if (_cmdMBeans.size() >= MAX_CMD_MBEAN) {
PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0);
_cmdMBeans.remove(0);
- JmxUtil.unregisterMBean("VMware " + _morHyperHost.get_value(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name"));
+ JmxUtil.unregisterMBean("VMware " + _morHyperHost.getValue(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name"));
}
} catch (Exception e) {
if(s_logger.isTraceEnabled())
@@ -500,12 +505,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
NDC.pop();
}
+
if(s_logger.isTraceEnabled())
s_logger.trace("End executeRequest(), cmd: " + cmd.getClass().getSimpleName());
return answer;
}
-
+
private Answer execute(ResizeVolumeCommand cmd) {
String path = cmd.getPath();
String vmName = cmd.getInstanceName();
@@ -533,15 +539,15 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if (newSize < oldSize){
throw new Exception("VMware doesn't support shrinking volume from larger size: " + oldSize+ " MB to a smaller size: " + newSize + " MB");
} else if(newSize == oldSize){
- return new ResizeVolumeAnswer(cmd, true, "success", newSize*1024);
+ return new ResizeVolumeAnswer(cmd, true, "success", newSize*1024);
}
disk.setCapacityInKB(newSize);
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(disk);
- deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.edit);
- vmConfigSpec.setDeviceChange(new VirtualDeviceConfigSpec[] { deviceConfigSpec });
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure VM to resize disk. vmName: " + vmName);
}
@@ -613,6 +619,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if (!resultPair.first()) {
throw new Exception(" vpc network usage plugin call failed ");
+
}
if (option.equals("get") || option.equals("vpn")) {
@@ -633,7 +640,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
} catch (Throwable e) {
- s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to "
+
+ s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to "
+ VmwareHelper.getExceptionMessage(e), e);
}
return new NetworkUsageAnswer(cmd, "success", 0L, 0L);
@@ -730,6 +738,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
}
+
if (!result.first()) {
s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: "
+ args);
@@ -739,7 +748,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
return new SetFirewallRulesAnswer(cmd, false, results);
- }
+ }
} catch (Throwable e) {
s_logger.error("SetFirewallRulesCommand(args: " + args
+ ") failed on setting one rule due to "
@@ -749,10 +758,10 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
results[i] = "Failed";
}
return new SetFirewallRulesAnswer(cmd, false, results);
- }
+ }
return new SetFirewallRulesAnswer(cmd, true, results);
- }
+ }
protected Answer execute(SetStaticNatRulesCommand cmd) {
if (s_logger.isInfoEnabled()) {
@@ -1336,12 +1345,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
- deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec();
- deviceConfigSpecArray[0].setDevice(nic);
- deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add);
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
+ deviceConfigSpec.setDevice(nic);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
if(!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure devices when running PlugNicCommand");
}
@@ -1384,12 +1393,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
return new UnPlugNicAnswer(cmd, true, "success");
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
- deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec();
- deviceConfigSpecArray[0].setDevice(nic);
- deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.remove);
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
+ deviceConfigSpec.setDevice(nic);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
if(!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure devices when running unplugNicCommand");
}
@@ -1527,6 +1536,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if (removeVif) {
+
String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK);
int nicMasks = Integer.parseInt(nicMasksStr);
nicMasks &= ~(1 << publicNicInfo.first().intValue());
@@ -1582,12 +1592,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
- deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec();
- deviceConfigSpecArray[0].setDevice(device);
- deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.edit);
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
+ deviceConfigSpec.setDevice(device);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
+
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
if(!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure devices when plugPublicNic");
}
@@ -1674,7 +1685,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
protected Answer execute(SavePasswordCommand cmd) {
if (s_logger.isInfoEnabled()) {
- s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: "
+
+ s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: "
+ StringUtils.getMaskedPasswordForDisplay(cmd.getPassword()));
}
@@ -1720,6 +1732,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
// ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null
+
String args = " -m " + cmd.getVmMac();
if (cmd.getVmIpAddress() != null) {
args += " -4 " + cmd.getVmIpAddress();
@@ -1737,7 +1750,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if (cmd.getStaticRoutes() != null) {
args += " -s " + cmd.getStaticRoutes();
}
-
+
if (cmd.getVmIp6Address() != null) {
args += " -6 " + cmd.getVmIp6Address();
args += " -u " + cmd.getDuid();
@@ -2097,7 +2110,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
assert (vmSpec.getMinSpeed() != null) && (rootDiskDataStoreDetails != null);
if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(),
vmSpec.getMinSpeed(), vmSpec.getLimitCpuUse(),(int)(vmSpec.getMaxRam()/(1024*1024)), ramMb,
- translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) {
+ translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), rootDiskDataStoreDetails.first(), false)) {
throw new Exception("Failed to create VM. vmName: " + vmName);
}
}
@@ -2129,8 +2142,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024));
VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(),
vmSpec.getMinSpeed(),(int) (vmSpec.getMaxRam()/(1024*1024)), ramMb,
- translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse());
-
+ translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), vmSpec.getLimitCpuUse());
+
VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices];
int i = 0;
int ideControllerKey = vmMo.getIDEDeviceControllerKey();
@@ -2156,17 +2169,17 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs);
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
- Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()),
+ Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()),
secDsMo.getMor(), true, true, i, i + 1);
deviceConfigSpecArray[i].setDevice(isoInfo.first());
if (isoInfo.second()) {
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
} else {
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
}
i++;
} else {
@@ -2182,11 +2195,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if (isoInfo.second()) {
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
} else {
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
}
} else {
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
@@ -2196,12 +2209,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
} else {
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
}
}
i++;
@@ -2253,7 +2266,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1);
}
deviceConfigSpecArray[i].setDevice(device);
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
+
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare volume at new device " + _gson.toJson(device));
@@ -2284,7 +2298,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
deviceConfigSpecArray[i].setDevice(nic);
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
if(s_logger.isDebugEnabled())
s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i]));
@@ -2297,7 +2311,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
nicCount++;
}
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+ vmConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray));
// pass boot arguments through machine.id & perform customized options to VMX
@@ -2322,7 +2336,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
String keyboardLayout = null;
if(vmSpec.getDetails() != null)
keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD);
- vmConfigSpec.setExtraConfig(configureVnc(extraOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout));
+ vmConfigSpec.getExtraConfig().addAll(Arrays.asList(configureVnc(extraOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout)));
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure VM before start. vmName: " + vmName);
@@ -2357,6 +2371,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
private Map validateVmDetails(Map vmDetails) {
+
Map validatedDetails = new HashMap();
if(vmDetails != null && vmDetails.size() > 0) {
@@ -2381,7 +2396,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
-
+
private NicTO[] sortNicsByDeviceId(NicTO[] nics) {
List listForSort = new ArrayList();
@@ -2496,7 +2511,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
!namePrefix.startsWith("cloud.private"));
}
else {
- networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()),
+ networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()),
nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, switchType, _portsPerDvPortGroup);
}
@@ -2892,7 +2907,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
try {
vmMo.rebootGuest();
return new RebootAnswer(cmd, "reboot succeeded", true);
- } catch(ToolsUnavailable e) {
+ } catch(ToolsUnavailableFaultMsg e) {
s_logger.warn("VMware tools is not installed at guest OS, we will perform hard reset for reboot");
} catch(Exception e) {
s_logger.warn("We are not able to perform gracefull guest reboot due to " + VmwareHelper.getExceptionMessage(e));
@@ -3077,8 +3092,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
VmwareManager mgr = dcMo.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
- ObjectContent[] ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" });
- if (ocs != null && ocs.length > 0) {
+ List ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" });
+ if (ocs != null && ocs.size() > 0) {
for (ObjectContent oc : ocs) {
HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj());
VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo));
@@ -3111,7 +3126,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
ManagedObjectReference morDatastore = null;
morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid());
if(morDatastore == null)
- morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(),
+ morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(),
pool.getPort(), pool.getPath(), pool.getUuid().replace("-", ""));
assert (morDatastore != null);
@@ -3382,7 +3397,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
return new CreateVMSnapshotAnswer(cmd, false, "");
}
}
-
+
protected Answer execute(DeleteVMSnapshotCommand cmd) {
try {
VmwareContext context = getServiceContext();
@@ -3395,7 +3410,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
return new DeleteVMSnapshotAnswer(cmd, false, "");
}
}
-
+
protected Answer execute(RevertToVMSnapshotCommand cmd){
try{
VmwareContext context = getServiceContext();
@@ -3598,7 +3613,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
if(result.first())
return new Answer(cmd);
} catch (Exception e) {
- s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to "
+ s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to "
+ VmwareHelper.getExceptionMessage(e), e);
}
return new Answer(cmd,false,"PingTestCommand failed");
@@ -3659,11 +3674,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
/*
* DestroyCommand content example
- *
+ *
* {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary",
* "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType":
* "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } }
- *
+ *
* {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary",
* "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem",
* "poolId":0,"deviceId":0 } }
@@ -3712,7 +3727,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
}
}
- }
+ }
if (s_logger.isInfoEnabled())
s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk");
@@ -3803,7 +3818,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
* NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms =
* networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) {
* s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); }
- *
+ *
* hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) {
* s_logger.warn("Unable to cleanup network due to exception, skip for next time"); }
*/
@@ -4024,21 +4039,21 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
vmConfig.setName(vmName);
vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB
vmConfig.setNumCPUs(1);
- vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString());
+ vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value());
VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
vmConfig.setFiles(fileInfo);
// Scsi controller
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
- scsiController.setSharedBus(VirtualSCSISharing.noSharing);
+ scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
scsiController.setBusNumber(0);
scsiController.setKey(1);
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
scsiControllerSpec.setDevice(scsiController);
- scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
+ scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
- vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec });
+ vmConfig.getDeviceChange().add(scsiControllerSpec );
hyperHost.createVm(vmConfig);
vmMo = hyperHost.findVmOnHyperHost(vmName);
return vmMo;
@@ -4077,11 +4092,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
new String[] {"name", "config.template", "runtime.powerState", "runtime.bootTime"});
if(ocs != null) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
String name = null;
boolean template = false;
- VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff;
+ VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF;
GregorianCalendar bootTime = null;
for(DynamicProperty prop : props) {
@@ -4091,7 +4106,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
template = (Boolean)prop.getVal();
else if(prop.getName().equals("runtime.powerState"))
powerState = (VirtualMachinePowerState)prop.getVal();
- else if(prop.getName().equals("runtime.bootTime"))
+ else if(prop.getName().equals("runtime.bootTime"))
bootTime = (GregorianCalendar)prop.getVal();
}
@@ -4099,7 +4114,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
boolean recycle = false;
// recycle stopped worker VM and VM that has been running for too long (hard-coded 10 hours for now)
- if(powerState == VirtualMachinePowerState.poweredOff)
+ if(powerState == VirtualMachinePowerState.POWERED_OFF)
recycle = true;
else if(bootTime != null && (new Date().getTime() - bootTime.getTimeInMillis() > 10*3600*1000))
recycle = true;
@@ -4203,7 +4218,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
DatastoreSummary dsSummary = dsMo.getSummary();
String address = hostMo.getHostName();
- StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().get_value(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace());
+ StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().getValue(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace());
StartupStorageCommand cmd = new StartupStorageCommand();
cmd.setName(poolUuid);
cmd.setPoolInfo(pInfo);
@@ -4241,7 +4256,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
fillHostHardwareInfo(serviceContext, cmd);
fillHostNetworkInfo(serviceContext, cmd);
fillHostDetailsInfo(serviceContext, details);
- } catch (RuntimeFault e) {
+ } catch (RuntimeFaultFaultMsg e) {
s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e);
throw new CloudRuntimeException("RuntimeFault while retrieving host info");
} catch (RemoteException e) {
@@ -4263,7 +4278,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion());
}
- private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException, Exception {
+ private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException, Exception {
VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary();
@@ -4279,7 +4294,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
cmd.setMemory(summary.getMemoryBytes());
}
- private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException {
+ private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException {
try {
VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
@@ -4315,7 +4330,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig();
- if (dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) {
+ if (dasConfig != null && dasConfig.isEnabled() != null && dasConfig.isEnabled().booleanValue()) {
details.put("NativeHA", "true");
}
}
@@ -4433,7 +4448,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
return hyperHost.findVmOnPeerHyperHost(vmName) != null;
}
- protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName,
+ protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName,
String vncPassword, String keyboardLayout) throws Exception {
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
@@ -4519,9 +4534,9 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
if (cpuArchitecture.equalsIgnoreCase("x86_64")) {
- return VirtualMachineGuestOsIdentifier.otherGuest64;
+ return VirtualMachineGuestOsIdentifier.OTHER_GUEST_64;
}
- return VirtualMachineGuestOsIdentifier.otherGuest;
+ return VirtualMachineGuestOsIdentifier.OTHER_GUEST;
}
private void prepareNetworkForVmTargetHost(HostMO hostMo, VirtualMachineMO vmMo) throws Exception {
@@ -4540,7 +4555,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
String[] tokens = networkName.split("\\.");
if (tokens.length == 3) {
Integer networkRateMbps = null;
- if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) {
+ if (shapingPolicy != null && shapingPolicy.isEnabled() != null && shapingPolicy.isEnabled().booleanValue()) {
networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024));
}
String vlanId = null;
@@ -4556,7 +4571,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
String[] tokens = networkName.split("\\.");
if (tokens.length == 3) {
Integer networkRateMbps = null;
- if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) {
+ if (shapingPolicy != null && shapingPolicy.isEnabled() != null && shapingPolicy.isEnabled().booleanValue()) {
networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024));
}
String vlanId = null;
@@ -4572,7 +4587,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
String[] tokens = networkName.split("\\.");
if (tokens.length >= 3) {
Integer networkRateMbps = null;
- if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) {
+ if (shapingPolicy != null && shapingPolicy.isEnabled() != null && shapingPolicy.isEnabled().booleanValue()) {
networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024));
}
@@ -4598,12 +4613,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
HashMap newStates = new HashMap();
if (ocs != null && ocs.length > 0) {
for (ObjectContent oc : ocs) {
- DynamicProperty[] objProps = oc.getPropSet();
+ List objProps = oc.getPropSet();
if (objProps != null) {
boolean isTemplate = false;
String name = null;
- VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff;
+ VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF;
for (DynamicProperty objProp : objProps) {
if (objProp.getName().equals("config.template")) {
if (objProp.getVal().toString().equalsIgnoreCase("true")) {
@@ -4630,19 +4645,19 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
private HashMap getVmStats(List vmNames) throws Exception {
VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
HashMap vmResponseMap = new HashMap();
- ManagedObjectReference perfMgr = getServiceContext().getServiceConnection().getServiceContent().getPerfManager();
- VimPortType service = getServiceContext().getServiceConnection().getService();
+ ManagedObjectReference perfMgr = getServiceContext().getServiceContent().getPerfManager();
+ VimPortType service = getServiceContext().getService();
PerfCounterInfo rxPerfCounterInfo = null;
PerfCounterInfo txPerfCounterInfo = null;
- PerfCounterInfo[] cInfo = (PerfCounterInfo[]) getServiceContext().getServiceUtil().getDynamicProperty(perfMgr, "perfCounter");
- for(int i=0; i cInfo = (List) getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter");
+ for(PerfCounterInfo info : cInfo) {
+ if ("net".equalsIgnoreCase(info.getGroupInfo().getKey())) {
+ if ("transmitted".equalsIgnoreCase(info.getNameInfo().getKey())) {
+ txPerfCounterInfo = info;
}
- if ("received".equalsIgnoreCase(cInfo[i].getNameInfo().getKey())) {
- rxPerfCounterInfo = cInfo[i];
+ if ("received".equalsIgnoreCase(info.getNameInfo().getKey())) {
+ rxPerfCounterInfo = info;
}
}
}
@@ -4650,7 +4665,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] {"name", "summary.config.numCpu", "summary.quickStats.overallCpuUsage"});
if (ocs != null && ocs.length > 0) {
for (ObjectContent oc : ocs) {
- DynamicProperty[] objProps = oc.getPropSet();
+ List objProps = oc.getPropSet();
if (objProps != null) {
String name = null;
String numberCPUs = null;
@@ -4674,13 +4689,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
assert(vmMor!=null);
ArrayList vmNetworkMetrics = new ArrayList();
- // get all the metrics from the available sample period
- PerfMetricId[] perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null);
+ // get all the metrics from the available sample period
+ List perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null);
if(perfMetrics != null) {
- for(int index=0; index < perfMetrics.length; ++index) {
- if ( ((rxPerfCounterInfo != null) && (perfMetrics[index].getCounterId() == rxPerfCounterInfo.getKey())) ||
- ((txPerfCounterInfo != null) && (perfMetrics[index].getCounterId() == txPerfCounterInfo.getKey())) ) {
- vmNetworkMetrics.add(perfMetrics[index]);
+ for(int index=0; index < perfMetrics.size(); ++index) {
+ if ( ((rxPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == rxPerfCounterInfo.getKey())) ||
+ ((txPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == txPerfCounterInfo.getKey())) ) {
+ vmNetworkMetrics.add(perfMetrics.get(index));
}
}
}
@@ -4693,23 +4708,26 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(vmMor);
PerfMetricId[] availableMetricIds = (PerfMetricId[]) vmNetworkMetrics.toArray(new PerfMetricId[0]);
- qSpec.setMetricId(availableMetricIds);
- PerfQuerySpec[] qSpecs = new PerfQuerySpec[] {qSpec};
- PerfEntityMetricBase[] values = service.queryPerf(perfMgr, qSpecs);
+ qSpec.getMetricId().addAll(Arrays.asList(availableMetricIds));
+ List qSpecs = new ArrayList();
+ qSpecs.add(qSpec);
+ List values = service.queryPerf(perfMgr, qSpecs);
- for(int i=0; i infos = ((PerfEntityMetric)values.get(i)).getSampleInfo();
+ int endMs = infos.get(infos.size()-1).getTimestamp().getSecond() * 1000 + infos.get(infos.size()-1).getTimestamp().getMillisecond();
+ int beginMs = infos.get(0).getTimestamp().getSecond() * 1000 + infos.get(0).getTimestamp().getMillisecond();
+ sampleDuration = (endMs - beginMs) /1000;
+ List vals = ((PerfEntityMetric)values.get(i)).getValue();
+ for(int vi = 0; ((vals!= null) && (vi < vals.size())); ++vi){
+ if(vals.get(vi) instanceof PerfMetricIntSeries) {
+ PerfMetricIntSeries val = (PerfMetricIntSeries)vals.get(vi);
+ List perfValues = val.getValue();
+ if (vals.get(vi).getId().getCounterId() == rxPerfCounterInfo.getKey()) {
+ networkReadKBs = sampleDuration * perfValues.get(3); //get the average RX rate multiplied by sampled duration
}
- if (vals[vi].getId().getCounterId() == txPerfCounterInfo.getKey()) {
- networkWriteKBs = sampleDuration * perfValues[3];//get the average TX rate multiplied by sampled duration
+ if (vals.get(vi).getId().getCounterId() == txPerfCounterInfo.getKey()) {
+ networkWriteKBs = sampleDuration * perfValues.get(3);//get the average TX rate multiplied by sampled duration
}
}
}
@@ -4719,8 +4737,8 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
}
}
}
- return vmResponseMap;
- }
+ return vmResponseMap;
+ }
protected String networkUsage(final String privateIpAddress, final String option, final String ethName) {
String args = null;
@@ -4753,7 +4771,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
return result.second();
} catch (Throwable e) {
- s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to "
+ s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to "
+ VmwareHelper.getExceptionMessage(e), e);
}
@@ -4894,7 +4912,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
_morHyperHost = new ManagedObjectReference();
String[] hostTokens = tokens[0].split(":");
_morHyperHost.setType(hostTokens[0]);
- _morHyperHost.set_value(hostTokens[1]);
+ _morHyperHost.setValue(hostTokens[1]);
_guestTrafficInfo = (VmwareTrafficLabel) params.get("guestTrafficInfo");
_publicTrafficInfo = (VmwareTrafficLabel) params.get("publicTrafficInfo");
@@ -5067,13 +5085,13 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
@Override
public void setName(String name) {
// TODO Auto-generated method stub
-
+
}
@Override
public void setConfigParams(Map params) {
// TODO Auto-generated method stub
-
+
}
@Override
@@ -5091,6 +5109,6 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
@Override
public void setRunLevel(int level) {
// TODO Auto-generated method stub
-
+
}
}
diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java
index fc298c895c8..646ef633fc7 100644
--- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageContextFactory.java
@@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
+// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.storage.resource;
@@ -20,45 +20,44 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
+import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareContext;
-import com.vmware.apputils.version.ExtendedAppUtil;
public class VmwareSecondaryStorageContextFactory {
private static volatile int s_seq = 1;
-
+
private static Map s_contextMap = new HashMap();
-
+
public static void initFactoryEnvironment() {
System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");
}
-
+
public static VmwareContext create(String vCenterAddress, String vCenterUserName, String vCenterPassword) throws Exception {
assert(vCenterAddress != null);
assert(vCenterUserName != null);
assert(vCenterPassword != null);
-
+
VmwareContext context = null;
-
+
synchronized(s_contextMap) {
context = s_contextMap.get(vCenterAddress);
if(context == null) {
String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService";
- String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword };
- ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params);
-
- appUtil.connect();
- context = new VmwareContext(appUtil, vCenterAddress);
+ //String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword };
+ VmwareClient vimClient = new VmwareClient(vCenterAddress + "-" + s_seq++);
+ vimClient.connect(serviceUrl, vCenterUserName, vCenterPassword);
+ context = new VmwareContext(vimClient, vCenterAddress);
context.registerStockObject("username", vCenterUserName);
context.registerStockObject("password", vCenterPassword);
-
+
s_contextMap.put(vCenterAddress, context);
}
}
-
+
assert(context != null);
return context;
}
-
+
public static void invalidate(VmwareContext context) {
synchronized(s_contextMap) {
for(Iterator> entryIter = s_contextMap.entrySet().iterator(); entryIter.hasNext();) {
@@ -68,7 +67,7 @@ public class VmwareSecondaryStorageContextFactory {
}
}
}
-
+
context.close();
}
}
diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java
index 2abed160dfc..566e750c3fe 100644
--- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareSecondaryStorageResourceHandler.java
@@ -11,7 +11,7 @@
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
+// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.storage.resource;
@@ -85,11 +85,11 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe
if(cmd.getContextParam("execid") != null) {
answer.setContextParam("execid", cmd.getContextParam("execid"));
}
-
+
if(cmd.getContextParam("checkpoint") != null) {
answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint"));
}
-
+
if(cmd.getContextParam("checkpoint2") != null) {
answer.setContextParam("checkpoint2", cmd.getContextParam("checkpoint2"));
}
@@ -219,23 +219,23 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe
}
morHyperHost.setType(hostTokens[0]);
- morHyperHost.set_value(hostTokens[1]);
+ morHyperHost.setValue(hostTokens[1]);
if(morHyperHost.getType().equalsIgnoreCase("HostSystem")) {
HostMO hostMo = new HostMO(context, morHyperHost);
try {
-
+
ManagedObjectReference mor = hostMo.getHyperHostCluster();
ClusterMO clusterMo = new ClusterMO(hostMo.getContext(), mor);
List> hostsInCluster = clusterMo.getClusterHosts();
for(Pair hostPair : hostsInCluster) {
HostMO hostIteratorMo = new HostMO(hostMo.getContext(), hostPair.first());
-
+
VmwareHypervisorHostNetworkSummary netSummary = hostIteratorMo.getHyperHostNetworkSummary(
hostIteratorMo.getHostType() == VmwareHostType.ESXi ? cmd.getContextParam("manageportgroup") : cmd.getContextParam("serviceconsole"));
_resource.ensureOutgoingRuleForAddress(netSummary.getHostIp());
-
+
s_logger.info("Setup firewall rule for host: " + netSummary.getHostIp());
}
} catch(Throwable e) {
@@ -253,7 +253,7 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe
public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) {
assert(cmd.getContextParam("worker") != null);
assert(workerSequence < 2);
-
+
if(workerSequence == 0)
return cmd.getContextParam("worker");
return cmd.getContextParam("worker2");
@@ -276,7 +276,7 @@ public class VmwareSecondaryStorageResourceHandler implements SecondaryStorageRe
assert(hostTokens.length == 2);
morHyperHost.setType(hostTokens[0]);
- morHyperHost.set_value(hostTokens[1]);
+ morHyperHost.setValue(hostTokens[1]);
if(morHyperHost.getType().equalsIgnoreCase("HostSystem")) {
HostMO hostMo = new HostMO(context, morHyperHost);
diff --git a/pom.xml b/pom.xml
index 3219ab0f06f..86cec1d8336 100644
--- a/pom.xml
+++ b/pom.xml
@@ -82,8 +82,8 @@
2.4
1.2
1.0-20081010.060147
+ 5.1
3.1.2.RELEASE
- 4.1
1.9.5
1.3.21.1
2.6
@@ -452,7 +452,8 @@
${cs.jdk.version}
true
128m
- 512m
+ 512m
+ -XDignore.symbol.file=true
diff --git a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java
index 0cf19fbdfff..d902dc4dbfd 100755
--- a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java
+++ b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java
@@ -48,14 +48,13 @@ import com.cloud.user.Account;
import com.cloud.utils.db.DB;
import com.cloud.utils.exception.CloudRuntimeException;
-@Component
@Local(value=TemplateAdapter.class)
public class BareMetalTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter {
private final static Logger s_logger = Logger.getLogger(BareMetalTemplateAdapter.class);
@Inject HostDao _hostDao;
@Inject ResourceManager _resourceMgr;
- @Override
+ @Override
public String getName() {
return TemplateAdapterType.BareMetal.getName();
}
@@ -63,7 +62,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
@Override
public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
-
+
if (profile.getZoneId() == null || profile.getZoneId() == -1) {
List dcs = _dcDao.listAllIncludingRemoved();
for (DataCenterVO dc : dcs) {
@@ -78,15 +77,15 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
throw new CloudRuntimeException("Please add PXE server before adding baremetal template in zone " + profile.getZoneId());
}
}
-
+
return profile;
}
-
+
@Override
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
throw new CloudRuntimeException("Baremetal doesn't support ISO template");
}
-
+
private void templateCreateUsage(VMTemplateVO template, HostVO host) {
if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_TEMPLATE_CREATE, template.getAccountId(), host.getDataCenterId(),
@@ -94,12 +93,12 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
template.getClass().getName(), template.getUuid());
}
}
-
+
@Override
public VMTemplateVO create(TemplateProfile profile) {
VMTemplateVO template = persistTemplate(profile);
Long zoneId = profile.getZoneId();
-
+
/* There is no secondary storage vm for baremetal, we use pxe server id.
* Tempalte is not bound to pxeserver right now, and we assume the pxeserver
* cannot be removed once it was added. so we use host id of first found pxe
@@ -127,7 +126,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
_tmpltHostDao.persist(vmTemplateHost);
templateCreateUsage(template, pxe);
}
-
+
_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
return template;
}
@@ -135,7 +134,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
public TemplateProfile prepareDelete(DeleteIsoCmd cmd) {
throw new CloudRuntimeException("Baremetal doesn't support ISO, how the delete get here???");
}
-
+
@Override @DB
public boolean delete(TemplateProfile profile) {
VMTemplateVO template = (VMTemplateVO)profile.getTemplate();
@@ -143,7 +142,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
boolean success = true;
String zoneName;
boolean isAllZone;
-
+
if (!template.isCrossZones() && profile.getZoneId() != null) {
isAllZone = false;
zoneName = profile.getZoneId().toString();
@@ -151,12 +150,12 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
zoneName = "all zones";
isAllZone = true;
}
-
+
s_logger.debug("Attempting to mark template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName);
Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
String eventType = EventTypes.EVENT_TEMPLATE_DELETE;
List templateHostVOs = _tmpltHostDao.listByTemplateId(templateId);
-
+
for (VMTemplateHostVO vo : templateHostVOs) {
VMTemplateHostVO lock = null;
try {
@@ -187,13 +186,13 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
}
}
}
-
+
s_logger.debug("Successfully marked template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName);
-
+
// If there are no more non-destroyed template host entries for this template, delete it
if (success && (_tmpltHostDao.listByTemplateId(templateId).size() == 0)) {
long accountId = template.getAccountId();
-
+
VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId);
try {
@@ -212,7 +211,7 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
}
s_logger.debug("Removed template: " + template.getName() + " because all of its template host refs were marked as destroyed.");
}
-
+
return success;
}
}
diff --git a/server/src/com/cloud/template/HyervisorTemplateAdapter.java b/server/src/com/cloud/template/HypervisorTemplateAdapter.java
similarity index 93%
rename from server/src/com/cloud/template/HyervisorTemplateAdapter.java
rename to server/src/com/cloud/template/HypervisorTemplateAdapter.java
index ad41af51506..142642193b6 100755
--- a/server/src/com/cloud/template/HyervisorTemplateAdapter.java
+++ b/server/src/com/cloud/template/HypervisorTemplateAdapter.java
@@ -75,10 +75,9 @@ import javax.ejb.Local;
import java.net.*;
import java.util.List;
-@Component
@Local(value=TemplateAdapter.class)
-public class HyervisorTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter {
- private final static Logger s_logger = Logger.getLogger(HyervisorTemplateAdapter.class);
+public class HypervisorTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter {
+ private final static Logger s_logger = Logger.getLogger(HypervisorTemplateAdapter.class);
@Inject DownloadMonitor _downloadMonitor;
@Inject SecondaryStorageVmManager _ssvmMgr;
@Inject AgentManager _agentMgr;
@@ -96,7 +95,7 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
private String validateUrl(String url) {
try {
URI uri = new URI(url);
- if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http")
+ if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http")
&& !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) {
throw new IllegalArgumentException("Unsupported scheme for url: " + url);
}
@@ -117,34 +116,34 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
} catch (UnknownHostException uhe) {
throw new IllegalArgumentException("Unable to resolve " + host);
}
-
+
return uri.toString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid URL " + url);
}
}
-
+
@Override
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
-
+
if((!url.toLowerCase().endsWith("iso"))&&(!url.toLowerCase().endsWith("iso.zip"))&&(!url.toLowerCase().endsWith("iso.bz2"))
&&(!url.toLowerCase().endsWith("iso.gz"))){
throw new InvalidParameterValueException("Please specify a valid iso");
}
-
+
profile.setUrl(validateUrl(url));
return profile;
}
-
+
@Override
public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
-
+
if((!url.toLowerCase().endsWith("vhd"))&&(!url.toLowerCase().endsWith("vhd.zip"))
- &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz"))
+ &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz"))
&&(!url.toLowerCase().endsWith("qcow2"))&&(!url.toLowerCase().endsWith("qcow2.zip"))
&&(!url.toLowerCase().endsWith("qcow2.bz2"))&&(!url.toLowerCase().endsWith("qcow2.gz"))
&&(!url.toLowerCase().endsWith("ova"))&&(!url.toLowerCase().endsWith("ova.zip"))
@@ -152,26 +151,26 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
&&(!url.toLowerCase().endsWith("img"))&&(!url.toLowerCase().endsWith("raw"))){
throw new InvalidParameterValueException("Please specify a valid "+ cmd.getFormat().toLowerCase());
}
-
+
if ((cmd.getFormat().equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith("vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith("vhd.gz") ))
|| (cmd.getFormat().equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith("qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz") ))
|| (cmd.getFormat().equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith("ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase().endsWith("ova.gz")))
|| (cmd.getFormat().equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith("img") && !url.toLowerCase().endsWith("raw")))) {
throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + cmd.getFormat().toLowerCase());
}
-
+
profile.setUrl(validateUrl(url));
return profile;
}
-
+
@Override
public VMTemplateVO create(TemplateProfile profile) {
VMTemplateVO template = persistTemplate(profile);
-
+
if (template == null) {
throw new CloudRuntimeException("Unable to persist the template " + profile.getTemplate());
}
-
+
DataStore imageStore = this.storeMgr.getDataStore(profile.getImageStoreId(), DataStoreRole.Image);
AsyncCallFuture future = this.imageService.createTemplateAsync(this.imageFactory.getTemplate(template.getId()), imageStore);
@@ -185,18 +184,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
throw new CloudRuntimeException("create template Failed", e);
}
_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
-
+
return template;
}
@Override @DB
public boolean delete(TemplateProfile profile) {
boolean success = true;
-
+
VMTemplateVO template = (VMTemplateVO)profile.getTemplate();
Long zoneId = profile.getZoneId();
Long templateId = template.getId();
-
+
String zoneName;
List secondaryStorageHosts;
if (!template.isCrossZones() && zoneId != null) {
@@ -207,9 +206,9 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
zoneName = "(all zones)";
secondaryStorageHosts = _ssvmMgr.listSecondaryStorageHostsInAllZones();
}
-
+
s_logger.debug("Attempting to mark template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName);
-
+
// Make sure the template is downloaded to all the necessary secondary storage hosts
for (HostVO secondaryStorageHost : secondaryStorageHosts) {
long hostId = secondaryStorageHost.getId();
@@ -222,16 +221,16 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
}
}
}
-
+
Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
String eventType = "";
-
+
if (template.getFormat().equals(ImageFormat.ISO)){
eventType = EventTypes.EVENT_ISO_DELETE;
} else {
eventType = EventTypes.EVENT_TEMPLATE_DELETE;
}
-
+
// Iterate through all necessary secondary storage hosts and mark the template on each host as destroyed
for (HostVO secondaryStorageHost : secondaryStorageHosts) {
long hostId = secondaryStorageHost.getId();
@@ -252,21 +251,21 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
List userVmUsingIso = _userVmDao.listByIsoId(templateId);
//check if there is any VM using this ISO.
if (userVmUsingIso == null || userVmUsingIso.isEmpty()) {
- if (installPath != null) {
- Answer answer = _agentMgr.sendToSecStorage(secondaryStorageHost, new DeleteTemplateCommand(secondaryStorageHost.getStorageUrl(), installPath));
+ if (installPath != null) {
+ Answer answer = _agentMgr.sendToSecStorage(secondaryStorageHost, new DeleteTemplateCommand(secondaryStorageHost.getStorageUrl(), installPath));
- if (answer == null || !answer.getResult()) {
- s_logger.debug("Failed to delete " + templateHostVO + " due to " + ((answer == null) ? "answer is null" : answer.getDetails()));
- } else {
- _tmpltHostDao.remove(templateHostVO.getId());
- s_logger.debug("Deleted template at: " + installPath);
- }
+ if (answer == null || !answer.getResult()) {
+ s_logger.debug("Failed to delete " + templateHostVO + " due to " + ((answer == null) ? "answer is null" : answer.getDetails()));
} else {
_tmpltHostDao.remove(templateHostVO.getId());
+ s_logger.debug("Deleted template at: " + installPath);
}
+ } else {
+ _tmpltHostDao.remove(templateHostVO.getId());
+ }
}
VMTemplateZoneVO templateZone = _tmpltZoneDao.findByZoneTemplate(sZoneId, templateId);
-
+
if (templateZone != null) {
_tmpltZoneDao.remove(templateZone.getId());
}
@@ -276,18 +275,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
}
}
}
-
+
if (!success) {
break;
}
}
-
+
s_logger.debug("Successfully marked template host refs for template: " + template.getName() + " as destroyed in zone: " + zoneName);
-
+
// If there are no more non-destroyed template host entries for this template, delete it
if (success && (_tmpltHostDao.listByTemplateId(templateId).size() == 0)) {
long accountId = template.getAccountId();
-
+
VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId);
try {
@@ -304,18 +303,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
_tmpltDao.releaseFromLockTable(lock.getId());
}
}
-
+
s_logger.debug("Removed template: " + template.getName() + " because all of its template host refs were marked as destroyed.");
}
-
+
return success;
}
-
+
public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
TemplateProfile profile = super.prepareDelete(cmd);
VMTemplateVO template = (VMTemplateVO)profile.getTemplate();
Long zoneId = profile.getZoneId();
-
+
if (template.getTemplateType() == TemplateType.SYSTEM) {
throw new InvalidParameterValueException("The DomR template cannot be deleted.");
}
@@ -323,18 +322,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
if (zoneId != null && (_ssvmMgr.findSecondaryStorageHost(zoneId) == null)) {
throw new InvalidParameterValueException("Failed to find a secondary storage host in the specified zone.");
}
-
+
return profile;
}
-
+
public TemplateProfile prepareDelete(DeleteIsoCmd cmd) {
TemplateProfile profile = super.prepareDelete(cmd);
Long zoneId = profile.getZoneId();
-
+
if (zoneId != null && (_ssvmMgr.findSecondaryStorageHost(zoneId) == null)) {
throw new InvalidParameterValueException("Failed to find a secondary storage host in the specified zone.");
}
-
+
return profile;
}
}
diff --git a/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java b/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java
index 8bb2a4de902..6e22e174f58 100644
--- a/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java
+++ b/server/test/com/cloud/vm/dao/UserVmCloneSettingDaoTestConfiguration.java
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-package com.cloud.storage.dao;
+package com.cloud.vm.dao;
import java.io.IOException;
diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql
index 2d024f17f5c..809e264d961 100644
--- a/setup/db/db/schema-40to410.sql
+++ b/setup/db/db/schema-40to410.sql
@@ -489,7 +489,7 @@ ALTER TABLE `cloud`.`data_center` ADD COLUMN `ip6_dns2` varchar(255);
DROP VIEW IF EXISTS `cloud`.`user_vm_view`;
CREATE VIEW `cloud`.`user_vm_view` AS
- select
+ select
vm_instance.id id,
vm_instance.name name,
user_vm.display_name display_name,
@@ -657,7 +657,7 @@ CREATE VIEW `cloud`.`user_vm_view` AS
DROP VIEW IF EXISTS `cloud`.`domain_router_view`;
CREATE VIEW `cloud`.`domain_router_view` AS
- select
+ select
vm_instance.id id,
vm_instance.name name,
account.id account_id,
@@ -761,7 +761,7 @@ CREATE VIEW `cloud`.`domain_router_view` AS
DROP VIEW IF EXISTS `cloud`.`security_group_view`;
CREATE VIEW `cloud`.`security_group_view` AS
- select
+ select
security_group.id id,
security_group.name name,
security_group.description description,
@@ -820,7 +820,7 @@ CREATE VIEW `cloud`.`security_group_view` AS
DROP VIEW IF EXISTS `cloud`.`resource_tag_view`;
CREATE VIEW `cloud`.`resource_tag_view` AS
- select
+ select
resource_tags.id,
resource_tags.uuid,
resource_tags.key,
@@ -852,7 +852,7 @@ CREATE VIEW `cloud`.`resource_tag_view` AS
DROP VIEW IF EXISTS `cloud`.`event_view`;
CREATE VIEW `cloud`.`event_view` AS
- select
+ select
event.id,
event.uuid,
event.type,
@@ -891,7 +891,7 @@ CREATE VIEW `cloud`.`event_view` AS
DROP VIEW IF EXISTS `cloud`.`instance_group_view`;
CREATE VIEW `cloud`.`instance_group_view` AS
- select
+ select
instance_group.id,
instance_group.uuid,
instance_group.name,
@@ -919,7 +919,7 @@ CREATE VIEW `cloud`.`instance_group_view` AS
DROP VIEW IF EXISTS `cloud`.`user_view`;
CREATE VIEW `cloud`.`user_view` AS
- select
+ select
user.id,
user.uuid,
user.username,
@@ -962,7 +962,7 @@ CREATE VIEW `cloud`.`user_view` AS
DROP VIEW IF EXISTS `cloud`.`project_view`;
CREATE VIEW `cloud`.`project_view` AS
- select
+ select
projects.id,
projects.uuid,
projects.name,
@@ -1003,7 +1003,7 @@ CREATE VIEW `cloud`.`project_view` AS
DROP VIEW IF EXISTS `cloud`.`project_account_view`;
CREATE VIEW `cloud`.`project_account_view` AS
- select
+ select
project_account.id,
account.id account_id,
account.uuid account_uuid,
@@ -1028,7 +1028,7 @@ CREATE VIEW `cloud`.`project_account_view` AS
DROP VIEW IF EXISTS `cloud`.`project_invitation_view`;
CREATE VIEW `cloud`.`project_invitation_view` AS
- select
+ select
project_invitations.id,
project_invitations.uuid,
project_invitations.email,
@@ -1056,7 +1056,7 @@ CREATE VIEW `cloud`.`project_invitation_view` AS
DROP VIEW IF EXISTS `cloud`.`host_view`;
CREATE VIEW `cloud`.`host_view` AS
- select
+ select
host.id,
host.uuid,
host.name,
@@ -1126,7 +1126,7 @@ CREATE VIEW `cloud`.`host_view` AS
DROP VIEW IF EXISTS `cloud`.`volume_view`;
CREATE VIEW `cloud`.`volume_view` AS
- select
+ select
volumes.id,
volumes.uuid,
volumes.name,
@@ -1227,7 +1227,7 @@ CREATE VIEW `cloud`.`volume_view` AS
DROP VIEW IF EXISTS `cloud`.`account_netstats_view`;
CREATE VIEW `cloud`.`account_netstats_view` AS
- SELECT
+ SELECT
account_id,
sum(net_bytes_received) + sum(current_bytes_received) as bytesReceived,
sum(net_bytes_sent) + sum(current_bytes_sent) as bytesSent
@@ -1238,7 +1238,7 @@ CREATE VIEW `cloud`.`account_netstats_view` AS
DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`;
CREATE VIEW `cloud`.`account_vmstats_view` AS
- SELECT
+ SELECT
account_id, state, count(*) as vmcount
from
`cloud`.`vm_instance`
@@ -1246,7 +1246,7 @@ CREATE VIEW `cloud`.`account_vmstats_view` AS
DROP VIEW IF EXISTS `cloud`.`free_ip_view`;
CREATE VIEW `cloud`.`free_ip_view` AS
- select
+ select
count(user_ip_address.id) free_ip
from
`cloud`.`user_ip_address`
@@ -1258,7 +1258,7 @@ CREATE VIEW `cloud`.`free_ip_view` AS
DROP VIEW IF EXISTS `cloud`.`account_view`;
CREATE VIEW `cloud`.`account_view` AS
- select
+ select
account.id,
account.uuid,
account.account_name,
@@ -1385,7 +1385,7 @@ CREATE VIEW `cloud`.`account_view` AS
DROP VIEW IF EXISTS `cloud`.`async_job_view`;
CREATE VIEW `cloud`.`async_job_view` AS
- select
+ select
account.id account_id,
account.uuid account_uuid,
account.account_name account_name,
@@ -1494,7 +1494,7 @@ CREATE VIEW `cloud`.`async_job_view` AS
DROP VIEW IF EXISTS `cloud`.`storage_pool_view`;
CREATE VIEW `cloud`.`storage_pool_view` AS
- select
+ select
storage_pool.id,
storage_pool.uuid,
storage_pool.name,
@@ -1543,7 +1543,7 @@ CREATE VIEW `cloud`.`storage_pool_view` AS
DROP VIEW IF EXISTS `cloud`.`disk_offering_view`;
CREATE VIEW `cloud`.`disk_offering_view` AS
- select
+ select
disk_offering.id,
disk_offering.uuid,
disk_offering.name,
@@ -1568,7 +1568,7 @@ CREATE VIEW `cloud`.`disk_offering_view` AS
DROP VIEW IF EXISTS `cloud`.`service_offering_view`;
CREATE VIEW `cloud`.`service_offering_view` AS
- select
+ select
service_offering.id,
disk_offering.uuid,
disk_offering.name,
@@ -1599,10 +1599,10 @@ CREATE VIEW `cloud`.`service_offering_view` AS
`cloud`.`disk_offering` ON service_offering.id = disk_offering.id
left join
`cloud`.`domain` ON disk_offering.domain_id = domain.id;
-
+
DROP VIEW IF EXISTS `cloud`.`data_center_view`;
CREATE VIEW `cloud`.`data_center_view` AS
- select
+ select
data_center.id,
data_center.uuid,
data_center.name,
@@ -1629,8 +1629,8 @@ CREATE VIEW `cloud`.`data_center_view` AS
from
`cloud`.`data_center`
left join
- `cloud`.`domain` ON data_center.domain_id = domain.id;
-
+ `cloud`.`domain` ON data_center.domain_id = domain.id;
+
CREATE TABLE `cloud`.`baremetal_dhcp_devices` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
@@ -1640,7 +1640,7 @@ CREATE TABLE `cloud`.`baremetal_dhcp_devices` (
`device_type` varchar(255) DEFAULT NULL COMMENT 'type of the external device',
`physical_network_id` bigint unsigned DEFAULT NULL COMMENT 'id of the physical network in to which external dhcp device is added',
`host_id` bigint unsigned DEFAULT NULL COMMENT 'host id coresponding to the external dhcp device',
- PRIMARY KEY (`id`)
+ PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`baremetal_pxe_devices` (
@@ -1651,9 +1651,10 @@ CREATE TABLE `cloud`.`baremetal_pxe_devices` (
`device_type` varchar(255) DEFAULT NULL COMMENT 'type of the pxe device',
`physical_network_id` bigint unsigned DEFAULT NULL COMMENT 'id of the physical network in to which external pxe device is added',
`host_id` bigint unsigned DEFAULT NULL COMMENT 'host id coresponding to the external pxe device',
- PRIMARY KEY (`id`)
+ PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
CREATE TABLE `cloud`.`ucs_blade` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`uuid` varchar(40) UNIQUE,
diff --git a/setup/db/db/schema-410to420.sql b/setup/db/db/schema-410to420.sql
index 6f68e120ac1..f3112a1da27 100644
--- a/setup/db/db/schema-410to420.sql
+++ b/setup/db/db/schema-410to420.sql
@@ -101,6 +101,13 @@ CREATE TABLE `vpc_service_map` (
INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'vm.instancename.flag', 'false', 'Append guest VM display Name (if set) to the internal name of the VM');
+INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (208, UUID(), 6, 'Windows 8');
+INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (209, UUID(), 6, 'Windows 8 (64 bit)');
+INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (210, UUID(), 6, 'Windows 8 Server (64 bit)');
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8', 208);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8 (64 bit)', 209);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Windows 8 Server (64 bit)', 210);
+
CREATE TABLE `cloud`.`user_vm_clone_setting` (
`vm_id` bigint unsigned NOT NULL COMMENT 'guest VM id',
`clone_type` varchar(10) NOT NULL COMMENT 'Full or Linked Clone (applicable to VMs on ESX)',
diff --git a/vmware-base/pom.xml b/vmware-base/pom.xml
index 765182baee4..8fa811fb3f2 100644
--- a/vmware-base/pom.xml
+++ b/vmware-base/pom.xml
@@ -43,18 +43,6 @@
${cs.vmware.api.version}
compile
-
- com.cloud.com.vmware
- vmware-vim
- ${cs.vmware.api.version}
- compile
-
-
- com.cloud.com.vmware
- vmware-apputils
- ${cs.vmware.api.version}
- compile
-
org.apache.axis
axis
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java
index ff7e00436ea..0ac93e4cd6a 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/BaseMO.java
@@ -25,55 +25,55 @@ import com.vmware.vim25.ManagedObjectReference;
public class BaseMO {
private static final Logger s_logger = Logger.getLogger(BaseMO.class);
-
+
protected VmwareContext _context;
protected ManagedObjectReference _mor;
private String _name;
-
+
public BaseMO(VmwareContext context, ManagedObjectReference mor) {
assert(context != null);
-
+
_context = context;
_mor = mor;
}
-
+
public BaseMO(VmwareContext context, String morType, String morValue) {
assert(context != null);
assert(morType != null);
assert(morValue != null);
-
+
_context = context;
_mor = new ManagedObjectReference();
_mor.setType(morType);
- _mor.set_value(morValue);
+ _mor.setValue(morValue);
}
-
+
public VmwareContext getContext() {
return _context;
}
-
+
public ManagedObjectReference getMor() {
assert(_mor != null);
return _mor;
}
-
+
public ManagedObjectReference getParentMor() throws Exception {
- return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "parent");
+ return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "parent");
}
public String getName() throws Exception {
if(_name == null)
- _name = (String)_context.getServiceUtil().getDynamicProperty(_mor, "name");
-
+ _name = (String)_context.getVimClient().getDynamicProperty(_mor, "name");
+
return _name;
}
-
+
public boolean destroy() throws Exception {
- ManagedObjectReference morTask = _context.getService().destroy_Task(_mor);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().destroyTask(_mor);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -81,16 +81,16 @@ public class BaseMO {
}
return false;
}
-
+
public void reload() throws Exception {
_context.getService().reload(_mor);
}
-
+
public boolean rename(String newName) throws Exception {
- ManagedObjectReference morTask = _context.getService().rename_Task(_mor, newName);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().renameTask(_mor, newName);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -98,11 +98,11 @@ public class BaseMO {
}
return false;
}
-
+
public void setCustomFieldValue(String fieldName, String value) throws Exception {
- CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
+ CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
_context.getServiceContent().getCustomFieldsManager());
-
+
int key = getCustomFieldKey(fieldName);
if(key == 0) {
try {
@@ -114,36 +114,36 @@ public class BaseMO {
key = getCustomFieldKey(fieldName);
}
}
-
+
if(key == 0)
throw new Exception("Unable to setup custom field facility");
-
+
cfmMo.setField(getMor(), key, value);
}
-
+
public String getCustomFieldValue(String fieldName) throws Exception {
int key = getCustomFieldKey(fieldName);
if(key == 0)
return null;
-
- CustomFieldStringValue cfValue = (CustomFieldStringValue)_context.getServiceUtil().getDynamicProperty(getMor(),
+
+ CustomFieldStringValue cfValue = (CustomFieldStringValue)_context.getVimClient().getDynamicProperty(getMor(),
String.format("value[%d]", key));
if(cfValue != null)
return cfValue.getValue();
-
+
return null;
}
-
+
public int getCustomFieldKey(String fieldName) throws Exception {
return getCustomFieldKey(getMor().getType(), fieldName);
}
-
+
public int getCustomFieldKey(String morType, String fieldName) throws Exception {
assert(morType != null);
-
- CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
+
+ CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
_context.getServiceContent().getCustomFieldsManager());
-
+
return cfmMo.getCustomFieldKey(morType, fieldName);
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java
index 2ce6695befb..d112c34fb9e 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/ClusterMO.java
@@ -26,7 +26,6 @@ import org.apache.log4j.Logger;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.utils.Pair;
import com.google.gson.Gson;
-import com.vmware.apputils.vim25.ServiceUtil;
import com.vmware.vim25.ArrayOfHostIpRouteEntry;
import com.vmware.vim25.ClusterComputeResourceSummary;
import com.vmware.vim25.ClusterConfigInfoEx;
@@ -47,24 +46,25 @@ import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.OptionValue;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
-import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.VirtualMachineConfigSpec;
+import edu.emory.mathcs.backport.java.util.Arrays;
+
//
// interface. This has changed as ClusterMO no longer works as a special host anymore. Need to refactor accordingly
//
public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
private static final Logger s_logger = Logger.getLogger(ClusterMO.class);
-
+
public ClusterMO(VmwareContext context, ManagedObjectReference morCluster) {
super(context, morCluster);
}
-
+
public ClusterMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
@Override
public String getHyperHostName() throws Exception {
return getName();
@@ -73,40 +73,39 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
@Override
public ClusterDasConfigInfo getDasConfig() throws Exception {
// Note getDynamicProperty() with "configurationEx.dasConfig" does not work here because of that dasConfig is a property in subclass
- ClusterConfigInfoEx configInfo = (ClusterConfigInfoEx)_context.getServiceUtil().getDynamicProperty(_mor, "configurationEx");
+ ClusterConfigInfoEx configInfo = (ClusterConfigInfoEx)_context.getVimClient().getDynamicProperty(_mor, "configurationEx");
return configInfo.getDasConfig();
}
-
+
@Override
public ManagedObjectReference getHyperHostDatacenter() throws Exception {
Pair dcPair = DatacenterMO.getOwnerDatacenter(getContext(), getMor());
assert(dcPair != null);
return dcPair.first().getMor();
}
-
+
@Override
public ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception {
- ServiceUtil serviceUtil = _context.getServiceUtil();
- return (ManagedObjectReference)serviceUtil.getDynamicProperty(getMor(), "resourcePool");
+ return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(getMor(), "resourcePool");
}
-
+
@Override
public ManagedObjectReference getHyperHostCluster() throws Exception {
return _mor;
}
-
+
@Override
public VirtualMachineMO findVmOnHyperHost(String name) throws Exception {
ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] { "name" });
return HypervisorHostHelper.findVmFromObjectContent(_context, ocs, name);
}
-
+
@Override
public VirtualMachineMO findVmOnPeerHyperHost(String name) throws Exception {
ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] { "name" });
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
for(DynamicProperty prop : props) {
if(prop.getVal().toString().equals(name))
@@ -117,54 +116,54 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
}
return null;
}
-
+
@Override
public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths));
-
+ s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths));
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
- pSpec.setPathSet(propertyPaths);
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
TraversalSpec host2VmFolderTraversal = new TraversalSpec();
host2VmFolderTraversal.setType("HostSystem");
host2VmFolderTraversal.setPath("vm");
host2VmFolderTraversal.setName("host2VmFolderTraversal");
-
+
TraversalSpec cluster2HostFolderTraversal = new TraversalSpec();
cluster2HostFolderTraversal.setType("ClusterComputeResource");
cluster2HostFolderTraversal.setPath("host");
cluster2HostFolderTraversal.setName("cluster2HostFolderTraversal");
- cluster2HostFolderTraversal.setSelectSet(new SelectionSpec[] { host2VmFolderTraversal });
-
+ cluster2HostFolderTraversal.getSelectSet().add(host2VmFolderTraversal);
+
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(getMor());
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { cluster2HostFolderTraversal });
-
+ oSpec.getSelectSet().add(cluster2HostFolderTraversal);
+
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] properties = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List properties = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
- return properties;
+ return properties.toArray(new ObjectContent[properties.size()]);
}
@Override
public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths));
-
+ s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths));
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datastore");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec cluster2DatastoreTraversal = new TraversalSpec();
cluster2DatastoreTraversal.setType("ClusterComputeResource");
cluster2DatastoreTraversal.setPath("datastore");
@@ -173,29 +172,30 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { cluster2DatastoreTraversal });
+ oSpec.getSelectSet().add(cluster2DatastoreTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] properties = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List properties = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
- return properties;
+ return properties.toArray(new ObjectContent[properties.size()]);
}
-
+
private ObjectContent[] getHostPropertiesOnCluster(String[] propertyPaths) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - retrieveProperties() on Host properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths));
+ s_logger.trace("vCenter API trace - retrieveProperties() on Host properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths));
PropertySpec pSpec = new PropertySpec();
pSpec.setType("HostSystem");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec cluster2HostTraversal = new TraversalSpec();
cluster2HostTraversal.setType("ClusterComputeResource");
cluster2HostTraversal.setPath("host");
@@ -204,63 +204,65 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { cluster2HostTraversal });
+ oSpec.getSelectSet().add(cluster2HostTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] properties = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List properties = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
- return properties;
+ return properties.toArray(new ObjectContent[properties.size()]);
}
@Override
public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.get_value() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec));
-
+ s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.getValue() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec));
+
assert(vmSpec != null);
DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter());
ManagedObjectReference morPool = getHyperHostOwnerResourcePool();
-
- ManagedObjectReference morTask = _context.getService().createVM_Task(
+
+ ManagedObjectReference morTask = _context.getService().createVMTask(
dcMo.getVmFolder(), vmSpec, morPool, null);
- String result = _context.getServiceUtil().waitForTask(morTask);
-
- if(result.equals("sucess")) {
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(result) {
_context.waitForTaskProgressDone(morTask);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - createVM_Task() done(successfully)");
return true;
} else {
s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - createVM_Task() done(failed)");
return false;
}
-
+
@Override
public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.get_value() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName
- + ", datastore: " + dsMo.getMor().get_value() + ", diskOption: " + diskOption);
+ s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName
+ + ", datastore: " + dsMo.getMor().getValue() + ", diskOption: " + diskOption);
ManagedObjectReference morRp = getHyperHostOwnerResourcePool();
assert(morRp != null);
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.get_value());
-
+ s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.getValue());
+
HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, null);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - importVmFromOVF() done");
}
@@ -268,83 +270,83 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
@Override
public boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB,
String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception {
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.get_value() + ", vmName: " + vmName + ", cpuCount: " + cpuCount
- + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB
- + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.get_value() + ", snapshotDirToParent: " + snapshotDirToParent);
-
+ s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount
+ + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB
+ + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent);
+
boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse,
memoryMB, memoryReserveMB, guestOsIdentifier, morDs, snapshotDirToParent);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - createBlankVm() done");
-
+
return result;
}
@Override
- public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress,
+ public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress,
int poolHostPort, String poolPath, String poolUuid) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress
+ s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress
+ ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid);
-
+
ManagedObjectReference morDs = null;
ManagedObjectReference morDsFirst = null;
- ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
- if(hosts != null && hosts.length > 0) {
+ List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host");
+ if(hosts != null && hosts.size() > 0) {
for(ManagedObjectReference morHost : hosts) {
HostMO hostMo = new HostMO(_context, morHost);
morDs = hostMo.mountDatastore(vmfsDatastore, poolHostAddress, poolHostPort, poolPath, poolUuid);
if(morDsFirst == null)
morDsFirst = morDs;
-
+
// assume datastore is in scope of datacenter
- assert(morDsFirst.get_value().equals(morDs.get_value()));
+ assert(morDsFirst.getValue().equals(morDs.getValue()));
}
}
-
+
if(morDs == null) {
String msg = "Failed to mount datastore in all hosts within the cluster";
s_logger.error(msg);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - mountDatastore() done(failed)");
throw new Exception(msg);
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - mountDatastore() done(successfully)");
-
+
return morDs;
}
-
+
@Override
public void unmountDatastore(String poolUuid) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid);
-
- ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
- if(hosts != null && hosts.length > 0) {
+ s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid);
+
+ List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host");
+ if(hosts != null && hosts.size() > 0) {
for(ManagedObjectReference morHost : hosts) {
HostMO hostMo = new HostMO(_context, morHost);
hostMo.unmountDatastore(poolUuid);
}
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - unmountDatastore() done");
}
-
+
@Override
public ManagedObjectReference findDatastore(String poolUuid) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - findDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid);
-
- CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
+ s_logger.trace("vCenter API trace - findDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid);
+
+ CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
_context.getServiceContent().getCustomFieldsManager());
int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID);
assert(key != 0);
@@ -352,16 +354,16 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"name", String.format("value[%d]", key)});
if(ocs != null) {
for(ObjectContent oc : ocs) {
- if(oc.getPropSet(0).getVal().equals(poolUuid))
+ if(oc.getPropSet().get(0).getVal().equals(poolUuid))
return oc.getObj();
-
- if(oc.getPropSet().length > 1) {
- DynamicProperty prop = oc.getPropSet(1);
+
+ if(oc.getPropSet().size() > 1) {
+ DynamicProperty prop = oc.getPropSet().get(1);
if(prop != null && prop.getVal() != null) {
if(prop.getVal() instanceof CustomFieldStringValue) {
String val = ((CustomFieldStringValue)prop.getVal()).getValue();
if(val.equalsIgnoreCase(poolUuid)) {
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - findDatastore() done(successfully)");
return oc.getObj();
@@ -371,31 +373,31 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
}
}
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - findDatastore() done(failed)");
return null;
}
-
+
@Override
public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - findDatastoreByExportPath(). target MOR: " + _mor.get_value() + ", exportPath: " + exportPath);
-
+ s_logger.trace("vCenter API trace - findDatastoreByExportPath(). target MOR: " + _mor.getValue() + ", exportPath: " + exportPath);
+
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"info"});
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet(0).getVal();
+ DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet().get(0).getVal();
if(dsInfo != null && dsInfo instanceof NasDatastoreInfo) {
NasDatastoreInfo info = (NasDatastoreInfo)dsInfo;
if(info != null) {
String vmwareUrl = info.getUrl();
if(vmwareUrl.charAt(vmwareUrl.length() - 1) == '/')
vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1);
-
+
URI uri = new URI(vmwareUrl);
if(uri.getPath().equals("/" + exportPath)) {
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(successfully)");
return oc.getObj();
@@ -404,49 +406,49 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
}
}
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(failed)");
return null;
}
-
+
@Override
public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.get_value() + ", vm: " + vmMo.getName());
+ s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.getValue() + ", vm: " + vmMo.getName());
- ClusterHostRecommendation[] candidates = recommendHostsForVm(vmMo);
- if(candidates != null && candidates.length > 0) {
+ List candidates = recommendHostsForVm(vmMo);
+ if(candidates != null && candidates.size() > 0) {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - findMigrationTarget() done(successfully)");
- return candidates[0].getHost();
+ return candidates.get(0).getHost();
}
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - findMigrationTarget() done(failed)");
return null;
}
-
+
@Override
public boolean isHyperHostConnected() throws Exception {
ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"runtime"});
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)oc.getPropSet(0).getVal();
- // as long as we have one host connected, we assume the cluster is up
- if(runtimeInfo.getConnectionState() == HostSystemConnectionState.connected)
+ HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)oc.getPropSet().get(0).getVal();
+ // as long as we have one host connected, we assume the cluster is up
+ if(runtimeInfo.getConnectionState() == HostSystemConnectionState.CONNECTED)
return true;
}
}
return false;
}
-
+
@Override
public String getHyperHostDefaultGateway() throws Exception {
ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"config.network.routeTableInfo.ipRoute"});
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- ArrayOfHostIpRouteEntry entries = (ArrayOfHostIpRouteEntry)oc.getPropSet(0).getVal();
+ ArrayOfHostIpRouteEntry entries = (ArrayOfHostIpRouteEntry)oc.getPropSet().get(0).getVal();
if(entries != null) {
for(HostIpRouteEntry entry : entries.getHostIpRouteEntry()) {
if(entry.getNetwork().equalsIgnoreCase("0.0.0.0"))
@@ -455,28 +457,28 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
}
}
}
-
+
throw new Exception("Could not find host default gateway, host is not properly configured?");
}
-
+
@Override
public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.get_value());
+ s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.getValue());
VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary();
-
- ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getServiceUtil().getDynamicProperty(
+
+ ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getVimClient().getDynamicProperty(
_mor, "summary");
-
- // TODO, need to use traversal to optimize retrieve of
+
+ // TODO, need to use traversal to optimize retrieve of
int cpuNumInCpuThreads = 1;
- ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
- if(hosts != null && hosts.length > 0) {
+ List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host");
+ if(hosts != null && hosts.size() > 0) {
for(ManagedObjectReference morHost : hosts) {
HostMO hostMo = new HostMO(_context, morHost);
HostHardwareSummary hardwareSummary = hostMo.getHostHardwareSummary();
-
+
if(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuThreads() > cpuNumInCpuThreads)
cpuNumInCpuThreads = hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuThreads();
}
@@ -484,74 +486,74 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
summary.setCpuCount(cpuNumInCpuThreads);
summary.setCpuSpeed(vmwareSummary.getTotalCpu());
summary.setMemoryBytes(vmwareSummary.getTotalMemory());
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done");
return summary;
}
-
+
@Override
public VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String esxServiceConsolePort) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.get_value() + ", mgmtPortgroup: " + esxServiceConsolePort);
-
- ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
- if(hosts != null && hosts.length > 0) {
- VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts[0]).getHyperHostNetworkSummary(esxServiceConsolePort);
-
+ s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + esxServiceConsolePort);
+
+ List hosts = (List)_context.getVimClient().getDynamicProperty(_mor, "host");
+ if(hosts != null && hosts.size() > 0) {
+ VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts.get(0)).getHyperHostNetworkSummary(esxServiceConsolePort);
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(successfully)");
return summary;
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(failed)");
return null;
}
-
+
@Override
public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.get_value());
+ s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.getValue());
ClusterComputeResourceSummary hardwareSummary = (ClusterComputeResourceSummary)
- _context.getServiceUtil().getDynamicProperty(_mor, "summary");
+ _context.getVimClient().getDynamicProperty(_mor, "summary");
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostHardwareSummary() done");
return hardwareSummary;
}
- public ClusterHostRecommendation[] recommendHostsForVm(VirtualMachineMO vmMo) throws Exception {
- return _context.getService().recommendHostsForVm(_mor, vmMo.getMor(),
+ public List recommendHostsForVm(VirtualMachineMO vmMo) throws Exception {
+ return _context.getService().recommendHostsForVm(_mor, vmMo.getMor(),
getHyperHostOwnerResourcePool());
}
-
+
public List> getClusterHosts() throws Exception {
List> hosts = new ArrayList>();
-
+
ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"name"});
if(ocs != null) {
for(ObjectContent oc : ocs) {
ManagedObjectReference morHost = oc.getObj();
- String name = (String)oc.getPropSet(0).getVal();
-
+ String name = (String)oc.getPropSet().get(0).getVal();
+
hosts.add(new Pair(morHost, name));
}
}
return hosts;
}
-
+
public HashMap getVmVncPortsOnCluster() throws Exception {
ObjectContent[] ocs = getVmPropertiesOnHyperHost(
new String[] { "name", "config.extraConfig[\"RemoteDisplay.vnc.port\"]" }
);
-
+
HashMap portInfo = new HashMap();
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] objProps = oc.getPropSet();
+ List objProps = oc.getPropSet();
if(objProps != null) {
String name = null;
String value = null;
@@ -561,16 +563,16 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
} else {
OptionValue optValue = (OptionValue)objProp.getVal();
value = (String)optValue.getValue();
- }
+ }
}
-
+
if(name != null && value != null) {
portInfo.put(name, Integer.parseInt(value));
}
}
}
}
-
+
return portInfo;
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java
index 44de683bb05..3082a7143b5 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/CustomFieldsManagerMO.java
@@ -16,6 +16,8 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
+import java.util.List;
+
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.CustomFieldDef;
import com.vmware.vim25.ManagedObjectReference;
@@ -26,34 +28,34 @@ public class CustomFieldsManagerMO extends BaseMO {
public CustomFieldsManagerMO(VmwareContext context, ManagedObjectReference mor) {
super(context, mor);
}
-
+
public CustomFieldsManagerMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
- public CustomFieldDef addCustomerFieldDef(String fieldName, String morType,
+
+ public CustomFieldDef addCustomerFieldDef(String fieldName, String morType,
PrivilegePolicyDef fieldDefPolicy, PrivilegePolicyDef fieldPolicy) throws Exception {
return _context.getService().addCustomFieldDef(getMor(), fieldName, morType, fieldDefPolicy, fieldPolicy);
}
-
+
public void removeCustomFieldDef(int key) throws Exception {
_context.getService().removeCustomFieldDef(getMor(), key);
}
-
+
public void renameCustomFieldDef(int key, String name) throws Exception {
_context.getService().renameCustomFieldDef(getMor(), key, name);
}
-
+
public void setField(ManagedObjectReference morEntity, int key, String value) throws Exception {
_context.getService().setField(getMor(), morEntity, key, value);
}
-
- public CustomFieldDef[] getFields() throws Exception {
- return (CustomFieldDef[])_context.getServiceUtil().getDynamicProperty(getMor(), "field");
+
+ public List getFields() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(getMor(), "field");
}
-
+
public int getCustomFieldKey(String morType, String fieldName) throws Exception {
- CustomFieldDef[] fields = getFields();
+ List fields = getFields();
if(fields != null) {
for(CustomFieldDef field : fields) {
if(field.getName().equals(fieldName) && field.getManagedObjectType().equals(morType))
@@ -62,12 +64,12 @@ public class CustomFieldsManagerMO extends BaseMO {
}
return 0;
}
-
+
public int ensureCustomFieldDef(String morType, String fieldName) throws Exception {
int key = getCustomFieldKey(morType, fieldName);
if(key > 0)
return key;
-
+
try {
CustomFieldDef field = addCustomerFieldDef(fieldName, morType, null, null);
return field.getKey();
@@ -75,10 +77,10 @@ public class CustomFieldsManagerMO extends BaseMO {
// assuming that someone is adding it
key = getCustomFieldKey(morType, fieldName);
}
-
+
if(key == 0)
throw new Exception("Unable to setup custom field facility for " + morType + ":" + fieldName);
-
+
return key;
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java
index 9f75bd6298a..0a3e20ba8aa 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatacenterMO.java
@@ -22,7 +22,6 @@ import java.util.List;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.utils.Pair;
-import com.vmware.apputils.vim25.ServiceUtil;
import com.vmware.vim25.CustomFieldStringValue;
import com.vmware.vim25.DVPortgroupConfigInfo;
import com.vmware.vim25.DistributedVirtualSwitchPortConnection;
@@ -34,59 +33,58 @@ import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.TraversalSpec;
-import com.vmware.vim25.VirtualDeviceBackingInfo;
import com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo;
-import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo;
+import edu.emory.mathcs.backport.java.util.Arrays;
public class DatacenterMO extends BaseMO {
-
+
public DatacenterMO(VmwareContext context, ManagedObjectReference morDc) {
super(context, morDc);
}
-
+
public DatacenterMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public DatacenterMO(VmwareContext context, String dcName) throws Exception {
super(context, null);
-
- _mor = _context.getServiceUtil().getDecendentMoRef(_context.getRootFolder(), "Datacenter", dcName);
+
+ _mor = _context.getVimClient().getDecendentMoRef(_context.getRootFolder(), "Datacenter", dcName);
assert(_mor != null);
}
-
- public String getName() throws Exception {
- return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name");
+
+ @Override
+ public String getName() throws Exception {
+ return (String)_context.getVimClient().getDynamicProperty(_mor, "name");
}
-
- public void registerTemplate(ManagedObjectReference morHost, String datastoreName,
+
+ public void registerTemplate(ManagedObjectReference morHost, String datastoreName,
String templateName, String templateFileName) throws Exception {
-
- ServiceUtil serviceUtil = _context.getServiceUtil();
-
- ManagedObjectReference morFolder = (ManagedObjectReference)serviceUtil.getDynamicProperty(
+
+
+ ManagedObjectReference morFolder = (ManagedObjectReference)_context.getVimClient().getDynamicProperty(
_mor, "vmFolder");
assert(morFolder != null);
-
- ManagedObjectReference morTask = _context.getService().registerVM_Task(
- morFolder,
+
+ ManagedObjectReference morTask = _context.getService().registerVMTask(
+ morFolder,
String.format("[%s] %s/%s", datastoreName, templateName, templateFileName),
- templateName, true,
+ templateName, true,
null, morHost);
-
- String result = serviceUtil.waitForTask(morTask);
- if (!result.equalsIgnoreCase("Sucess")) {
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if (!result) {
throw new Exception("Unable to register template due to " + TaskMO.getTaskFailureInfo(_context, morTask));
} else {
_context.waitForTaskProgressDone(morTask);
}
}
-
+
public VirtualMachineMO findVm(String vmName) throws Exception {
- ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" });
- if(ocs != null && ocs.length > 0) {
+ List ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" });
+ if(ocs != null && ocs.size() > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
for(DynamicProperty prop : props) {
if(prop.getVal().toString().equals(vmName))
@@ -97,19 +95,19 @@ public class DatacenterMO extends BaseMO {
}
return null;
}
-
+
public List findVmByNameAndLabel(String vmLabel) throws Exception {
- CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
+ CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
_context.getServiceContent().getCustomFieldsManager());
int key = cfmMo.getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_UUID);
assert(key != 0);
-
+
List list = new ArrayList();
-
- ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name", String.format("value[%d]", key)});
- if(ocs != null && ocs.length > 0) {
+
+ List ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name", String.format("value[%d]", key)});
+ if(ocs != null && ocs.size() > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
for(DynamicProperty prop : props) {
if(prop.getVal() != null) {
@@ -135,209 +133,217 @@ public class DatacenterMO extends BaseMO {
public List> getAllVmsOnDatacenter() throws Exception {
List> vms = new ArrayList>();
-
- ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" });
+
+ List ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" });
if(ocs != null) {
for(ObjectContent oc : ocs) {
- String vmName = oc.getPropSet(0).getVal().toString();
+ String vmName = oc.getPropSet().get(0).getVal().toString();
vms.add(new Pair(oc.getObj(), vmName));
}
}
-
+
return vms;
- }
-
+ }
+
public ManagedObjectReference findDatastore(String name) throws Exception {
assert(name != null);
-
- ObjectContent[] ocs = getDatastorePropertiesOnDatacenter(new String[] { "name" });
+
+ List ocs = getDatastorePropertiesOnDatacenter(new String[] { "name" });
if(ocs != null) {
for(ObjectContent oc : ocs) {
- if(oc.getPropSet(0).getVal().toString().equals(name)) {
+ if(oc.getPropSet().get(0).getVal().toString().equals(name)) {
return oc.getObj();
}
}
}
return null;
}
-
+
public ManagedObjectReference findHost(String name) throws Exception {
- ObjectContent[] ocs= getHostPropertiesOnDatacenterHostFolder(new String[] { "name" });
-
+ List ocs= getHostPropertiesOnDatacenterHostFolder(new String[] { "name" });
+
if(ocs != null) {
for(ObjectContent oc : ocs) {
- if(oc.getPropSet(0).getVal().toString().equals(name)) {
+ if(oc.getPropSet().get(0).getVal().toString().equals(name)) {
return oc.getObj();
}
}
}
return null;
}
-
+
public ManagedObjectReference getVmFolder() throws Exception {
- return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "vmFolder");
+ return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "vmFolder");
}
-
- public ObjectContent[] getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception {
+
+ public List getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("HostSystem");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec computeResource2HostTraversal = new TraversalSpec();
computeResource2HostTraversal.setType("ComputeResource");
computeResource2HostTraversal.setPath("host");
computeResource2HostTraversal.setName("computeResource2HostTraversal");
-
+
SelectionSpec recurseFolders = new SelectionSpec();
recurseFolders.setName("folder2childEntity");
-
+
TraversalSpec folder2childEntity = new TraversalSpec();
folder2childEntity.setType("Folder");
folder2childEntity.setPath("childEntity");
folder2childEntity.setName(recurseFolders.getName());
- folder2childEntity.setSelectSet(new SelectionSpec[] { recurseFolders, computeResource2HostTraversal });
-
+ folder2childEntity.getSelectSet().add(recurseFolders);
+ folder2childEntity.getSelectSet().add(computeResource2HostTraversal);
+
TraversalSpec dc2HostFolderTraversal = new TraversalSpec();
dc2HostFolderTraversal.setType("Datacenter");
dc2HostFolderTraversal.setPath("hostFolder");
dc2HostFolderTraversal.setName("dc2HostFolderTraversal");
- dc2HostFolderTraversal.setSelectSet(new SelectionSpec[] { folder2childEntity } );
-
+ dc2HostFolderTraversal.getSelectSet().add(folder2childEntity);
+
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { dc2HostFolderTraversal });
+ oSpec.getSelectSet().add(dc2HostFolderTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- return _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
+
}
-
- public ObjectContent[] getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception {
-
+
+ public List getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception {
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datastore");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec dc2DatastoreTraversal = new TraversalSpec();
dc2DatastoreTraversal.setType("Datacenter");
dc2DatastoreTraversal.setPath("datastore");
dc2DatastoreTraversal.setName("dc2DatastoreTraversal");
-
+
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { dc2DatastoreTraversal });
+ oSpec.getSelectSet().add(dc2DatastoreTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- return _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
+
}
-
- public ObjectContent[] getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception {
+
+ public List getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec dc2VmFolderTraversal = new TraversalSpec();
dc2VmFolderTraversal.setType("Datacenter");
dc2VmFolderTraversal.setPath("vmFolder");
dc2VmFolderTraversal.setName("dc2VmFolderTraversal");
-
+
+
SelectionSpec recurseFolders = new SelectionSpec();
recurseFolders.setName("folder2childEntity");
-
+
TraversalSpec folder2childEntity = new TraversalSpec();
folder2childEntity.setType("Folder");
folder2childEntity.setPath("childEntity");
folder2childEntity.setName(recurseFolders.getName());
- folder2childEntity.setSelectSet(new SelectionSpec[] { recurseFolders });
- dc2VmFolderTraversal.setSelectSet(new SelectionSpec[] { folder2childEntity } );
+ folder2childEntity.getSelectSet().add(recurseFolders);
+ dc2VmFolderTraversal.getSelectSet().add(folder2childEntity);
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { dc2VmFolderTraversal });
+ oSpec.getSelectSet().add(dc2VmFolderTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- return _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
}
-
- public static Pair getOwnerDatacenter(VmwareContext context,
+
+ public static Pair getOwnerDatacenter(VmwareContext context,
ManagedObjectReference morEntity) throws Exception {
-
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datacenter");
- pSpec.setPathSet(new String[] { "name" });
-
+ pSpec.getPathSet().add("name");
+
TraversalSpec entityParentTraversal = new TraversalSpec();
entityParentTraversal.setType("ManagedEntity");
entityParentTraversal.setPath("parent");
entityParentTraversal.setName("entityParentTraversal");
- entityParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "entityParentTraversal") });
+ SelectionSpec selSpec = new SelectionSpec();
+ selSpec.setName("entityParentTraversal");
+ entityParentTraversal.getSelectSet().add(selSpec);
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(morEntity);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { entityParentTraversal });
+ oSpec.getSelectSet().add(entityParentTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = context.getService().retrieveProperties(
- context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
- assert(ocs != null);
- assert(ocs[0].getObj() != null);
- assert(ocs[0].getPropSet(0) != null);
- assert(ocs[0].getPropSet(0).getVal() != null);
-
- String dcName = ocs[0].getPropSet(0).getVal().toString();
- return new Pair(new DatacenterMO(context, ocs[0].getObj()), dcName);
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = context.getService().retrieveProperties(
+ context.getPropertyCollector(), pfSpecArr);
+
+ assert(ocs != null && ocs.size() > 0);
+ assert(ocs.get(0).getObj() != null);
+ assert(ocs.get(0).getPropSet().get(0) != null);
+ assert(ocs.get(0).getPropSet().get(0).getVal() != null);
+
+ String dcName = ocs.get(0).getPropSet().get(0).getVal().toString();
+ return new Pair(new DatacenterMO(context, ocs.get(0).getObj()), dcName);
}
-
+
public ManagedObjectReference getDvPortGroupMor(String dvPortGroupName) throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("DistributedVirtualPortgroup");
- pSpec.setPathSet(new String[] {"name"});
-
+ pSpec.getPathSet().add("name");
+
TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec();
datacenter2DvPortGroupTraversal.setType("Datacenter");
datacenter2DvPortGroupTraversal.setPath("network");
datacenter2DvPortGroupTraversal.setName("datacenter2DvPortgroupTraversal");
-
+
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { datacenter2DvPortGroupTraversal });
+ oSpec.getSelectSet().add(datacenter2DvPortGroupTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
if(ocs != null) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
for(DynamicProperty prop : props) {
if(prop.getVal().equals(dvPortGroupName))
@@ -347,22 +353,23 @@ public class DatacenterMO extends BaseMO {
}
}
return null;
- }
+ }
public boolean hasDvPortGroup(String dvPortGroupName) throws Exception {
ManagedObjectReference morNetwork = getDvPortGroupMor(dvPortGroupName);
if(morNetwork != null)
return true;
- return false;
+ return false;
}
-
+
public DVPortgroupConfigInfo getDvPortGroupSpec(String dvPortGroupName) throws Exception {
DVPortgroupConfigInfo configSpec = null;
String nameProperty = null;
PropertySpec pSpec = new PropertySpec();
pSpec.setType("DistributedVirtualPortgroup");
- pSpec.setPathSet(new String[] {"name", "config"});
-
+ pSpec.getPathSet().add("name");
+ pSpec.getPathSet().add("config");
+
TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec();
datacenter2DvPortGroupTraversal.setType("Datacenter");
datacenter2DvPortGroupTraversal.setPath("network");
@@ -371,21 +378,22 @@ public class DatacenterMO extends BaseMO {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { datacenter2DvPortGroupTraversal });
+ oSpec.getSelectSet().add(datacenter2DvPortGroupTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
if(ocs != null) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
- assert(props.length == 2);
+ assert(props.size() == 2);
for(DynamicProperty prop : props) {
if(prop.getName().equals("config")) {
configSpec = (DVPortgroupConfigInfo) prop.getVal();
@@ -395,7 +403,7 @@ public class DatacenterMO extends BaseMO {
}
}
if(nameProperty.equalsIgnoreCase(dvPortGroupName)) {
- return configSpec;
+ return configSpec;
}
}
}
@@ -408,7 +416,8 @@ public class DatacenterMO extends BaseMO {
ManagedObjectReference dvSwitchMor = null;
PropertySpec pSpec = new PropertySpec();
pSpec.setType("DistributedVirtualPortgroup");
- pSpec.setPathSet(new String[] { "key", "config.distributedVirtualSwitch" });
+ pSpec.getPathSet().add("key");
+ pSpec.getPathSet().add("config.distributedVirtualSwitch");
TraversalSpec datacenter2DvPortGroupTraversal = new TraversalSpec();
datacenter2DvPortGroupTraversal.setType("Datacenter");
@@ -418,21 +427,22 @@ public class DatacenterMO extends BaseMO {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { datacenter2DvPortGroupTraversal });
+ oSpec.getSelectSet().add(datacenter2DvPortGroupTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
if (ocs != null) {
for (ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if (props != null) {
- assert (props.length == 2);
+ assert (props.size() == 2);
for (DynamicProperty prop : props) {
if (prop.getName().equals("key")) {
dvPortGroupKey = (String) prop.getVal();
@@ -441,7 +451,7 @@ public class DatacenterMO extends BaseMO {
dvSwitchMor = (ManagedObjectReference) prop.getVal();
}
}
- if ((dvPortGroupKey != null) && dvPortGroupKey.equals(dvPortGroupMor.get_value())) {
+ if ((dvPortGroupKey != null) && dvPortGroupKey.equals(dvPortGroupMor.getValue())) {
return dvSwitchMor;
}
}
@@ -452,7 +462,7 @@ public class DatacenterMO extends BaseMO {
public String getDvSwitchUuid(ManagedObjectReference dvSwitchMor) throws Exception {
assert (dvSwitchMor != null);
- return (String) _context.getServiceUtil().getDynamicProperty(dvSwitchMor, "uuid");
+ return (String) _context.getVimClient().getDynamicProperty(dvSwitchMor, "uuid");
}
public VirtualEthernetCardDistributedVirtualPortBackingInfo getDvPortBackingInfo(Pair networkInfo)
@@ -464,7 +474,7 @@ public class DatacenterMO extends BaseMO {
ManagedObjectReference dvsMor = getDvSwitchMor(networkInfo.first());
String dvSwitchUuid = getDvSwitchUuid(dvsMor);
dvPortConnection.setSwitchUuid(dvSwitchUuid);
- dvPortConnection.setPortgroupKey(networkInfo.first().get_value());
+ dvPortConnection.setPortgroupKey(networkInfo.first().getValue());
dvPortBacking.setPort(dvPortConnection);
System.out.println("Plugging NIC device into network " + networkInfo.second() + " backed by dvSwitch: "
+ dvSwitchUuid);
@@ -474,8 +484,8 @@ public class DatacenterMO extends BaseMO {
public ManagedObjectReference getDvSwitchMor(String dvSwitchName) throws Exception {
ManagedObjectReference dvSwitchMor = null;
ManagedObjectReference networkFolderMor = null;
- networkFolderMor = _context.getServiceUtil().getMoRefProp(_mor, "networkFolder");
- dvSwitchMor = _context.getServiceUtil().getDecendentMoRef(networkFolderMor, "VmwareDistributedVirtualSwitch", dvSwitchName);
+ networkFolderMor = _context.getVimClient().getMoRefProp(_mor, "networkFolder");
+ dvSwitchMor = _context.getVimClient().getDecendentMoRef(networkFolderMor, "VmwareDistributedVirtualSwitch", dvSwitchName);
return dvSwitchMor;
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java
index 57e83b9799b..c79605d08ab 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DatastoreMO.java
@@ -36,95 +36,98 @@ import com.vmware.vim25.TraversalSpec;
public class DatastoreMO extends BaseMO {
private static final Logger s_logger = Logger.getLogger(DatastoreMO.class);
-
- private String _name;
- private Pair _ownerDc;
-
+
+ private String _name;
+ private Pair _ownerDc;
+
public DatastoreMO(VmwareContext context, ManagedObjectReference morDatastore) {
super(context, morDatastore);
}
-
+
public DatastoreMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
public String getName() throws Exception {
- if(_name == null)
- _name = (String)_context.getServiceUtil().getDynamicProperty(_mor, "name");
-
+ if(_name == null)
+ _name = (String)_context.getVimClient().getDynamicProperty(_mor, "name");
+
return _name;
}
-
+
public DatastoreSummary getSummary() throws Exception {
- return (DatastoreSummary)_context.getServiceUtil().getDynamicProperty(_mor, "summary");
+ return (DatastoreSummary)_context.getVimClient().getDynamicProperty(_mor, "summary");
}
-
+
public HostDatastoreBrowserMO getHostDatastoreBrowserMO() throws Exception {
- return new HostDatastoreBrowserMO(_context,
- (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(_mor, "browser"));
+ return new HostDatastoreBrowserMO(_context,
+ (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "browser"));
}
-
+
public String getInventoryPath() throws Exception {
Pair dcInfo = getOwnerDatacenter();
return dcInfo.second() + "/" + getName();
}
-
+
public Pair getOwnerDatacenter() throws Exception {
if(_ownerDc != null)
return _ownerDc;
-
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datacenter");
- pSpec.setPathSet(new String[] { "name" });
-
+ pSpec.getPathSet().add("name");
+
TraversalSpec folderParentTraversal = new TraversalSpec();
folderParentTraversal.setType("Folder");
folderParentTraversal.setPath("parent");
folderParentTraversal.setName("folderParentTraversal");
- folderParentTraversal.setSelectSet(new SelectionSpec[] { new SelectionSpec(null, null, "folderParentTraversal") });
-
+ SelectionSpec sSpec = new SelectionSpec();
+ sSpec.setName("folderParentTraversal");
+ folderParentTraversal.getSelectSet().add(sSpec);
+
TraversalSpec dsParentTraversal = new TraversalSpec();
dsParentTraversal.setType("Datastore");
dsParentTraversal.setPath("parent");
dsParentTraversal.setName("dsParentTraversal");
- dsParentTraversal.setSelectSet(new SelectionSpec[] { folderParentTraversal });
+ dsParentTraversal.getSelectSet().add(folderParentTraversal);
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(getMor());
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { dsParentTraversal });
+ oSpec.getSelectSet().add(dsParentTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
- assert(ocs != null);
- assert(ocs[0].getObj() != null);
- assert(ocs[0].getPropSet() != null);
- String dcName = ocs[0].getPropSet()[0].getVal().toString();
- _ownerDc = new Pair(new DatacenterMO(_context, ocs[0].getObj()), dcName);
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
+ assert(ocs != null && ocs.size() > 0);
+ assert(ocs.get(0).getObj() != null);
+ assert(ocs.get(0).getPropSet() != null);
+ String dcName = ocs.get(0).getPropSet().get(0).getVal().toString();
+ _ownerDc = new Pair(new DatacenterMO(_context, ocs.get(0).getObj()), dcName);
return _ownerDc;
}
-
+
public void makeDirectory(String path, ManagedObjectReference morDc) throws Exception {
String datastoreName = getName();
ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager();
-
+
String fullPath = path;
- if(!DatastoreFile.isFullDatastorePath(fullPath))
+ if(!DatastoreFile.isFullDatastorePath(fullPath))
fullPath = String.format("[%s] %s", datastoreName, path);
-
+
_context.getService().makeDirectory(morFileManager, fullPath, morDc, true);
}
-
+
public boolean deleteFile(String path, ManagedObjectReference morDc, boolean testExistence) throws Exception {
String datastoreName = getName();
ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager();
-
+
String fullPath = path;
if(!DatastoreFile.isFullDatastorePath(fullPath))
fullPath = String.format("[%s] %s", datastoreName, path);
@@ -136,12 +139,11 @@ public class DatastoreMO extends BaseMO {
s_logger.info("Unable to test file existence due to exception " + e.getClass().getName() + ", skip deleting of it");
return true;
}
-
- ManagedObjectReference morTask = _context.getService().deleteDatastoreFile_Task(morFileManager,
- fullPath, morDc);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ ManagedObjectReference morTask = _context.getService().deleteDatastoreFileTask(morFileManager, fullPath, morDc);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -149,29 +151,29 @@ public class DatastoreMO extends BaseMO {
}
return false;
}
-
+
public boolean copyDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc,
- ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc,
+ ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc,
boolean forceOverwrite) throws Exception {
-
+
String srcDsName = getName();
DatastoreMO destDsMo = new DatastoreMO(_context, morDestDs);
String destDsName = destDsMo.getName();
-
+
ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager();
String srcFullPath = srcFilePath;
if(!DatastoreFile.isFullDatastorePath(srcFullPath))
srcFullPath = String.format("[%s] %s", srcDsName, srcFilePath);
-
+
String destFullPath = destFilePath;
if(!DatastoreFile.isFullDatastorePath(destFullPath))
destFullPath = String.format("[%s] %s", destDsName, destFilePath);
-
- ManagedObjectReference morTask = _context.getService().copyDatastoreFile_Task(morFileManager,
+
+ ManagedObjectReference morTask = _context.getService().copyDatastoreFileTask(morFileManager,
srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -179,29 +181,29 @@ public class DatastoreMO extends BaseMO {
}
return false;
}
-
+
public boolean moveDatastoreFile(String srcFilePath, ManagedObjectReference morSrcDc,
- ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc,
+ ManagedObjectReference morDestDs, String destFilePath, ManagedObjectReference morDestDc,
boolean forceOverwrite) throws Exception {
-
+
String srcDsName = getName();
DatastoreMO destDsMo = new DatastoreMO(_context, morDestDs);
String destDsName = destDsMo.getName();
-
+
ManagedObjectReference morFileManager = _context.getServiceContent().getFileManager();
String srcFullPath = srcFilePath;
if(!DatastoreFile.isFullDatastorePath(srcFullPath))
srcFullPath = String.format("[%s] %s", srcDsName, srcFilePath);
-
+
String destFullPath = destFilePath;
if(!DatastoreFile.isFullDatastorePath(destFullPath))
destFullPath = String.format("[%s] %s", destDsName, destFilePath);
-
- ManagedObjectReference morTask = _context.getService().moveDatastoreFile_Task(morFileManager,
+
+ ManagedObjectReference morTask = _context.getService().moveDatastoreFileTask(morFileManager,
srcFullPath, morSrcDc, destFullPath, morDestDc, forceOverwrite);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -209,23 +211,23 @@ public class DatastoreMO extends BaseMO {
}
return false;
}
-
+
public String[] getVmdkFileChain(String rootVmdkDatastoreFullPath) throws Exception {
Pair dcPair = getOwnerDatacenter();
-
+
List files = new ArrayList();
files.add(rootVmdkDatastoreFullPath);
-
+
String currentVmdkFullPath = rootVmdkDatastoreFullPath;
while(true) {
String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), currentVmdkFullPath);
byte[] content = getContext().getResourceContent(url);
if(content == null || content.length == 0)
break;
-
+
VmdkFileDescriptor descriptor = new VmdkFileDescriptor();
descriptor.parse(content);
-
+
String parentFileName = descriptor.getParentFileName();
if(parentFileName == null)
break;
@@ -239,8 +241,8 @@ public class DatastoreMO extends BaseMO {
dir = dir.substring(0, dir.lastIndexOf('/'));
else
dir = "";
-
- currentVmdkFullPath = new DatastoreFile(dsFile.getDatastoreName(), dir,
+
+ currentVmdkFullPath = new DatastoreFile(dsFile.getDatastoreName(), dir,
parentFileName.substring(parentFileName.lastIndexOf('/') + 1)).getPath();
files.add(currentVmdkFullPath);
} else {
@@ -248,7 +250,7 @@ public class DatastoreMO extends BaseMO {
files.add(currentVmdkFullPath);
}
}
-
+
return files.toArray(new String[0]);
}
@@ -257,59 +259,59 @@ public class DatastoreMO extends BaseMO {
String fullPath = path;
if(!DatastoreFile.isFullDatastorePath(fullPath))
fullPath = String.format("[%s] %s", getName(), fullPath);
-
+
Pair dcPair = getOwnerDatacenter();
String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), fullPath);
-
+
// TODO, VMware currently does not have a formal API to list Datastore directory content,
// folloing hacking may have performance hit if datastore has a large number of files
return _context.listDatastoreDirContent(url);
}
-
+
public boolean fileExists(String fileFullPath) throws Exception {
DatastoreFile file = new DatastoreFile(fileFullPath);
DatastoreFile dirFile = new DatastoreFile(file.getDatastoreName(), file.getDir());
-
+
HostDatastoreBrowserMO browserMo = getHostDatastoreBrowserMO();
-
+
s_logger.info("Search file " + file.getFileName() + " on " + dirFile.getPath());
HostDatastoreBrowserSearchResults results = browserMo.searchDatastore(dirFile.getPath(), file.getFileName(), true);
if(results != null) {
- FileInfo[] info = results.getFile();
- if(info != null && info.length > 0) {
+ List info = results.getFile();
+ if(info != null && info.size() > 0) {
s_logger.info("File " + fileFullPath + " exists on datastore");
return true;
}
}
-
+
s_logger.info("File " + fileFullPath + " does not exist on datastore");
return false;
-/*
+/*
String[] fileNames = listDirContent(dirFile.getPath());
-
+
String fileName = file.getFileName();
for(String name : fileNames) {
if(name.equalsIgnoreCase(fileName))
return true;
- }
-
+ }
+
return false;
-*/
+*/
}
-
+
public boolean folderExists(String folderParentDatastorePath, String folderName) throws Exception {
HostDatastoreBrowserMO browserMo = getHostDatastoreBrowserMO();
-
+
HostDatastoreBrowserSearchResults results = browserMo.searchDatastore(folderParentDatastorePath, folderName, true);
if(results != null) {
- FileInfo[] info = results.getFile();
- if(info != null && info.length > 0) {
+ List info = results.getFile();
+ if(info != null && info.size() > 0) {
s_logger.info("Folder " + folderName + " exists on datastore");
return true;
}
}
-
+
s_logger.info("Folder " + folderName + " does not exist on datastore");
return false;
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java
index 494477e9be3..247be2a5fab 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/DistributedVirtualSwitchMO.java
@@ -16,11 +16,13 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
+import java.util.ArrayList;
+import java.util.List;
+
import org.apache.log4j.Logger;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.DVPortgroupConfigSpec;
-import com.vmware.vim25.HostPortGroupSpec;
import com.vmware.vim25.ManagedObjectReference;
public class DistributedVirtualSwitchMO extends BaseMO {
@@ -35,13 +37,13 @@ public class DistributedVirtualSwitchMO extends BaseMO {
}
public void createDVPortGroup(DVPortgroupConfigSpec dvPortGroupSpec) throws Exception {
- DVPortgroupConfigSpec[] dvPortGroupSpecArray = new DVPortgroupConfigSpec[1];
- dvPortGroupSpecArray[0] = dvPortGroupSpec;
- _context.getService().addDVPortgroup_Task(_mor, dvPortGroupSpecArray);
+ List dvPortGroupSpecArray = new ArrayList();
+ dvPortGroupSpecArray.add(dvPortGroupSpec);
+ _context.getService().addDVPortgroupTask(_mor, dvPortGroupSpecArray);
}
public void updateDvPortGroup(ManagedObjectReference dvPortGroupMor, DVPortgroupConfigSpec dvPortGroupSpec) throws Exception {
// TODO(sateesh): Update numPorts
- _context.getService().reconfigureDVPortgroup_Task(dvPortGroupMor, dvPortGroupSpec);
+ _context.getService().reconfigureDVPortgroupTask(dvPortGroupMor, dvPortGroupSpec);
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java
index ec0a1810701..59e754c951d 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreBrowserMO.java
@@ -24,39 +24,39 @@ import com.vmware.vim25.HostDatastoreBrowserSearchSpec;
import com.vmware.vim25.ManagedObjectReference;
public class HostDatastoreBrowserMO extends BaseMO {
-
+
private static final Logger s_logger = Logger.getLogger(HostDatastoreBrowserMO.class);
-
+
public HostDatastoreBrowserMO(VmwareContext context, ManagedObjectReference morHostDatastoreBrowser) {
super(context, morHostDatastoreBrowser);
}
-
+
public HostDatastoreBrowserMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public void DeleteFile(String datastoreFullPath) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - deleteFile(). target mor: " + _mor.get_value() + ", file datastore path: " + datastoreFullPath);
-
+ s_logger.trace("vCenter API trace - deleteFile(). target mor: " + _mor.getValue() + ", file datastore path: " + datastoreFullPath);
+
_context.getService().deleteFile(_mor, datastoreFullPath);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - deleteFile() done");
}
-
+
public HostDatastoreBrowserSearchResults searchDatastore(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - searchDatastore(). target mor: " + _mor.get_value() + ", file datastore path: " + datastorePath);
+ s_logger.trace("vCenter API trace - searchDatastore(). target mor: " + _mor.getValue() + ", file datastore path: " + datastorePath);
try {
- ManagedObjectReference morTask = _context.getService().searchDatastore_Task(_mor, datastorePath, searchSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().searchDatastoreTask(_mor, datastorePath, searchSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
-
- return (HostDatastoreBrowserSearchResults)_context.getServiceUtil().getDynamicProperty(morTask, "info.result");
+
+ return (HostDatastoreBrowserSearchResults)_context.getVimClient().getDynamicProperty(morTask, "info.result");
} else {
s_logger.error("VMware searchDaastore_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
@@ -64,30 +64,30 @@ public class HostDatastoreBrowserMO extends BaseMO {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - searchDatastore() done");
}
-
+
return null;
}
-
+
public HostDatastoreBrowserSearchResults searchDatastore(String datastorePath, String fileName, boolean caseInsensitive) throws Exception {
HostDatastoreBrowserSearchSpec spec = new HostDatastoreBrowserSearchSpec();
spec.setSearchCaseInsensitive(caseInsensitive);
- spec.setMatchPattern(new String[] { fileName });
+ spec.getMatchPattern().add(fileName);
return searchDatastore(datastorePath, spec);
}
-
+
public HostDatastoreBrowserSearchResults searchDatastoreSubFolders(String datastorePath, HostDatastoreBrowserSearchSpec searchSpec) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - searchDatastoreSubFolders(). target mor: " + _mor.get_value() + ", file datastore path: " + datastorePath);
+ s_logger.trace("vCenter API trace - searchDatastoreSubFolders(). target mor: " + _mor.getValue() + ", file datastore path: " + datastorePath);
try {
- ManagedObjectReference morTask = _context.getService().searchDatastoreSubFolders_Task(_mor, datastorePath, searchSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().searchDatastoreSubFoldersTask(_mor, datastorePath, searchSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
-
- return (HostDatastoreBrowserSearchResults)_context.getServiceUtil().getDynamicProperty(morTask, "info.result");
+
+ return (HostDatastoreBrowserSearchResults)_context.getVimClient().getDynamicProperty(morTask, "info.result");
} else {
s_logger.error("VMware searchDaastoreSubFolders_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
@@ -95,14 +95,14 @@ public class HostDatastoreBrowserMO extends BaseMO {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - searchDatastore() done");
}
-
+
return null;
}
-
+
public HostDatastoreBrowserSearchResults searchDatastoreSubFolders(String datastorePath, String folderName, boolean caseInsensitive) throws Exception {
HostDatastoreBrowserSearchSpec spec = new HostDatastoreBrowserSearchSpec();
spec.setSearchCaseInsensitive(caseInsensitive);
- spec.setMatchPattern(new String[] { folderName });
+ spec.getMatchPattern().add(folderName);
return searchDatastore(datastorePath, spec);
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java
index d94102bb2fb..3dcd7249060 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java
@@ -17,6 +17,9 @@
package com.cloud.hypervisor.vmware.mo;
import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.CustomFieldStringValue;
@@ -37,27 +40,27 @@ public class HostDatastoreSystemMO extends BaseMO {
public HostDatastoreSystemMO(VmwareContext context, ManagedObjectReference morHostDatastore) {
super(context, morHostDatastore);
}
-
+
public HostDatastoreSystemMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public ManagedObjectReference findDatastore(String name) throws Exception {
// added cloud.com specific name convention, we will use custom field "cloud.uuid" as datastore name as well
- CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
+ CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
_context.getServiceContent().getCustomFieldsManager());
int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID);
assert(key != 0);
- ObjectContent[] ocs = getDatastorePropertiesOnHostDatastoreSystem(
+ List ocs = getDatastorePropertiesOnHostDatastoreSystem(
new String[] { "name", String.format("value[%d]", key) });
if(ocs != null) {
for(ObjectContent oc : ocs) {
- if(oc.getPropSet(0).getVal().equals(name))
+ if(oc.getPropSet().get(0).getVal().equals(name))
return oc.getObj();
-
- if(oc.getPropSet().length > 1) {
- DynamicProperty prop = oc.getPropSet(1);
+
+ if(oc.getPropSet().size() > 1) {
+ DynamicProperty prop = oc.getPropSet().get(1);
if(prop != null && prop.getVal() != null) {
if(prop.getVal() instanceof CustomFieldStringValue) {
String val = ((CustomFieldStringValue)prop.getVal()).getValue();
@@ -70,13 +73,13 @@ public class HostDatastoreSystemMO extends BaseMO {
}
return null;
}
-
+
// storeUrl in nfs://host/exportpath format
public ManagedObjectReference findDatastoreByUrl(String storeUrl) throws Exception {
assert(storeUrl != null);
-
- ManagedObjectReference[] datastores = getDatastores();
- if(datastores != null && datastores.length > 0) {
+
+ List datastores = getDatastores();
+ if(datastores != null && datastores.size() > 0) {
for(ManagedObjectReference morDatastore : datastores) {
NasDatastoreInfo info = getNasDatastoreInfo(morDatastore);
if(info != null) {
@@ -87,7 +90,7 @@ public class HostDatastoreSystemMO extends BaseMO {
}
}
}
-
+
return null;
}
@@ -95,30 +98,30 @@ public class HostDatastoreSystemMO extends BaseMO {
// we should be able to find the datastore by name
public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception {
assert(exportPath != null);
-
- ManagedObjectReference[] datastores = getDatastores();
- if(datastores != null && datastores.length > 0) {
+
+ List datastores = getDatastores();
+ if(datastores != null && datastores.size() > 0) {
for(ManagedObjectReference morDatastore : datastores) {
DatastoreMO dsMo = new DatastoreMO(_context, morDatastore);
- if(dsMo.getInventoryPath().equals(exportPath))
+ if(dsMo.getInventoryPath().equals(exportPath))
return morDatastore;
-
+
NasDatastoreInfo info = getNasDatastoreInfo(morDatastore);
if(info != null) {
String vmwareUrl = info.getUrl();
if(vmwareUrl.charAt(vmwareUrl.length() - 1) == '/')
vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1);
-
+
URI uri = new URI(vmwareUrl);
if(uri.getPath().equals("/" + exportPath))
return morDatastore;
}
}
}
-
+
return null;
}
-
+
public boolean deleteDatastore(String name) throws Exception {
ManagedObjectReference morDatastore = findDatastore(name);
if(morDatastore != null) {
@@ -127,59 +130,60 @@ public class HostDatastoreSystemMO extends BaseMO {
}
return false;
}
-
- public ManagedObjectReference createNfsDatastore(String host, int port,
+
+ public ManagedObjectReference createNfsDatastore(String host, int port,
String exportPath, String uuid) throws Exception {
-
+
HostNasVolumeSpec spec = new HostNasVolumeSpec();
spec.setRemoteHost(host);
spec.setRemotePath(exportPath);
spec.setType("nfs");
spec.setLocalPath(uuid);
-
+
// readOnly/readWrite
spec.setAccessMode("readWrite");
return _context.getService().createNasDatastore(_mor, spec);
}
-
- public ManagedObjectReference[] getDatastores() throws Exception {
- return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(
+
+ public List getDatastores() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(
_mor, "datastore");
}
-
+
public DatastoreInfo getDatastoreInfo(ManagedObjectReference morDatastore) throws Exception {
- return (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info");
+ return (DatastoreInfo)_context.getVimClient().getDynamicProperty(morDatastore, "info");
}
-
+
public NasDatastoreInfo getNasDatastoreInfo(ManagedObjectReference morDatastore) throws Exception {
- DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info");
+ DatastoreInfo info = (DatastoreInfo)_context.getVimClient().getDynamicProperty(morDatastore, "info");
if(info instanceof NasDatastoreInfo)
return (NasDatastoreInfo)info;
return null;
}
-
- public ObjectContent[] getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception {
-
+
+ public List getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception {
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datastore");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec hostDsSys2DatastoreTraversal = new TraversalSpec();
hostDsSys2DatastoreTraversal.setType("HostDatastoreSystem");
hostDsSys2DatastoreTraversal.setPath("datastore");
hostDsSys2DatastoreTraversal.setName("hostDsSys2DatastoreTraversal");
-
+
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { hostDsSys2DatastoreTraversal });
+ oSpec.getSelectSet().add(hostDsSys2DatastoreTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
return _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ _context.getPropertyCollector(), pfSpecArr);
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java
index 2d2b35390ce..df159261c43 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostFirewallSystemMO.java
@@ -29,27 +29,27 @@ public class HostFirewallSystemMO extends BaseMO {
public HostFirewallSystemMO(VmwareContext context, ManagedObjectReference morFirewallSystem) {
super(context, morFirewallSystem);
}
-
+
public HostFirewallSystemMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public HostFirewallInfo getFirewallInfo() throws Exception {
- return (HostFirewallInfo)_context.getServiceUtil().getDynamicProperty(_mor, "firewallInfo");
+ return (HostFirewallInfo)_context.getVimClient().getDynamicProperty(_mor, "firewallInfo");
}
-
+
public void updateDefaultPolicy(HostFirewallDefaultPolicy policy) throws Exception {
_context.getService().updateDefaultPolicy(_mor, policy);
}
-
+
public void enableRuleset(String rulesetName) throws Exception {
_context.getService().enableRuleset(_mor, rulesetName);
}
-
+
public void disableRuleset(String rulesetName) throws Exception {
_context.getService().disableRuleset(_mor, rulesetName);
}
-
+
public void refreshFirewall() throws Exception {
_context.getService().refreshFirewall(_mor);
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
index 40343b692c3..a866fdc6261 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
@@ -27,8 +27,8 @@ import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.hypervisor.vmware.util.VmwareHelper;
import com.cloud.utils.Pair;
import com.google.gson.Gson;
-import com.vmware.apputils.vim25.ServiceUtil;
import com.vmware.vim25.AboutInfo;
+import com.vmware.vim25.AlreadyExistsFaultMsg;
import com.vmware.vim25.ClusterDasConfigInfo;
import com.vmware.vim25.ComputeResourceSummary;
import com.vmware.vim25.DatastoreSummary;
@@ -55,65 +55,62 @@ import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.OptionValue;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
-import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.VirtualMachineConfigSpec;
-import com.vmware.vim25.VirtualMachineSnapshotInfo;
-import com.vmware.vim25.VirtualMachineSnapshotTree;
import com.vmware.vim25.VirtualNicManagerNetConfig;
import com.vmware.vim25.NasDatastoreInfo;
+import edu.emory.mathcs.backport.java.util.Arrays;
+
public class HostMO extends BaseMO implements VmwareHypervisorHost {
private static final Logger s_logger = Logger.getLogger(HostMO.class);
Map _vmCache = new HashMap();
-
+
public HostMO (VmwareContext context, ManagedObjectReference morHost) {
super(context, morHost);
}
-
+
public HostMO (VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public HostHardwareSummary getHostHardwareSummary() throws Exception {
HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor);
HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware();
return hardwareSummary;
}
-
+
public HostConfigManager getHostConfigManager() throws Exception {
- return (HostConfigManager)_context.getServiceUtil().getDynamicProperty(_mor, "configManager");
+ return (HostConfigManager)_context.getVimClient().getDynamicProperty(_mor, "configManager");
}
-
- public VirtualNicManagerNetConfig[] getHostVirtualNicManagerNetConfig() throws Exception {
- VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor,
+
+ public List getHostVirtualNicManagerNetConfig() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(_mor,
"config.virtualNicManagerInfo.netConfig");
- return netConfigs;
}
-
- public HostIpRouteEntry[] getHostIpRouteEntries() throws Exception {
- HostIpRouteEntry[] entries = (HostIpRouteEntry[])_context.getServiceUtil().getDynamicProperty(_mor,
+
+ public List getHostIpRouteEntries() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(_mor,
"config.network.routeTableInfo.ipRoute");
- return entries;
}
-
+
public HostListSummaryQuickStats getHostQuickStats() throws Exception {
- return (HostListSummaryQuickStats)_context.getServiceUtil().getDynamicProperty(_mor, "summary.quickStats");
+ return (HostListSummaryQuickStats)_context.getVimClient().getDynamicProperty(_mor, "summary.quickStats");
}
-
+
public HostHyperThreadScheduleInfo getHostHyperThreadInfo() throws Exception {
- return (HostHyperThreadScheduleInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.hyperThread");
+ return (HostHyperThreadScheduleInfo)_context.getVimClient().getDynamicProperty(_mor, "config.hyperThread");
}
-
+
public HostNetworkInfo getHostNetworkInfo() throws Exception {
- return (HostNetworkInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.network");
+ return (HostNetworkInfo)_context.getVimClient().getDynamicProperty(_mor, "config.network");
}
-
+
public HostPortGroupSpec getHostPortGroupSpec(String portGroupName) throws Exception {
-
+
HostNetworkInfo hostNetInfo = getHostNetworkInfo();
-
- HostPortGroup[] portGroups = hostNetInfo.getPortgroup();
+
+ List portGroups = hostNetInfo.getPortgroup();
if(portGroups != null) {
for(HostPortGroup portGroup : portGroups) {
HostPortGroupSpec spec = portGroup.getSpec();
@@ -121,15 +118,15 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return spec;
}
}
-
+
return null;
}
-
+
@Override
public String getHyperHostName() throws Exception {
return getName();
}
-
+
@Override
public ClusterDasConfigInfo getDasConfig() throws Exception {
ManagedObjectReference morParent = getParentMor();
@@ -137,31 +134,31 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ClusterMO clusterMo = new ClusterMO(_context, morParent);
return clusterMo.getDasConfig();
}
-
+
return null;
}
-
+
@Override
public String getHyperHostDefaultGateway() throws Exception {
- HostIpRouteEntry[] entries = getHostIpRouteEntries();
+ List 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(
+ (ManagedObjectReference)_context.getVimClient().getDynamicProperty(
_mor, "configManager.datastoreSystem")
);
}
-
+
public HostDatastoreBrowserMO getHostDatastoreBrowserMO() throws Exception {
return new HostDatastoreBrowserMO(_context,
- (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(
+ (ManagedObjectReference)_context.getVimClient().getDynamicProperty(
_mor, "datastoreBrowser")
);
}
@@ -170,7 +167,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { "name"} );
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] objProps = oc.getPropSet();
+ List objProps = oc.getPropSet();
if(objProps != null) {
for(DynamicProperty objProp : objProps) {
if(objProp.getVal().toString().equals(datastoreName))
@@ -181,22 +178,22 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
return null;
}
-
+
public HostNetworkSystemMO getHostNetworkSystemMO() throws Exception {
HostConfigManager configMgr = getHostConfigManager();
return new HostNetworkSystemMO(_context, configMgr.getNetworkSystem());
}
-
+
public HostFirewallSystemMO getHostFirewallSystemMO() throws Exception {
HostConfigManager configMgr = getHostConfigManager();
ManagedObjectReference morFirewall = configMgr.getFirewallSystem();
-
+
// only ESX hosts have firewall manager
if(morFirewall != null)
return new HostFirewallSystemMO(_context, morFirewall);
return null;
}
-
+
@Override
public ManagedObjectReference getHyperHostDatacenter() throws Exception {
Pair dcPair = DatacenterMO.getOwnerDatacenter(getContext(), getMor());
@@ -206,43 +203,40 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
@Override
public ManagedObjectReference getHyperHostOwnerResourcePool() throws Exception {
- ServiceUtil serviceUtil = _context.getServiceUtil();
- ManagedObjectReference morComputerResource = (ManagedObjectReference)serviceUtil.getDynamicProperty(_mor, "parent");
- return (ManagedObjectReference)serviceUtil.getDynamicProperty(morComputerResource, "resourcePool");
+ ManagedObjectReference morComputerResource = (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "parent");
+ return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(morComputerResource, "resourcePool");
}
@Override
public ManagedObjectReference getHyperHostCluster() throws Exception {
- ServiceUtil serviceUtil = _context.getServiceUtil();
- ManagedObjectReference morParent = (ManagedObjectReference)serviceUtil.getDynamicProperty(_mor, "parent");
-
+ ManagedObjectReference morParent = (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "parent");
+
if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) {
return morParent;
}
-
+
assert(false);
throw new Exception("Standalone host is not supported");
}
-
+
public ManagedObjectReference[] getHostLocalDatastore() throws Exception {
- ServiceUtil serviceUtil = _context.getServiceUtil();
- ManagedObjectReference[] datastores = (ManagedObjectReference[])serviceUtil.getDynamicProperty(
+ List datastores = (List)_context.getVimClient().getDynamicProperty(
_mor, "datastore");
List l = new ArrayList();
if(datastores != null) {
for(ManagedObjectReference mor : datastores) {
- DatastoreSummary summary = (DatastoreSummary)serviceUtil.getDynamicProperty(mor, "summary");
- if(summary.getType().equalsIgnoreCase("VMFS") && !summary.getMultipleHostAccess())
+ DatastoreSummary summary = (DatastoreSummary)_context.getVimClient().getDynamicProperty(mor, "summary");
+ if(summary.getType().equalsIgnoreCase("VMFS") && !summary.isMultipleHostAccess())
l.add(mor);
}
}
return l.toArray(new ManagedObjectReference[1]);
}
-
+
public HostVirtualSwitch getHostVirtualSwitchByName(String name) throws Exception {
- HostVirtualSwitch[] switches = (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty(
+ List switches = (List)_context.getVimClient().getDynamicProperty(
_mor, "config.network.vswitch");
-
+
if(switches != null) {
for(HostVirtualSwitch vswitch : switches) {
if(vswitch.getName().equals(name))
@@ -251,58 +245,58 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
return null;
}
-
- public HostVirtualSwitch[] getHostVirtualSwitch() throws Exception {
- return (HostVirtualSwitch[])_context.getServiceUtil().getDynamicProperty(_mor, "config.network.vswitch");
+
+ public List getHostVirtualSwitch() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(_mor, "config.network.vswitch");
}
-
+
public AboutInfo getHostAboutInfo() throws Exception {
- return (AboutInfo)_context.getServiceUtil().getDynamicProperty(_mor, "config.product");
+ return (AboutInfo)_context.getVimClient().getDynamicProperty(_mor, "config.product");
}
-
+
public VmwareHostType getHostType() throws Exception {
AboutInfo aboutInfo = getHostAboutInfo();
if("VMware ESXi".equals(aboutInfo.getName()))
return VmwareHostType.ESXi;
else if("VMware ESX".equals(aboutInfo.getName()))
return VmwareHostType.ESX;
-
+
throw new Exception("Unrecognized VMware host type " + aboutInfo.getName());
}
-
+
// default virtual switch is which management network residents on
public HostVirtualSwitch getHostDefaultVirtualSwitch() throws Exception {
String managementPortGroup = getPortGroupNameByNicType(HostVirtualNicType.management);
if(managementPortGroup != null)
return getPortGroupVirtualSwitch(managementPortGroup);
-
+
return null;
}
-
+
public HostVirtualSwitch getPortGroupVirtualSwitch(String portGroupName) throws Exception {
String vSwitchName = getPortGroupVirtualSwitchName(portGroupName);
if(vSwitchName != null)
return getVirtualSwitchByName(vSwitchName);
-
+
return null;
}
-
+
public HostVirtualSwitch getVirtualSwitchByName(String vSwitchName) throws Exception {
-
- HostVirtualSwitch[] vSwitchs = getHostVirtualSwitch();
+
+ List vSwitchs = getHostVirtualSwitch();
if(vSwitchs != null) {
for(HostVirtualSwitch vSwitch: vSwitchs) {
if(vSwitch.getName().equals(vSwitchName))
return vSwitch;
}
}
-
+
return null;
}
-
+
public String getPortGroupVirtualSwitchName(String portGroupName) throws Exception {
HostNetworkInfo hostNetInfo = getHostNetworkInfo();
- HostPortGroup[] portGroups = hostNetInfo.getPortgroup();
+ List portGroups = hostNetInfo.getPortgroup();
if(portGroups != null) {
for(HostPortGroup portGroup : portGroups) {
HostPortGroupSpec spec = portGroup.getSpec();
@@ -310,13 +304,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return spec.getVswitchName();
}
}
-
+
return null;
}
-
+
public HostPortGroupSpec getPortGroupSpec(String portGroupName) throws Exception {
HostNetworkInfo hostNetInfo = getHostNetworkInfo();
- HostPortGroup[] portGroups = hostNetInfo.getPortgroup();
+ List portGroups = hostNetInfo.getPortgroup();
if(portGroups != null) {
for(HostPortGroup portGroup : portGroups) {
HostPortGroupSpec spec = portGroup.getSpec();
@@ -324,20 +318,20 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return spec;
}
}
-
+
return null;
}
-
+
public String getPortGroupNameByNicType(HostVirtualNicType nicType) throws Exception {
assert(nicType != null);
-
- VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor,
+
+ List netConfigs = (List)_context.getVimClient().getDynamicProperty(_mor,
"config.virtualNicManagerInfo.netConfig");
-
+
if(netConfigs != null) {
for(VirtualNicManagerNetConfig netConfig : netConfigs) {
if(netConfig.getNicType().equals(nicType.toString())) {
- HostVirtualNic[] nics = netConfig.getCandidateVnic();
+ List nics = netConfig.getCandidateVnic();
if(nics != null) {
for(HostVirtualNic nic : nics) {
return nic.getPortgroup();
@@ -346,36 +340,36 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
}
}
-
+
if(nicType == HostVirtualNicType.management) {
// ESX management network is configured in service console
HostNetworkInfo netInfo = getHostNetworkInfo();
assert(netInfo != null);
- HostVirtualNic[] nics = netInfo.getConsoleVnic();
+ List nics = netInfo.getConsoleVnic();
if(nics != null) {
for(HostVirtualNic nic : nics) {
return nic.getPortgroup();
}
}
}
-
+
return null;
}
-
+
public boolean hasPortGroup(HostVirtualSwitch vSwitch, String portGroupName) throws Exception {
ManagedObjectReference morNetwork = getNetworkMor(portGroupName);
if(morNetwork != null)
return true;
return false;
}
-
+
public void createPortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, HostNetworkSecurityPolicy secPolicy, HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception {
assert(portGroupName != null);
HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO();
assert(hostNetMo != null);
-
+
HostPortGroupSpec spec = new HostPortGroupSpec();
-
+
spec.setName(portGroupName);
if(vlanId != null)
spec.setVlanId(vlanId.intValue());
@@ -387,14 +381,14 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
spec.setVswitchName(vSwitch.getName());
hostNetMo.addPortGroup(spec);
}
-
+
public void updatePortGroup(HostVirtualSwitch vSwitch, String portGroupName, Integer vlanId, HostNetworkSecurityPolicy secPolicy, HostNetworkTrafficShapingPolicy shapingPolicy) throws Exception {
assert(portGroupName != null);
HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO();
assert(hostNetMo != null);
-
+
HostPortGroupSpec spec = new HostPortGroupSpec();
-
+
spec.setName(portGroupName);
if(vlanId != null)
spec.setVlanId(vlanId.intValue());
@@ -406,19 +400,19 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
spec.setVswitchName(vSwitch.getName());
hostNetMo.updatePortGroup(portGroupName, spec);
}
-
+
public void deletePortGroup(String portGroupName) throws Exception {
assert(portGroupName != null);
HostNetworkSystemMO hostNetMo = getHostNetworkSystemMO();
assert(hostNetMo != null);
- hostNetMo.removePortGroup(portGroupName);
+ hostNetMo.removePortGroup(portGroupName);
}
-
+
public ManagedObjectReference getNetworkMor(String portGroupName) throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Network");
- pSpec.setPathSet(new String[] {"summary.name"});
-
+ pSpec.getPathSet().add("summary.name");
+
TraversalSpec host2NetworkTraversal = new TraversalSpec();
host2NetworkTraversal.setType("HostSystem");
host2NetworkTraversal.setPath("network");
@@ -427,19 +421,20 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { host2NetworkTraversal });
+ oSpec.getSelectSet().add(host2NetworkTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
if(ocs != null) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
for(DynamicProperty prop : props) {
if(prop.getVal().equals(portGroupName))
@@ -450,62 +445,62 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
return null;
}
-
- public ManagedObjectReference[] getVmMorsOnNetwork(String portGroupName) throws Exception {
+
+ public List getVmMorsOnNetwork(String portGroupName) throws Exception {
ManagedObjectReference morNetwork = getNetworkMor(portGroupName);
if(morNetwork != null)
- return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(morNetwork, "vm");
+ return (List)_context.getVimClient().getDynamicProperty(morNetwork, "vm");
return null;
}
-
+
public String getHostName() throws Exception {
- return (String)_context.getServiceUtil().getDynamicProperty(_mor, "name");
+ return (String)_context.getVimClient().getDynamicProperty(_mor, "name");
}
@Override
public synchronized VirtualMachineMO findVmOnHyperHost(String name) throws Exception {
if(s_logger.isDebugEnabled())
s_logger.debug("find VM " + name + " on host");
-
+
VirtualMachineMO vmMo = _vmCache.get(name);
if(vmMo != null) {
if(s_logger.isDebugEnabled())
s_logger.debug("VM " + name + " found in host cache");
return vmMo;
}
-
+
loadVmCache();
return _vmCache.get(name);
}
-
+
private void loadVmCache() throws Exception {
if(s_logger.isDebugEnabled())
s_logger.debug("load VM cache on host");
-
+
_vmCache.clear();
-
+
ObjectContent[] ocs = getVmPropertiesOnHyperHost(new String[] { "name" });
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- String vmName = oc.getPropSet()[0].getVal().toString();
-
+ String vmName = oc.getPropSet().get(0).getVal().toString();
+
if(s_logger.isTraceEnabled())
s_logger.trace("put " + vmName + " into host cache");
-
+
_vmCache.put(vmName, new VirtualMachineMO(_context, oc.getObj()));
}
}
}
-
+
@Override
public VirtualMachineMO findVmOnPeerHyperHost(String name) throws Exception {
ManagedObjectReference morParent = getParentMor();
-
+
if(morParent.getType().equals("ClusterComputeResource")) {
ClusterMO clusterMo = new ClusterMO(_context, morParent);
return clusterMo.findVmOnHyperHost(name);
} else {
- // we don't support standalone host, all hosts have to be managed by
+ // we don't support standalone host, all hosts have to be managed by
// a cluster within vCenter
assert(false);
return null;
@@ -517,30 +512,30 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
assert(vmSpec != null);
DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter());
ManagedObjectReference morPool = getHyperHostOwnerResourcePool();
-
- ManagedObjectReference morTask = _context.getService().createVM_Task(
+
+ ManagedObjectReference morTask = _context.getService().createVMTask(
dcMo.getVmFolder(), vmSpec, morPool, _mor);
- String result = _context.getServiceUtil().waitForTask(morTask);
-
- if(result.equals("sucess")) {
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
return false;
}
-
+
public HashMap getVmVncPortsOnHost() throws Exception {
ObjectContent[] ocs = getVmPropertiesOnHyperHost(
new String[] { "name", "config.extraConfig[\"RemoteDisplay.vnc.port\"]" }
);
-
+
HashMap portInfo = new HashMap();
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] objProps = oc.getPropSet();
+ List objProps = oc.getPropSet();
if(objProps != null) {
String name = null;
String value = null;
@@ -550,27 +545,28 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
} else {
OptionValue optValue = (OptionValue)objProp.getVal();
value = (String)optValue.getValue();
- }
+ }
}
-
+
if(name != null && value != null) {
portInfo.put(name, Integer.parseInt(value));
}
}
}
}
-
+
return portInfo;
}
-
- public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception {
+
+ @Override
+ public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths));
-
+ s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths));
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec host2VmTraversal = new TraversalSpec();
host2VmTraversal.setType("HostSystem");
host2VmTraversal.setPath("vm");
@@ -579,30 +575,31 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { host2VmTraversal });
+ oSpec.getSelectSet().add(host2VmTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] properties = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List properties = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
- return properties;
+ return properties.toArray(new ObjectContent[properties.size()]);
}
@Override
public ObjectContent[] getDatastorePropertiesOnHyperHost(String[] propertyPaths) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths));
+ s_logger.trace("vCenter API trace - retrieveProperties() on Datastore properties. target MOR: " + _mor.getValue() + ", properties: " + new Gson().toJson(propertyPaths));
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Datastore");
- pSpec.setPathSet(propertyPaths);
-
+ pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
+
TraversalSpec host2DatastoreTraversal = new TraversalSpec();
host2DatastoreTraversal.setType("HostSystem");
host2DatastoreTraversal.setPath("datastore");
@@ -611,87 +608,88 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { host2DatastoreTraversal });
+ oSpec.getSelectSet().add(host2DatastoreTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] properties = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List properties = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
- return properties;
+ return properties.toArray(new ObjectContent[properties.size()]);
}
-
+
public List> getDatastoreMountsOnHost() throws Exception {
List> mounts = new ArrayList>();
-
+
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {
- String.format("host[\"%s\"].mountInfo.path", _mor.get_value()) });
+ String.format("host[\"%s\"].mountInfo.path", _mor.getValue()) });
if(ocs != null) {
for(ObjectContent oc : ocs) {
Pair mount = new Pair(
- oc.getObj(), oc.getPropSet(0).getVal().toString());
+ oc.getObj(), oc.getPropSet().get(0).getVal().toString());
mounts.add(mount);
}
}
return mounts;
}
-
+
public List> getLocalDatastoreOnHost() throws Exception {
List> dsList = new ArrayList>();
-
+
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] { "name", "summary" });
if(ocs != null) {
for(ObjectContent oc : ocs) {
DatastoreSummary dsSummary = (DatastoreSummary)VmwareHelper.getPropValue(oc, "summary");
- if(dsSummary.getMultipleHostAccess() == false && dsSummary.isAccessible() && dsSummary.getType().equalsIgnoreCase("vmfs")) {
+ if(dsSummary.isMultipleHostAccess() == false && dsSummary.isAccessible() && dsSummary.getType().equalsIgnoreCase("vmfs")) {
ManagedObjectReference morDs = oc.getObj();
String name = (String)VmwareHelper.getPropValue(oc, "name");
-
+
dsList.add(new Pair(morDs, name));
}
}
}
return dsList;
}
-
+
public void importVmFromOVF(String ovfFilePath, String vmName, String datastoreName, String diskOption) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.get_value() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName
+ s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName
+ ",datastoreName: " + datastoreName + ", diskOption: " + diskOption);
-
+
DatastoreMO dsMo = getHostDatastoreMO(datastoreName);
if(dsMo == null)
throw new Exception("Invalid datastore name: " + datastoreName);
-
+
importVmFromOVF(ovfFilePath, vmName, dsMo, diskOption);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - importVmFromOVF() done");
}
-
+
@Override
public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception {
ManagedObjectReference morRp = getHyperHostOwnerResourcePool();
assert(morRp != null);
-
+
HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, _mor);
}
-
+
@Override
public boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB,
String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.get_value() + ", vmName: " + vmName + ", cpuCount: " + cpuCount
- + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB
- + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.get_value() + ", snapshotDirToParent: " + snapshotDirToParent);
-
+ s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount
+ + ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB
+ + ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent);
+
boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse,
memoryMB, memoryReserveMB, guestOsIdentifier, morDs, snapshotDirToParent);
@@ -703,7 +701,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
public ManagedObjectReference getExistingDataStoreOnHost(boolean vmfsDatastore, String hostAddress,
int hostPort, String path, String uuid, HostDatastoreSystemMO hostDatastoreSystemMo) {
// First retrieve the list of Datastores on the host.
- ManagedObjectReference[] morArray;
+ List morArray;
try {
morArray = hostDatastoreSystemMo.getDatastores();
} catch (Exception e) {
@@ -711,17 +709,17 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return null;
}
// Next, get all the NAS datastores from this array of datastores.
- if (morArray.length > 0) {
+ if (morArray.size() > 0) {
int i;
- for (i = 0; i < morArray.length; i++) {
+ for (i = 0; i < morArray.size(); i++) {
NasDatastoreInfo nasDS;
try {
- nasDS = hostDatastoreSystemMo.getNasDatastoreInfo(morArray[i]);
+ nasDS = hostDatastoreSystemMo.getNasDatastoreInfo(morArray.get(i));
if (nasDS != null) {
//DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info");
if (nasDS.getNas().getRemoteHost().equalsIgnoreCase(hostAddress) &&
nasDS.getNas().getRemotePath().equalsIgnoreCase(path)) {
- return morArray[i];
+ return morArray.get(i);
}
}
} catch (Exception e) {
@@ -734,13 +732,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
@Override
- public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress,
+ public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress,
int poolHostPort, String poolPath, String poolUuid) throws Exception {
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress
+ s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress
+ ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid);
-
+
HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO();
ManagedObjectReference morDatastore = hostDatastoreSystemMo.findDatastore(poolUuid);
if(morDatastore == null) {
@@ -751,9 +749,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
poolHostPort,
poolPath,
poolUuid);
- } catch (com.vmware.vim25.AlreadyExists e) {
+ } catch (AlreadyExistsFaultMsg e) {
s_logger.info("Creation of NFS datastore on vCenter failed since datastore already exists." +
- " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " +
+ " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " +
vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort +
", poolPath: " + poolPath + ", poolUuid: " + poolUuid);
// Retrieve the morDatastore and return it.
@@ -761,16 +759,16 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
poolHostPort, poolPath, poolUuid, hostDatastoreSystemMo));
} catch (Exception e) {
s_logger.info("Creation of NFS datastore on vCenter failed. " +
- " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " +
+ " Details: vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " +
vmfsDatastore + ", poolHost: " + poolHostAddress + ", poolHostPort: " + poolHostPort +
", poolPath: " + poolPath + ", poolUuid: " + poolUuid + ". Exception mesg: " + e.getMessage());
throw new Exception("Creation of NFS datastore on vCenter failed.");
}
if(morDatastore == null) {
- String msg = "Unable to create NFS datastore. host: " + poolHostAddress + ", port: "
+ String msg = "Unable to create NFS datastore. host: " + poolHostAddress + ", port: "
+ poolHostPort + ", path: " + poolPath + ", uuid: " + poolUuid;
s_logger.error(msg);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - mountDatastore() done(failed)");
throw new Exception(msg);
@@ -778,32 +776,32 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
} else {
morDatastore = _context.getDatastoreMorByPath(poolPath);
if(morDatastore == null) {
- String msg = "Unable to create VMFS datastore. host: " + poolHostAddress + ", port: "
+ String msg = "Unable to create VMFS datastore. host: " + poolHostAddress + ", port: "
+ poolHostPort + ", path: " + poolPath + ", uuid: " + poolUuid;
s_logger.error(msg);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - mountDatastore() done(failed)");
throw new Exception(msg);
}
-
+
DatastoreMO dsMo = new DatastoreMO(_context, morDatastore);
dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid);
}
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - mountDatastore() done(successfully)");
-
+
return morDatastore;
}
-
+
@Override
public void unmountDatastore(String poolUuid) throws Exception {
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid);
-
+ s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid);
+
HostDatastoreSystemMO hostDatastoreSystemMo = getHostDatastoreSystemMO();
if(!hostDatastoreSystemMo.deleteDatastore(poolUuid)) {
String msg = "Unable to unmount datastore. uuid: " + poolUuid;
@@ -813,35 +811,35 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
s_logger.trace("vCenter API trace - unmountDatastore() done(failed)");
throw new Exception(msg);
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - unmountDatastore() done");
}
-
+
@Override
public ManagedObjectReference findDatastore(String poolUuid) throws Exception {
HostDatastoreSystemMO hostDsMo = getHostDatastoreSystemMO();
return hostDsMo.findDatastore(poolUuid);
}
-
+
@Override
public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception {
HostDatastoreSystemMO datastoreSystemMo = getHostDatastoreSystemMO();
return datastoreSystemMo.findDatastoreByExportPath(exportPath);
}
-
+
@Override
public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception {
return _mor;
}
-
+
@Override
public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.get_value());
-
+ s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.getValue());
+
VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary();
-
+
HostHardwareSummary hardwareSummary = getHostHardwareSummary();
// TODO: not sure how hyper-thread is counted in VMware resource pool
summary.setCpuCount(hardwareSummary.getNumCpuCores());
@@ -852,27 +850,27 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done");
return summary;
}
-
+
@Override
public VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String managementPortGroup) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.get_value() + ", mgmtPortgroup: " + managementPortGroup);
-
+ s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + managementPortGroup);
+
VmwareHypervisorHostNetworkSummary summary = new VmwareHypervisorHostNetworkSummary();
-
+
if(this.getHostType() == VmwareHostType.ESXi) {
- VirtualNicManagerNetConfig[] netConfigs = (VirtualNicManagerNetConfig[])_context.getServiceUtil().getDynamicProperty(_mor,
+ List netConfigs = (List)_context.getVimClient().getDynamicProperty(_mor,
"config.virtualNicManagerInfo.netConfig");
assert(netConfigs != null);
-
- for(int i = 0; i < netConfigs.length; i++) {
- if(netConfigs[i].getNicType().equals("management")) {
- for(HostVirtualNic nic : netConfigs[i].getCandidateVnic()) {
+
+ for(VirtualNicManagerNetConfig netConfig : netConfigs) {
+ if(netConfig.getNicType().equals("management")) {
+ for(HostVirtualNic nic : netConfig.getCandidateVnic()) {
if(nic.getPortgroup().equals(managementPortGroup)) {
summary.setHostIp(nic.getSpec().getIp().getIpAddress());
summary.setHostNetmask(nic.getSpec().getIp().getSubnetMask());
summary.setHostMacAddress(nic.getSpec().getMac());
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostNetworkSummary() done(successfully)");
return summary;
@@ -882,16 +880,16 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
} else {
// try with ESX path
- HostVirtualNic[] hostVNics = (HostVirtualNic[])_context.getServiceUtil().getDynamicProperty(_mor,
+ List hostVNics = (List)_context.getVimClient().getDynamicProperty(_mor,
"config.network.consoleVnic");
-
+
if(hostVNics != null) {
for(HostVirtualNic vnic : hostVNics) {
if(vnic.getPortgroup().equals(managementPortGroup)) {
summary.setHostIp(vnic.getSpec().getIp().getIpAddress());
summary.setHostNetmask(vnic.getSpec().getIp().getSubnetMask());
summary.setHostMacAddress(vnic.getSpec().getMac());
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostNetworkSummary() done(successfully)");
return summary;
@@ -904,29 +902,29 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
s_logger.trace("vCenter API trace - getHyperHostNetworkSummary() done(failed)");
throw new Exception("Uanble to find management port group " + managementPortGroup);
}
-
+
@Override
public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.get_value());
+ s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.getValue());
//
// This is to adopt the model when using Cluster as a big host while ComputeResourceSummary is used
// directly from VMware resource pool
//
- // When we break cluster hosts into individual hosts used in our resource allocator,
+ // When we break cluster hosts into individual hosts used in our resource allocator,
// we will have to populate ComputeResourceSummary by ourselves here
//
HostHardwareSummary hardwareSummary = getHostHardwareSummary();
-
+
ComputeResourceSummary resourceSummary = new ComputeResourceSummary();
-
+
// TODO: not sure how hyper-threading is counted in VMware
resourceSummary.setNumCpuCores(hardwareSummary.getNumCpuCores());
-
+
// Note: memory here is in Byte unit
resourceSummary.setTotalMemory(hardwareSummary.getMemorySize());
-
+
// Total CPU is based on (# of cores) x Mhz
int totalCpu = hardwareSummary.getCpuMhz() * hardwareSummary.getNumCpuCores();
resourceSummary.setTotalCpu(totalCpu);
@@ -934,30 +932,30 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
HostListSummaryQuickStats stats = getHostQuickStats();
if(stats.getOverallCpuUsage() == null || stats.getOverallMemoryUsage() == null)
throw new Exception("Unable to get valid overal CPU/Memory usage data, host may be disconnected");
-
+
resourceSummary.setEffectiveCpu(totalCpu - stats.getOverallCpuUsage());
-
+
// Note effective memory is in MB unit
resourceSummary.setEffectiveMemory(hardwareSummary.getMemorySize()/(1024*1024) - stats.getOverallMemoryUsage());
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - getHyperHostHardwareSummary() done");
-
+
return resourceSummary;
}
-
+
@Override
public boolean isHyperHostConnected() throws Exception {
- HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)_context.getServiceUtil().getDynamicProperty(_mor, "runtime");
- return runtimeInfo.getConnectionState() == HostSystemConnectionState.connected;
+ HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)_context.getVimClient().getDynamicProperty(_mor, "runtime");
+ return runtimeInfo.getConnectionState() == HostSystemConnectionState.CONNECTED;
}
-
+
public boolean revertToSnapshot(ManagedObjectReference morSnapshot)
throws Exception {
ManagedObjectReference morTask = _context.getService()
- .revertToSnapshot_Task(morSnapshot, _mor, false);
- String result = _context.getServiceUtil().waitForTask(morTask);
- if (result.equals("sucess")) {
+ .revertToSnapshotTask(morSnapshot, _mor, false);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if (result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java
index 90d690c1101..ca362809f3a 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HttpNfcLeaseMO.java
@@ -20,121 +20,142 @@ import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.rmi.RemoteException;
+import java.util.Arrays;
+import java.util.List;
import org.apache.log4j.Logger;
+import org.w3c.dom.Element;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.HttpNfcLeaseInfo;
import com.vmware.vim25.HttpNfcLeaseManifestEntry;
import com.vmware.vim25.HttpNfcLeaseState;
import com.vmware.vim25.ManagedObjectReference;
+import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.OvfCreateImportSpecResult;
import com.vmware.vim25.OvfFileItem;
+import com.vmware.vim25.PropertyFilterSpec;
+import com.vmware.vim25.PropertySpec;
public class HttpNfcLeaseMO extends BaseMO {
private static final Logger s_logger = Logger.getLogger(HttpNfcLeaseMO.class);
-
+
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");
+ Object stateProp = _context.getVimClient().getDynamicProperty(_mor, "state");
+ // Due to some issue in JAX-WS De-serialization getting the information
+ // from the nodes
+ assert (stateProp.toString().contains("val: null"));
+ String stateVal = null;
+ Element stateElement = (Element) stateProp;
+ if (stateElement != null && stateElement.getFirstChild() != null) {
+ stateVal = stateElement.getFirstChild().getTextContent();
+ }
+ if (stateVal != null) {
+ return HttpNfcLeaseState.fromValue(stateVal);
+ }
+ return HttpNfcLeaseState.ERROR;
}
-
+
public HttpNfcLeaseState waitState(HttpNfcLeaseState[] states) throws Exception {
assert(states != null);
assert(states.length > 0);
-
+
HttpNfcLeaseState state;
while(true) {
state = getState();
- if(state == HttpNfcLeaseState.ready || state == HttpNfcLeaseState.error)
+ if(state == HttpNfcLeaseState.READY || state == HttpNfcLeaseState.ERROR)
return state;
}
}
-
+
+
+
public HttpNfcLeaseInfo getLeaseInfo() throws Exception {
- return (HttpNfcLeaseInfo)_context.getServiceUtil().getDynamicProperty(_mor, "info");
+ return (HttpNfcLeaseInfo)_context.getVimClient().getDynamicProperty(_mor, "info");
}
-
- public HttpNfcLeaseManifestEntry[] getLeaseManifest() throws Exception {
+
+ public List getLeaseManifest() throws Exception {
return _context.getService().httpNfcLeaseGetManifest(_mor);
}
-
+
public void completeLease() throws Exception {
_context.getService().httpNfcLeaseComplete(_mor);
}
-
+
public void abortLease() throws Exception {
_context.getService().httpNfcLeaseAbort(_mor, null);
}
-
+
public void updateLeaseProgress(int percent) throws Exception {
// make sure percentage is in right range
if(percent < 0)
percent = 0;
else if(percent > 100)
percent = 100;
-
+
_context.getService().httpNfcLeaseProgress(_mor, percent);
}
-
+
public ProgressReporter createProgressReporter() {
return new ProgressReporter();
}
-
- public static long calcTotalBytes(OvfCreateImportSpecResult ovfImportResult) {
- OvfFileItem[] fileItemArr = ovfImportResult.getFileItem();
- long totalBytes = 0;
- if (fileItemArr != null) {
- for (OvfFileItem fi : fileItemArr) {
- totalBytes += fi.getSize();
- }
- }
- return totalBytes;
- }
-
- public static String readOvfContent(String ovfFilePath) throws IOException {
- StringBuffer strContent = new StringBuffer();
- BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath)));
- String lineStr;
- while ((lineStr = in.readLine()) != null) {
- strContent.append(lineStr);
- }
- in.close();
- return strContent.toString();
+ public static long calcTotalBytes(OvfCreateImportSpecResult ovfImportResult) {
+ List fileItemArr = ovfImportResult.getFileItem();
+ long totalBytes = 0;
+ if (fileItemArr != null) {
+ for (OvfFileItem fi : fileItemArr) {
+ totalBytes += fi.getSize();
+ }
+ }
+ return totalBytes;
}
-
+
+ public static String readOvfContent(String ovfFilePath) throws IOException {
+ StringBuffer strContent = new StringBuffer();
+ BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath)));
+ String lineStr;
+ while ((lineStr = in.readLine()) != null) {
+ strContent.append(lineStr);
+ }
+
+ in.close();
+ return strContent.toString();
+ }
+
public class ProgressReporter extends Thread {
volatile int _percent;
volatile boolean _done;
-
+
public ProgressReporter() {
_percent = 0;
_done = false;
-
+
setDaemon(true);
start();
}
-
+
public void reportProgress(int percent) {
_percent = percent;
}
-
+
public void close() {
if(s_logger.isInfoEnabled())
s_logger.info("close ProgressReporter, interrupt reporter runner to let it quit");
-
+
_done = true;
interrupt();
}
-
+
@Override
public void run() {
while(!_done) {
@@ -149,7 +170,7 @@ public class HttpNfcLeaseMO extends BaseMO {
s_logger.warn("Unexpected exception ", e);
}
}
-
+
if(s_logger.isInfoEnabled())
s_logger.info("ProgressReporter stopped");
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java
index 77862d118bf..621c091481a 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HypervisorHostHelper.java
@@ -74,16 +74,16 @@ public class HypervisorHostHelper {
private static final Logger s_logger = Logger.getLogger(HypervisorHostHelper.class);
private static final int DEFAULT_LOCK_TIMEOUT_SECONDS = 600;
private static final String s_policyNamePrefix = "cloud.policy.";
-
+
// make vmware-base loosely coupled with cloud-specific stuff, duplicate VLAN.UNTAGGED constant here
private static final String UNTAGGED_VLAN_NAME = "untagged";
-
- public static VirtualMachineMO findVmFromObjectContent(VmwareContext context,
+
+ public static VirtualMachineMO findVmFromObjectContent(VmwareContext context,
ObjectContent[] ocs, String name) {
-
+
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty prop = oc.getPropSet(0);
+ DynamicProperty prop = oc.getPropSet().get(0);
assert(prop != null);
if(prop.getVal().toString().equals(name))
return new VirtualMachineMO(context, oc.getObj());
@@ -91,20 +91,20 @@ public class HypervisorHostHelper {
}
return null;
}
-
+
public static ManagedObjectReference findDatastoreWithBackwardsCompatibility(VmwareHypervisorHost hyperHost, String uuidName) throws Exception {
ManagedObjectReference morDs = hyperHost.findDatastore(uuidName.replace("-", ""));
if(morDs == null)
morDs = hyperHost.findDatastore(uuidName);
-
+
return morDs;
}
-
+
public static DatastoreMO getHyperHostDatastoreMO(VmwareHypervisorHost hyperHost, String datastoreName) throws Exception {
ObjectContent[] ocs = hyperHost.getDatastorePropertiesOnHyperHost(new String[] { "name"} );
if(ocs != null && ocs.length > 0) {
for(ObjectContent oc : ocs) {
- DynamicProperty[] objProps = oc.getPropSet();
+ List objProps = oc.getPropSet();
if(objProps != null) {
for(DynamicProperty objProp : objProps) {
if(objProp.getVal().toString().equals(datastoreName))
@@ -115,7 +115,7 @@ public class HypervisorHostHelper {
}
return null;
}
-
+
public static String getPublicNetworkNamePrefix(String vlanId) {
if (UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
return "cloud.public.untagged";
@@ -123,24 +123,24 @@ public class HypervisorHostHelper {
return "cloud.public." + vlanId;
}
}
-
+
public static String composeCloudNetworkName(String prefix, String vlanId, Integer networkRateMbps, String vSwitchName) {
StringBuffer sb = new StringBuffer(prefix);
if(vlanId == null || UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId))
sb.append(".untagged");
else
sb.append(".").append(vlanId);
-
+
if(networkRateMbps != null && networkRateMbps.intValue() > 0)
sb.append(".").append(String.valueOf(networkRateMbps));
else
sb.append(".0");
sb.append(".").append(VersioningContants.PORTGROUP_NAMING_VERSION);
sb.append("-").append(vSwitchName);
-
+
return sb.toString();
}
-
+
public static Map getValidatedVsmCredentials(VmwareContext context) throws Exception {
Map vsmCredentials = context.getStockObject("vsmcredentials");
String msg;
@@ -396,9 +396,9 @@ public class HypervisorHostHelper {
* @param timeOutMs
* @param vSwitchType
* @param numPorts
- * @return
- * @throws Exception
- */
+ * @return
+ * @throws Exception
+ */
public static Pair prepareNetwork(String physicalNetwork, String namePrefix,
HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs,
@@ -417,7 +417,7 @@ public class HypervisorHostHelper {
boolean createGCTag = false;
String networkName;
Integer vid = null;
-
+
if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
@@ -504,22 +504,22 @@ public class HypervisorHostHelper {
} else {
s_logger.info("Found Ethernet port profile " + ethPortProfileName);
}
- long averageBandwidth = 0L;
- if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
- averageBandwidth = (long) (networkRateMbps.intValue() * 1024L * 1024L);
- }
- // We chose 50% higher allocation than average bandwidth.
+ long averageBandwidth = 0L;
+ if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
+ averageBandwidth = (long) (networkRateMbps.intValue() * 1024L * 1024L);
+ }
+ // We chose 50% higher allocation than average bandwidth.
// TODO(sateesh): Optionally let user specify the peak coefficient
- long peakBandwidth = (long) (averageBandwidth * 1.5);
+ long peakBandwidth = (long) (averageBandwidth * 1.5);
// TODO(sateesh): Optionally let user specify the burst coefficient
- long burstSize = 5 * averageBandwidth / 8;
+ long burstSize = 5 * averageBandwidth / 8;
- if (!dataCenterMo.hasDvPortGroup(networkName)) {
- s_logger.info("Port profile " + networkName + " not found.");
+ if (!dataCenterMo.hasDvPortGroup(networkName)) {
+ s_logger.info("Port profile " + networkName + " not found.");
createPortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
- bWaitPortGroupReady = true;
- } else {
- s_logger.info("Port profile " + networkName + " found.");
+ bWaitPortGroupReady = true;
+ } else {
+ s_logger.info("Port profile " + networkName + " found.");
updatePortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
}
}
@@ -533,7 +533,7 @@ public class HypervisorHostHelper {
s_logger.error(msg);
throw new Exception(msg);
}
-
+
if(createGCTag) {
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true");
@@ -563,39 +563,39 @@ public class HypervisorHostHelper {
}
public static boolean isSpecMatch(DVPortgroupConfigInfo configInfo, Integer vid, DVSTrafficShapingPolicy shapingPolicy) {
- DVSTrafficShapingPolicy currentTrafficShapingPolicy;
+ DVSTrafficShapingPolicy currentTrafficShapingPolicy;
currentTrafficShapingPolicy = configInfo.getDefaultPortConfig().getInShapingPolicy();
- assert(currentTrafficShapingPolicy != null);
+ assert(currentTrafficShapingPolicy != null);
- LongPolicy averageBandwidth = currentTrafficShapingPolicy.getAverageBandwidth();
- LongPolicy burstSize = currentTrafficShapingPolicy.getBurstSize();
- LongPolicy peakBandwidth = currentTrafficShapingPolicy.getPeakBandwidth();
- BoolPolicy isEnabled = currentTrafficShapingPolicy.getEnabled();
+ LongPolicy averageBandwidth = currentTrafficShapingPolicy.getAverageBandwidth();
+ LongPolicy burstSize = currentTrafficShapingPolicy.getBurstSize();
+ LongPolicy peakBandwidth = currentTrafficShapingPolicy.getPeakBandwidth();
+ BoolPolicy isEnabled = currentTrafficShapingPolicy.getEnabled();
if (!isEnabled.equals(shapingPolicy.getEnabled())) {
- return false;
+ return false;
}
- if(averageBandwidth != null && !averageBandwidth.equals(shapingPolicy.getAverageBandwidth())) {
- if(s_logger.isInfoEnabled()) {
- s_logger.info("Average bandwidth setting in shaping policy doesn't match with existing setting.");
- }
- return false;
- } else if(burstSize != null && !burstSize.equals(shapingPolicy.getBurstSize())) {
- if(s_logger.isInfoEnabled()) {
- s_logger.info("Burst size setting in shaping policy doesn't match with existing setting.");
- }
- return false;
- } else if(peakBandwidth != null && !peakBandwidth.equals(shapingPolicy.getPeakBandwidth())) {
- if(s_logger.isInfoEnabled()) {
- s_logger.info("Peak bandwidth setting in shaping policy doesn't match with existing setting.");
- }
- return false;
- }
+ if(averageBandwidth != null && !averageBandwidth.equals(shapingPolicy.getAverageBandwidth())) {
+ if(s_logger.isInfoEnabled()) {
+ s_logger.info("Average bandwidth setting in shaping policy doesn't match with existing setting.");
+ }
+ return false;
+ } else if(burstSize != null && !burstSize.equals(shapingPolicy.getBurstSize())) {
+ if(s_logger.isInfoEnabled()) {
+ s_logger.info("Burst size setting in shaping policy doesn't match with existing setting.");
+ }
+ return false;
+ } else if(peakBandwidth != null && !peakBandwidth.equals(shapingPolicy.getPeakBandwidth())) {
+ if(s_logger.isInfoEnabled()) {
+ s_logger.info("Peak bandwidth setting in shaping policy doesn't match with existing setting.");
+ }
+ return false;
+ }
- return true;
- }
+ return true;
+ }
public static DVPortgroupConfigSpec createDvPortGroupSpec(String dvPortGroupName, DVPortSetting portSetting, int numPorts) {
DVPortgroupConfigSpec spec = new DVPortgroupConfigSpec();
@@ -670,7 +670,7 @@ public class HypervisorHostHelper {
}
public static Pair prepareNetwork(String vSwitchName, String namePrefix,
- HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps,
+ HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps,
long timeOutMs, boolean syncPeerHosts) throws Exception {
HostVirtualSwitch vSwitch;
@@ -689,12 +689,12 @@ public class HypervisorHostHelper {
boolean createGCTag = false;
String networkName;
Integer vid = null;
-
+
if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
}
-
+
networkName = composeCloudNetworkName(namePrefix, vlanId, networkRateMbps, vSwitchName);
HostNetworkSecurityPolicy secPolicy = null;
if (namePrefix.equalsIgnoreCase("cloud.private")) {
@@ -708,11 +708,11 @@ public class HypervisorHostHelper {
shapingPolicy = new HostNetworkTrafficShapingPolicy();
shapingPolicy.setEnabled(true);
shapingPolicy.setAverageBandwidth((long)networkRateMbps.intValue()*1024L*1024L);
-
- //
+
+ //
// TODO : people may have different opinion on how to set the following
//
-
+
// give 50% premium to peek
shapingPolicy.setPeakBandwidth((long)(shapingPolicy.getAverageBandwidth()*1.5));
@@ -733,7 +733,7 @@ public class HypervisorHostHelper {
}
ManagedObjectReference morNetwork;
- if(bWaitPortGroupReady)
+ if(bWaitPortGroupReady)
morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);
else
morNetwork = hostMo.getNetworkMor(networkName);
@@ -742,24 +742,24 @@ public class HypervisorHostHelper {
s_logger.error(msg);
throw new Exception(msg);
}
-
+
if(createGCTag) {
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true");
}
-
+
if(syncPeerHosts) {
ManagedObjectReference morParent = hostMo.getParentMor();
if(morParent != null && morParent.getType().equals("ClusterComputeResource")) {
// to be conservative, lock cluster
- GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.get_value());
+ GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.getValue());
try {
if(lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {
try {
- ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getServiceUtil().getDynamicProperty(morParent, "host");
+ List hosts = (List)hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host");
if(hosts != null) {
for(ManagedObjectReference otherHost: hosts) {
- if(!otherHost.get_value().equals(hostMo.getMor().get_value())) {
+ if(!otherHost.getValue().equals(hostMo.getMor().getValue())) {
HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);
try {
if(s_logger.isDebugEnabled())
@@ -786,7 +786,7 @@ public class HypervisorHostHelper {
s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName);
return new Pair(morNetwork, networkName);
}
-
+
private static boolean isSpecMatch(HostPortGroupSpec spec, Integer vlanId, HostNetworkTrafficShapingPolicy shapingPolicy) {
// check VLAN configuration
if(vlanId != null) {
@@ -801,17 +801,17 @@ public class HypervisorHostHelper {
HostNetworkTrafficShapingPolicy policyInSpec = null;
if(spec.getPolicy() != null)
policyInSpec = spec.getPolicy().getShapingPolicy();
-
+
if(policyInSpec != null && shapingPolicy == null || policyInSpec == null && shapingPolicy != null)
return false;
-
+
if(policyInSpec == null && shapingPolicy == null)
return true;
-
+
// so far policyInSpec and shapingPolicy should both not be null
- if(policyInSpec.getEnabled() == null || !policyInSpec.getEnabled().booleanValue())
+ if(policyInSpec.isEnabled() == null || !policyInSpec.isEnabled().booleanValue())
return false;
-
+
if(policyInSpec.getAverageBandwidth() == null || policyInSpec.getAverageBandwidth().longValue() != shapingPolicy.getAverageBandwidth().longValue())
return false;
@@ -820,10 +820,10 @@ public class HypervisorHostHelper {
if(policyInSpec.getBurstSize() == null || policyInSpec.getBurstSize().longValue() != shapingPolicy.getBurstSize().longValue())
return false;
-
+
return true;
}
-
+
public static ManagedObjectReference waitForNetworkReady(HostMO hostMo,
String networkName, long timeOutMs) throws Exception {
@@ -844,14 +844,14 @@ public class HypervisorHostHelper {
return morNetwork;
}
-
- public static boolean createBlankVm(VmwareHypervisorHost host, String vmName,
- int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier,
+
+ public static boolean createBlankVm(VmwareHypervisorHost host, String vmName,
+ int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier,
ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception {
-
+
if(s_logger.isInfoEnabled())
s_logger.info("Create blank VM. cpuCount: " + cpuCount + ", cpuSpeed(MHz): " + cpuSpeedMHz + ", mem(Mb): " + memoryMB);
-
+
// VM config basics
VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();
vmConfig.setName(vmName);
@@ -859,62 +859,63 @@ public class HypervisorHostHelper {
// Scsi controller
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
- scsiController.setSharedBus(VirtualSCSISharing.noSharing);
+ scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
scsiController.setBusNumber(0);
scsiController.setKey(1);
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
scsiControllerSpec.setDevice(scsiController);
- scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
+ scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
DatastoreMO dsMo = new DatastoreMO(host.getContext(), morDs);
fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
vmConfig.setFiles(fileInfo);
-
+
VirtualMachineVideoCard videoCard = new VirtualMachineVideoCard();
videoCard.setControllerKey(100);
videoCard.setUseAutoDetect(true);
-
+
VirtualDeviceConfigSpec videoDeviceSpec = new VirtualDeviceConfigSpec();
videoDeviceSpec.setDevice(videoCard);
- videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
-
- vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec, videoDeviceSpec });
+ videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+
+ vmConfig.getDeviceChange().add(scsiControllerSpec);
+ vmConfig.getDeviceChange().add(videoDeviceSpec);
if(host.createVm(vmConfig)) {
VirtualMachineMO vmMo = host.findVmOnHyperHost(vmName);
assert(vmMo != null);
-
+
int ideControllerKey = -1;
while(ideControllerKey < 0) {
ideControllerKey = vmMo.tryGetIDEDeviceControllerKey();
if(ideControllerKey >= 0)
break;
-
+
s_logger.info("Waiting for IDE controller be ready in VM: " + vmName);
Thread.sleep(1000);
}
-
+
if(snapshotDirToParent) {
String snapshotDir = String.format("/vmfs/volumes/%s/", dsMo.getName());
-
+
s_logger.info("Switch snapshot working directory to " + snapshotDir + " for " + vmName);
vmMo.setSnapshotDirectory(snapshotDir);
-
+
// Don't have a good way to test if the VM is really ready for use through normal API after configuration file manipulation,
// delay 3 seconds
Thread.sleep(3000);
}
-
+
s_logger.info("Blank VM: " + vmName + " is ready for use");
return true;
}
return false;
}
-
+
public static String resolveHostNameInUrl(DatacenterMO dcMo, String url) {
-
+
s_logger.info("Resolving host name in url through vCenter, url: " + url);
-
+
URI uri;
try {
uri = new URI(url);
@@ -922,13 +923,13 @@ public class HypervisorHostHelper {
s_logger.warn("URISyntaxException on url " + url);
return url;
}
-
+
String host = uri.getHost();
if(NetUtils.isValidIp(host)) {
s_logger.info("host name in url is already in IP address, url: " + url);
return url;
}
-
+
try {
ManagedObjectReference morHost = dcMo.findHost(host);
if(morHost != null) {
@@ -938,18 +939,18 @@ public class HypervisorHostHelper {
managementPortGroupName = (String)dcMo.getContext().getStockObject("manageportgroup");
else
managementPortGroupName = (String)dcMo.getContext().getStockObject("serviceconsole");
-
+
VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(managementPortGroupName);
if(summary == null) {
s_logger.warn("Unable to resolve host name in url through vSphere, url: " + url);
return url;
}
-
+
String hostIp = summary.getHostIp();
-
+
try {
URI resolvedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostIp, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
-
+
s_logger.info("url " + url + " is resolved to " + resolvedUri.toString() + " through vCenter");
return resolvedUri.toString();
} catch (URISyntaxException e) {
@@ -960,41 +961,41 @@ public class HypervisorHostHelper {
} catch(Exception e) {
s_logger.warn("Unexpected exception ", e);
}
-
+
return url;
}
-
- public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption,
+
+ public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption,
ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {
-
+
assert(morRp != null);
-
- OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
- importSpecParams.setHostSystem(morHost);
- importSpecParams.setLocale("US");
- importSpecParams.setEntityName(vmName);
+
+ OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
+ importSpecParams.setHostSystem(morHost);
+ importSpecParams.setLocale("US");
+ importSpecParams.setEntityName(vmName);
importSpecParams.setDeploymentOption("");
importSpecParams.setDiskProvisioning(diskOption); // diskOption: thin, thick, etc
- importSpecParams.setPropertyMapping(null);
-
+ //importSpecParams.setPropertyMapping(null);
+
String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath);
VmwareContext context = host.getContext();
OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(
- context.getServiceContent().getOvfManager(), ovfDescriptor, morRp,
+ context.getServiceContent().getOvfManager(), ovfDescriptor, morRp,
dsMo.getMor(), importSpecParams);
-
+
if(ovfImportResult == null) {
- String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
+ String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
+ vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
- ManagedObjectReference morLease = context.getService().importVApp(morRp,
+ ManagedObjectReference morLease = context.getService().importVApp(morRp,
ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
if(morLease == null) {
- String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
+ String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
+ vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new Exception(msg);
@@ -1002,56 +1003,56 @@ public class HypervisorHostHelper {
boolean importSuccess = true;
final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
HttpNfcLeaseState state = leaseMo.waitState(
- new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
+ new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
try {
- if(state == HttpNfcLeaseState.ready) {
+ if(state == HttpNfcLeaseState.READY) {
final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
- File ovfFile = new File(ovfFilePath);
-
+ File ovfFile = new File(ovfFilePath);
+
HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
- HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
+ List deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
long bytesAlreadyWritten = 0;
-
+
final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
try {
for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
- String deviceKey = deviceUrl.getImportKey();
+ String deviceKey = deviceUrl.getImportKey();
for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
- if (deviceKey.equals(ovfFileItem.getDeviceId())) {
+ if (deviceKey.equals(ovfFileItem.getDeviceId())) {
String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
String urlToPost = deviceUrl.getUrl();
urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
-
- context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile,
+
+ context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile,
bytesAlreadyWritten, new ActionDelegate () {
public void action(Long param) {
progressReporter.reportProgress((int)(param * 100 / totalBytes));
}
- });
-
+ });
+
bytesAlreadyWritten += ovfFileItem.getSize();
- }
- }
+ }
+ }
}
} catch (Exception e) {
s_logger.error("Failed to complete file upload task. " + e.getMessage());
// Set flag to cleanup the stale template left due to failed import operation, if any
importSuccess = false;
throw e;
- } finally {
- progressReporter.close();
- }
+ } finally {
+ progressReporter.close();
+ }
if (bytesAlreadyWritten == totalBytes) {
- leaseMo.updateLeaseProgress(100);
- }
+ leaseMo.updateLeaseProgress(100);
+ }
}
- } finally {
+ } finally {
if (!importSuccess) {
s_logger.error("Aborting the lease on " + vmName + " after import operation failed.");
leaseMo.abortLease();
} else {
- leaseMo.completeLease();
- }
+ 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 dadd7d12a01..df82f155cf1 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/NetworkMO.java
@@ -16,6 +16,8 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
+import java.util.List;
+
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.ManagedObjectReference;
@@ -23,17 +25,16 @@ public class NetworkMO extends BaseMO {
public NetworkMO(VmwareContext context, ManagedObjectReference morCluster) {
super(context, morCluster);
}
-
+
public NetworkMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public void destroyNetwork() throws Exception {
- _context.getService().destroyNetwork(_mor);
+ _context.getService().destroyNetwork(_mor);
}
-
- public ManagedObjectReference[] getVMsOnNetwork() throws Exception {
- ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "vm");
- return vms;
+
+ public List getVMsOnNetwork() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(_mor, "vm");
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java
index 5d57bd1fb09..bb4fb56ebbc 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/PerfManagerMO.java
@@ -16,7 +16,13 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
+import java.util.ArrayList;
import java.util.Calendar;
+import java.util.List;
+
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.vmware.vim25.ManagedObjectReference;
@@ -28,58 +34,91 @@ import com.vmware.vim25.PerfMetricId;
import com.vmware.vim25.PerfProviderSummary;
import com.vmware.vim25.PerfQuerySpec;
+import edu.emory.mathcs.backport.java.util.Arrays;
+
public class PerfManagerMO extends BaseMO {
public PerfManagerMO(VmwareContext context, ManagedObjectReference mor) {
super(context, mor);
}
-
+
public PerfManagerMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public void createPerfInterval(PerfInterval interval) throws Exception {
_context.getService().createPerfInterval(_mor, interval);
}
-
- public PerfMetricId[] queryAvailablePerfMetric(ManagedObjectReference morEntity, Calendar beginTime,
+
+ /**
+ * Converts Calendar object into XMLGregorianCalendar
+ *
+ * @param calendar Object to be converted
+ * @return XMLGregorianCalendar
+ */
+ private XMLGregorianCalendar calendarToXMLGregorianCalendar(Calendar calendar) throws DatatypeConfigurationException {
+
+ DatatypeFactory dtf = DatatypeFactory.newInstance();
+ XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar();
+ xgc.setYear(calendar.get(Calendar.YEAR));
+ xgc.setMonth(calendar.get(Calendar.MONTH) + 1);
+ xgc.setDay(calendar.get(Calendar.DAY_OF_MONTH));
+ xgc.setHour(calendar.get(Calendar.HOUR_OF_DAY));
+ xgc.setMinute(calendar.get(Calendar.MINUTE));
+ xgc.setSecond(calendar.get(Calendar.SECOND));
+ xgc.setMillisecond(calendar.get(Calendar.MILLISECOND));
+
+ // Calendar ZONE_OFFSET and DST_OFFSET fields are in milliseconds.
+ int offsetInMinutes = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000);
+ xgc.setTimezone(offsetInMinutes);
+ return xgc;
+ }
+
+ public List queryAvailablePerfMetric(ManagedObjectReference morEntity, Calendar beginTime,
Calendar endTime, Integer intervalId) throws Exception {
-
- return _context.getService().queryAvailablePerfMetric(_mor, morEntity, beginTime, endTime, intervalId);
+
+ return _context.getService().queryAvailablePerfMetric(_mor, morEntity, calendarToXMLGregorianCalendar(beginTime),
+ calendarToXMLGregorianCalendar(endTime), intervalId);
}
public PerfCompositeMetric queryPerfComposite(PerfQuerySpec spec) throws Exception {
return _context.getService().queryPerfComposite(_mor, spec);
}
-
- public PerfCounterInfo[] queryPerfCounter(int[] counterId) throws Exception {
- return _context.getService().queryPerfCounter(_mor, counterId);
- }
-
- public PerfCounterInfo[] queryPerfCounterByLevel(int level) throws Exception {
- return _context.getService().queryPerfCounterByLevel(_mor, level);
- }
-
- public PerfProviderSummary queryPerfProviderSummary(ManagedObjectReference morEntity) throws Exception {
- return _context.getService().queryPerfProviderSummary(_mor, morEntity);
+
+ public List queryPerfCounter(int[] counterId) throws Exception {
+ List counterArr = new ArrayList();
+ if ( counterId != null){
+ for (int i = 0; i < counterId.length; i++ ){
+ counterArr.add(counterId[i]);
+ }
+ }
+ return _context.getService().queryPerfCounter(_mor, counterArr);
}
- public PerfEntityMetricBase[] queryPerf(PerfQuerySpec[] specs) throws Exception {
- return _context.getService().queryPerf(_mor, specs);
+ public List queryPerfCounterByLevel(int level) throws Exception {
+ return _context.getService().queryPerfCounterByLevel(_mor, level);
}
-
+
+ public PerfProviderSummary queryPerfProviderSummary(ManagedObjectReference morEntity) throws Exception {
+ return _context.getService().queryPerfProviderSummary(_mor, morEntity);
+ }
+
+ public List queryPerf(PerfQuerySpec[] specs) throws Exception {
+ return _context.getService().queryPerf(_mor, Arrays.asList(specs));
+ }
+
public void removePerfInterval(int samplePeriod) throws Exception {
_context.getService().removePerfInterval(_mor, samplePeriod);
}
-
+
public void updatePerfInterval(PerfInterval interval) throws Exception {
_context.getService().updatePerfInterval(_mor, interval);
}
-
- public PerfCounterInfo[] getCounterInfo() throws Exception {
- return (PerfCounterInfo[])_context.getServiceUtil().getDynamicProperty(_mor, "perfCounter");
+
+ public List getCounterInfo() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(_mor, "perfCounter");
}
-
- public PerfInterval[] getIntervalInfo() throws Exception {
- return (PerfInterval[])_context.getServiceUtil().getDynamicProperty(_mor, "historicalInterval");
+
+ public List getIntervalInfo() throws Exception {
+ return (List)_context.getVimClient().getDynamicProperty(_mor, "historicalInterval");
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java
index 3b0b153dc7f..694734bf09a 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/TaskMO.java
@@ -27,48 +27,48 @@ public class TaskMO extends BaseMO {
public TaskMO(VmwareContext context, ManagedObjectReference morTask) {
super(context, morTask);
}
-
+
public TaskMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public TaskInfo getTaskInfo() throws Exception {
- return (TaskInfo)getContext().getServiceUtil().getDynamicProperty(_mor, "info");
+ return (TaskInfo)getContext().getVimClient().getDynamicProperty(_mor, "info");
}
-
+
public void setTaskDescription(LocalizableMessage description) throws Exception {
_context.getService().setTaskDescription(_mor, description);
}
-
+
public void setTaskState(TaskInfoState state, Object result, LocalizedMethodFault fault) throws Exception {
_context.getService().setTaskState(_mor, state, result, fault);
}
-
+
public void updateProgress(int percentDone) throws Exception {
_context.getService().updateProgress(_mor, percentDone);
}
-
+
public void cancelTask() throws Exception {
_context.getService().cancelTask(_mor);
}
-
+
public static String getTaskFailureInfo(VmwareContext context, ManagedObjectReference morTask) {
StringBuffer sb = new StringBuffer();
-
+
try {
- TaskInfo info = (TaskInfo)context.getServiceUtil().getDynamicProperty(morTask, "info");
+ TaskInfo info = (TaskInfo)context.getVimClient().getDynamicProperty(morTask, "info");
if(info != null) {
LocalizedMethodFault fault = info.getError();
if(fault != null) {
sb.append(fault.getLocalizedMessage()).append(" ");
-
+
if(fault.getFault() != null)
sb.append(fault.getFault().getClass().getName());
}
}
} catch(Exception e) {
}
-
+
return sb.toString();
}
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java
index aab82100421..e21d06adf62 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualDiskManagerMO.java
@@ -25,132 +25,132 @@ import com.vmware.vim25.VirtualDiskSpec;
public class VirtualDiskManagerMO extends BaseMO {
private static final Logger s_logger = Logger.getLogger(VirtualDiskManagerMO.class);
-
+
public VirtualDiskManagerMO(VmwareContext context, ManagedObjectReference morDiskMgr) {
super(context, morDiskMgr);
}
-
+
public VirtualDiskManagerMO(VmwareContext context, String morType, String morValue) {
super(context, morType, morValue);
}
-
+
public void copyVirtualDisk(String srcName, ManagedObjectReference morSrcDc,
- String destName, ManagedObjectReference morDestDc, VirtualDiskSpec diskSpec,
+ String destName, ManagedObjectReference morDestDc, VirtualDiskSpec diskSpec,
boolean force) throws Exception {
-
- ManagedObjectReference morTask = _context.getService().copyVirtualDisk_Task(_mor, srcName, morSrcDc, destName, morDestDc, diskSpec, force);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
- throw new Exception("Unable to copy virtual disk " + srcName + " to " + destName
- + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
-
- _context.waitForTaskProgressDone(morTask);
- }
-
- public void createVirtualDisk(String name, ManagedObjectReference morDc, VirtualDiskSpec diskSpec) throws Exception {
- ManagedObjectReference morTask = _context.getService().createVirtualDisk_Task(_mor, name, morDc, diskSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
- throw new Exception("Unable to create virtual disk " + name
+
+ ManagedObjectReference morTask = _context.getService().copyVirtualDiskTask(_mor, srcName, morSrcDc, destName, morDestDc, diskSpec, force);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
+ throw new Exception("Unable to copy virtual disk " + srcName + " to " + destName
+ " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
+ public void createVirtualDisk(String name, ManagedObjectReference morDc, VirtualDiskSpec diskSpec) throws Exception {
+ ManagedObjectReference morTask = _context.getService().createVirtualDiskTask(_mor, name, morDc, diskSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
+ throw new Exception("Unable to create virtual disk " + name
+ + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
+
+ _context.waitForTaskProgressDone(morTask);
+ }
+
public void defragmentVirtualDisk(String name, ManagedObjectReference morDc) throws Exception {
- ManagedObjectReference morTask = _context.getService().defragmentVirtualDisk_Task(_mor, name, morDc);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().defragmentVirtualDiskTask(_mor, name, morDc);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to defragment virtual disk " + name + " due to " + result);
_context.waitForTaskProgressDone(morTask);
}
-
+
public void deleteVirtualDisk(String name, ManagedObjectReference morDc) throws Exception {
- ManagedObjectReference morTask = _context.getService().deleteVirtualDisk_Task(_mor, name, morDc);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().deleteVirtualDiskTask(_mor, name, morDc);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to delete virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public void eagerZeroVirtualDisk(String name, ManagedObjectReference morDc) throws Exception {
- ManagedObjectReference morTask = _context.getService().eagerZeroVirtualDisk_Task(_mor, name, morDc);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().eagerZeroVirtualDiskTask(_mor, name, morDc);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to eager zero virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public void extendVirtualDisk(String name, ManagedObjectReference morDc, long newCapacityKb, boolean eagerZero) throws Exception {
- ManagedObjectReference morTask = _context.getService().extendVirtualDisk_Task(_mor, name, morDc, newCapacityKb, eagerZero);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().extendVirtualDiskTask(_mor, name, morDc, newCapacityKb, eagerZero);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to extend virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public void inflateVirtualDisk(String name, ManagedObjectReference morDc) throws Exception {
- ManagedObjectReference morTask = _context.getService().inflateVirtualDisk_Task(_mor, name, morDc);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().inflateVirtualDiskTask(_mor, name, morDc);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to inflate virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public void shrinkVirtualDisk(String name, ManagedObjectReference morDc, boolean copy) throws Exception {
- ManagedObjectReference morTask = _context.getService().shrinkVirtualDisk_Task(_mor, name, morDc, copy);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().shrinkVirtualDiskTask(_mor, name, morDc, copy);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to shrink virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public void zeroFillVirtualDisk(String name, ManagedObjectReference morDc) throws Exception {
- ManagedObjectReference morTask = _context.getService().zeroFillVirtualDisk_Task(_mor, name, morDc);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
+ ManagedObjectReference morTask = _context.getService().zeroFillVirtualDiskTask(_mor, name, morDc);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
throw new Exception("Unable to zero fill virtual disk " + name + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public void moveVirtualDisk(String srcName, ManagedObjectReference morSrcDc,
String destName, ManagedObjectReference morDestDc, boolean force) throws Exception {
-
- ManagedObjectReference morTask = _context.getService().moveVirtualDisk_Task(_mor, srcName, morSrcDc,
+
+ ManagedObjectReference morTask = _context.getService().moveVirtualDiskTask(_mor, srcName, morSrcDc,
destName, morDestDc, force);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(!result.equals("sucess"))
- throw new Exception("Unable to move virtual disk " + srcName + " to " + destName
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(!result)
+ throw new Exception("Unable to move virtual disk " + srcName + " to " + destName
+ " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
_context.waitForTaskProgressDone(morTask);
}
-
+
public int queryVirtualDiskFragmentation(String name, ManagedObjectReference morDc) throws Exception {
return _context.getService().queryVirtualDiskFragmentation(_mor, name, morDc);
}
-
+
public HostDiskDimensionsChs queryVirtualDiskGeometry(String name, ManagedObjectReference morDc) throws Exception {
return _context.getService().queryVirtualDiskGeometry(_mor, name, morDc);
}
-
+
public String queryVirtualDiskUuid(String name, ManagedObjectReference morDc) throws Exception {
return _context.getService().queryVirtualDiskUuid(_mor, name, morDc);
}
-
+
public void setVirtualDiskUuid(String name, ManagedObjectReference morDc, String uuid) throws Exception {
_context.getService().setVirtualDiskUuid(_mor, name, morDc, uuid);
}
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java
index d36814d9148..4503349edf1 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/VirtualMachineMO.java
@@ -97,28 +97,30 @@ import com.vmware.vim25.VirtualPCIController;
import com.vmware.vim25.VirtualSCSIController;
import com.vmware.vim25.VirtualSCSISharing;
+import edu.emory.mathcs.backport.java.util.Arrays;
+
public class VirtualMachineMO extends BaseMO {
private static final Logger s_logger = Logger.getLogger(VirtualMachineMO.class);
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" });
-
+ pSpec.getPathSet().add("name");
+
TraversalSpec vmDatastoreTraversal = new TraversalSpec();
vmDatastoreTraversal.setType("VirtualMachine");
vmDatastoreTraversal.setPath("datastore");
@@ -127,41 +129,43 @@ public class VirtualMachineMO extends BaseMO {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { vmDatastoreTraversal });
+ oSpec.getSelectSet().add(vmDatastoreTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
+
if(ocs != null) {
for(ObjectContent oc : ocs) {
- DynamicProperty prop = oc.getPropSet(0);
+ DynamicProperty prop = oc.getPropSet().get(0);
if(prop.getVal().toString().equals(dsName)) {
return new Pair(new DatastoreMO(_context, oc.getObj()), dsName);
}
}
}
-
+
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");
+ return (String)getContext().getVimClient().getDynamicProperty(_mor, "name");
}
-
+
public GuestInfo getVmGuestInfo() throws Exception {
- return (GuestInfo)getContext().getServiceUtil().getDynamicProperty(_mor, "guest");
+ return (GuestInfo)getContext().getVimClient().getDynamicProperty(_mor, "guest");
}
-
+
public boolean isVMwareToolsRunning() throws Exception {
GuestInfo guestInfo = getVmGuestInfo();
if(guestInfo != null) {
@@ -170,100 +174,100 @@ public class VirtualMachineMO extends BaseMO {
}
return false;
}
-
+
public boolean powerOn() throws Exception {
- if(getPowerState() == VirtualMachinePowerState.poweredOn)
+ if(getPowerState() == VirtualMachinePowerState.POWERED_ON)
return true;
-
- ManagedObjectReference morTask = _context.getService().powerOnVM_Task(_mor, null);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ ManagedObjectReference morTask = _context.getService().powerOnVMTask(_mor, null);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_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)
+ if(getPowerState() == VirtualMachinePowerState.POWERED_OFF)
return true;
-
+
return powerOffNoCheck();
}
-
+
public boolean safePowerOff(int shutdownWaitMs) throws Exception {
-
- if(getPowerState() == VirtualMachinePowerState.poweredOff)
+
+ if(getPowerState() == VirtualMachinePowerState.POWERED_OFF)
return true;
-
+
if(isVMwareToolsRunning()) {
try {
String vmName = this.getName();
-
+
s_logger.info("Try gracefully shut down VM " + vmName);
shutdown();
-
+
long startTick = System.currentTimeMillis();
- while(getPowerState() != VirtualMachinePowerState.poweredOff && System.currentTimeMillis() - startTick < shutdownWaitMs) {
- try {
+ while(getPowerState() != VirtualMachinePowerState.POWERED_OFF && System.currentTimeMillis() - startTick < shutdownWaitMs) {
+ try {
Thread.sleep(1000);
} catch(InterruptedException e) {
}
}
-
- if(getPowerState() != VirtualMachinePowerState.poweredOff) {
+
+ if(getPowerState() != VirtualMachinePowerState.POWERED_OFF) {
s_logger.info("can not gracefully shutdown VM within " + (shutdownWaitMs/1000) + " seconds, we will perform force power off on VM " + vmName);
return powerOffNoCheck();
}
-
+
return true;
} catch(Exception e) {
- s_logger.warn("Failed to do guest-os graceful shutdown due to " + VmwareHelper.getExceptionMessage(e));
+ s_logger.warn("Failed to do guest-os graceful shutdown due to " + VmwareHelper.getExceptionMessage(e));
}
}
-
+
return powerOffNoCheck();
}
-
+
private boolean powerOffNoCheck() throws Exception {
- ManagedObjectReference morTask = _context.getService().powerOffVM_Task(_mor);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().powerOffVMTask(_mor);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
-
+
// It seems that even if a power-off task is returned done, VM state may still not be marked,
// wait up to 5 seconds to make sure to avoid race conditioning for immediate following on operations
// that relies on a powered-off VM
long startTick = System.currentTimeMillis();
- while(getPowerState() != VirtualMachinePowerState.poweredOff && System.currentTimeMillis() - startTick < 5000) {
- try {
+ while(getPowerState() != VirtualMachinePowerState.POWERED_OFF && System.currentTimeMillis() - startTick < 5000) {
+ try {
Thread.sleep(1000);
} catch(InterruptedException e) {
}
}
return true;
} else {
- if(getPowerState() == VirtualMachinePowerState.poweredOff) {
- // to help deal with possible race-condition
+ if(getPowerState() == VirtualMachinePowerState.POWERED_OFF) {
+ // to help deal with possible race-condition
s_logger.info("Current power-off task failed. However, VM has been switched to the state we are expecting for");
return true;
}
-
+
s_logger.error("VMware powerOffVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
return false;
}
-
+
public VirtualMachinePowerState getPowerState() throws Exception {
-
- VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff;
-
+
+ VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF;
+
// This is really ugly, there is a case that when windows guest VM is doing sysprep, the temporary
// rebooting process may let us pick up a "poweredOff" state during VMsync process, this can trigger
// a series actions. Unfortunately, from VMware API we can not distinguish power state into such details.
@@ -272,8 +276,8 @@ public class VirtualMachineMO extends BaseMO {
// In the future, VMsync should not kick off CloudStack action (this is not a HA case) based on VM
// state report, until then we can remove this hacking fix
for(int i = 0; i < 3; i++) {
- powerState = (VirtualMachinePowerState)getContext().getServiceUtil().getDynamicProperty(_mor, "runtime.powerState");
- if(powerState == VirtualMachinePowerState.poweredOff) {
+ powerState = (VirtualMachinePowerState)getContext().getVimClient().getDynamicProperty(_mor, "runtime.powerState");
+ if(powerState == VirtualMachinePowerState.POWERED_OFF) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
@@ -282,15 +286,15 @@ public class VirtualMachineMO extends BaseMO {
break;
}
}
-
+
return powerState;
}
-
+
public boolean reset() throws Exception {
- ManagedObjectReference morTask = _context.getService().resetVM_Task(_mor);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().resetVMTask(_mor);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -298,69 +302,69 @@ public class VirtualMachineMO extends BaseMO {
}
return false;
}
-
+
public void shutdown() throws Exception {
_context.getService().shutdownGuest(_mor);
}
-
+
public void rebootGuest() throws Exception {
_context.getService().rebootGuest(_mor);
}
-
+
public void markAsTemplate() throws Exception {
_context.getService().markAsTemplate(_mor);
}
-
+
public boolean isTemplate() throws Exception {
VirtualMachineConfigInfo configInfo = this.getConfigInfo();
return configInfo.isTemplate();
}
-
+
public boolean migrate(ManagedObjectReference morRp, ManagedObjectReference morTargetHost) throws Exception {
- ManagedObjectReference morTask = _context.getService().migrateVM_Task(_mor,
- morRp, morTargetHost, VirtualMachineMovePriority.defaultPriority, null);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().migrateVMTask(_mor,
+ morRp, morTargetHost, VirtualMachineMovePriority.DEFAULT_PRIORITY, null);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_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,
+
+ ManagedObjectReference morTask = _context.getService().relocateVMTask(_mor,
relocateSpec, null);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
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");
+ return (VirtualMachineSnapshotInfo)_context.getVimClient().getDynamicProperty(_mor, "snapshot");
}
-
- public boolean createSnapshot(String snapshotName, String snapshotDescription,
+
+ public boolean createSnapshot(String snapshotName, String snapshotDescription,
boolean dumpMemory, boolean quiesce) throws Exception {
-
- ManagedObjectReference morTask = _context.getService().createSnapshot_Task(_mor, snapshotName,
+
+ ManagedObjectReference morTask = _context.getService().createSnapshotTask(_mor, snapshotName,
snapshotDescription, dumpMemory, quiesce);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
ManagedObjectReference morSnapshot = null;
@@ -371,40 +375,40 @@ public class VirtualMachineMO extends BaseMO {
if(morSnapshot != null) {
break;
}
-
+
try { Thread.sleep(1000); } catch(InterruptedException e) {}
}
-
+
if(morSnapshot == null)
s_logger.error("We've been waiting for over 10 seconds for snapshot MOR to be appearing in vCenter after CreateSnapshot task is done, but it is still not there?!");
-
+
return true;
} else {
s_logger.error("VMware createSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
return false;
}
-
+
public boolean removeSnapshot(String snapshotName, boolean removeChildren) throws Exception {
ManagedObjectReference morSnapshot = getSnapshotMor(snapshotName);
if(morSnapshot == null) {
s_logger.warn("Unable to find snapshot: " + snapshotName);
return false;
}
-
- ManagedObjectReference morTask = _context.getService().removeSnapshot_Task(morSnapshot, removeChildren);
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+
+ ManagedObjectReference morTask = _context.getService().removeSnapshotTask(morSnapshot, removeChildren, true);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
return false;
}
-
+
public boolean revertToSnapshot(String snapshotName) throws Exception {
ManagedObjectReference morSnapshot = getSnapshotMor(snapshotName);
if (morSnapshot == null) {
@@ -412,9 +416,9 @@ public class VirtualMachineMO extends BaseMO {
return false;
}
ManagedObjectReference morTask = _context.getService()
- .revertToSnapshot_Task(morSnapshot, _mor, null);
- String result = _context.getServiceUtil().waitForTask(morTask);
- if (result.equals("sucess")) {
+ .revertToSnapshotTask(morSnapshot, _mor, null);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if (result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -424,16 +428,16 @@ public class VirtualMachineMO extends BaseMO {
return false;
}
-
+
public boolean removeAllSnapshots() throws Exception {
VirtualMachineSnapshotInfo snapshotInfo = getSnapshotInfo();
-
+
if(snapshotInfo != null && snapshotInfo.getRootSnapshotList() != null) {
- VirtualMachineSnapshotTree[] tree = snapshotInfo.getRootSnapshotList();
+ List tree = snapshotInfo.getRootSnapshotList();
for(VirtualMachineSnapshotTree treeNode : tree) {
- ManagedObjectReference morTask = _context.getService().removeSnapshot_Task(treeNode.getSnapshot(), true);
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().removeSnapshotTask(treeNode.getSnapshot(), true, true);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
} else {
s_logger.error("VMware removeSnapshot_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
@@ -441,88 +445,90 @@ public class VirtualMachineMO extends BaseMO {
}
}
}
-
+
return true;
}
-
- public String getSnapshotDiskFileDatastorePath(VirtualMachineFileInfo vmFileInfo,
+
+ public String getSnapshotDiskFileDatastorePath(VirtualMachineFileInfo vmFileInfo,
List> datastoreMounts,
String snapshotDiskFile) throws Exception {
-
+
// if file path start with "/", need to search all datastore mounts on the host in order
- // to form fully qualified datastore path
+ // to form fully qualified datastore path
if(snapshotDiskFile.startsWith("/")) {
for(Pair mount: datastoreMounts) {
if(snapshotDiskFile.startsWith(mount.second())) {
DatastoreMO dsMo = new DatastoreMO(_context, mount.first());
-
+
String dsFullPath = String.format("[%s] %s", dsMo.getName(), snapshotDiskFile.substring(mount.second().length() + 1));
s_logger.info("Convert snapshot disk file name to datastore path. " + snapshotDiskFile + "->" + dsFullPath);
return dsFullPath;
}
}
-
+
s_logger.info("Convert snapshot disk file name to datastore path. " + snapshotDiskFile + "->" + snapshotDiskFile);
return snapshotDiskFile;
} else {
-
- // snapshot directory string from VirtualMachineFileInfo ends with /
+
+ // snapshot directory string from VirtualMachineFileInfo ends with /
String dsFullPath = vmFileInfo.getSnapshotDirectory() + snapshotDiskFile;
s_logger.info("Convert snapshot disk file name to datastore path. " + snapshotDiskFile + "->" + dsFullPath);
return dsFullPath;
}
}
-
+
public SnapshotDescriptor getSnapshotDescriptor() throws Exception {
Pair dcPair = getOwnerDatacenter();
-
+
String dsPath = getSnapshotDescriptorDatastorePath();
assert(dsPath != null);
String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), dsPath);
byte[] content = getContext().getResourceContent(url);
-
+
if(content == null || content.length < 1) {
s_logger.warn("Snapshot descriptor file (vsd) does not exist anymore?");
}
-
+
SnapshotDescriptor descriptor = new SnapshotDescriptor();
descriptor.parse(content);
return descriptor;
}
-
+
public String getSnapshotDescriptorDatastorePath() throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
- pSpec.setPathSet(new String[] { "name", "config.files" });
-
+ pSpec.getPathSet().add("name");
+ pSpec.getPathSet().add("config.files");
+
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.FALSE);
-
+
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
assert(ocs != null);
String vmName = null;
VirtualMachineFileInfo fileInfo = null;
-
- assert(ocs.length == 1);
+
+ assert(ocs.size() == 1);
for(ObjectContent oc : ocs) {
- DynamicProperty[] props = oc.getPropSet();
+ List props = oc.getPropSet();
if(props != null) {
- assert(props.length == 2);
-
+ assert(props.size() == 2);
+
for(DynamicProperty prop : props) {
if(prop.getName().equals("name")) {
vmName = prop.getVal().toString();
} else {
- fileInfo = (VirtualMachineFileInfo)prop.getVal();
+ fileInfo = (VirtualMachineFileInfo)prop.getVal();
}
}
}
@@ -534,116 +540,117 @@ public class VirtualMachineMO extends BaseMO {
DatastoreFile vmxFile = new DatastoreFile(fileInfo.getVmPathName());
return vmxFile.getCompanionPath(vmName + ".vmsd");
}
-
+
public ManagedObjectReference getSnapshotMor(String snapshotName) throws Exception {
VirtualMachineSnapshotInfo info = getSnapshotInfo();
if(info != null) {
- VirtualMachineSnapshotTree[] snapTree = info.getRootSnapshotList();
- return VmwareHelper.findSnapshotInTree(snapTree, snapshotName);
+ List snapTree = info.getRootSnapshotList();
+ return VmwareHelper.findSnapshotInTree(snapTree, snapshotName);
}
return null;
}
-
- public boolean createFullClone(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool,
+
+ public boolean createFullClone(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool,
ManagedObjectReference morDs) throws Exception {
-
+
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec();
cloneSpec.setLocation(relocSpec);
cloneSpec.setPowerOn(false);
cloneSpec.setTemplate(false);
-
+
relocSpec.setDatastore(morDs);
relocSpec.setPool(morResourcePool);
- ManagedObjectReference morTask = _context.getService().cloneVM_Task(_mor, morFolder, cloneName, cloneSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_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,
+
+ 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);
+ List diskLocator = new ArrayList(independentDisks.length);
+ for(int i = 0; i < independentDisks.length; i++) {
+ VirtualMachineRelocateSpecDiskLocator loc = new VirtualMachineRelocateSpecDiskLocator();
+ loc.setDatastore(morDs);
+ loc.setDiskId(independentDisks[i].getKey());
+ loc.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING.value());
+ diskLocator.add(loc);
}
-
- rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._createNewChildDiskBacking);
- rSpec.setDisk(diskLocator);
+
+ rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.value());
+ rSpec.getDisk().addAll(diskLocator);
} else {
- rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions._createNewChildDiskBacking);
+ rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.value());
}
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")) {
+
+ ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_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(
+ return (VirtualMachineRuntimeInfo)_context.getVimClient().getDynamicProperty(
_mor, "runtime");
}
-
+
public VirtualMachineConfigInfo getConfigInfo() throws Exception {
- return (VirtualMachineConfigInfo)_context.getServiceUtil().getDynamicProperty(
+ return (VirtualMachineConfigInfo)_context.getVimClient().getDynamicProperty(
_mor, "config");
}
-
+
public VirtualMachineConfigSummary getConfigSummary() throws Exception {
- return (VirtualMachineConfigSummary)_context.getServiceUtil().getDynamicProperty(
+ return (VirtualMachineConfigSummary)_context.getVimClient().getDynamicProperty(
_mor, "summary.config");
}
-
+
public VirtualMachineFileInfo getFileInfo() throws Exception {
- return (VirtualMachineFileInfo)_context.getServiceUtil().getDynamicProperty(
+ return (VirtualMachineFileInfo)_context.getVimClient().getDynamicProperty(
_mor, "config.files");
}
-
+
public ManagedObjectReference getParentMor() throws Exception {
- return (ManagedObjectReference)_context.getServiceUtil().getDynamicProperty(
+ return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(
_mor, "parent");
}
public String[] getNetworks() throws Exception {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Network");
- pSpec.setPathSet(new String[] {"name"});
-
+ pSpec.getPathSet().add("name");
+
TraversalSpec vm2NetworkTraversal = new TraversalSpec();
vm2NetworkTraversal.setType("VirtualMachine");
vm2NetworkTraversal.setPath("network");
@@ -652,20 +659,21 @@ public class VirtualMachineMO extends BaseMO {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal });
+ oSpec.getSelectSet().add(vm2NetworkTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
List networks = new ArrayList();
- if(ocs != null && ocs.length > 0) {
+ if(ocs != null && ocs.size() > 0) {
for(ObjectContent oc : ocs) {
- networks.add(oc.getPropSet(0).getVal().toString());
+ networks.add(oc.getPropSet().get(0).getVal().toString());
}
}
return networks.toArray(new String[0]);
@@ -675,16 +683,18 @@ public class VirtualMachineMO extends BaseMO {
List networks = new ArrayList();
int gcTagKey = getCustomFieldKey("Network", CustomFieldConstants.CLOUD_GC);
-
+
if(gcTagKey == 0) {
gcTagKey = getCustomFieldKey("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP);
s_logger.debug("The custom key for dvPortGroup is : " + gcTagKey);
}
-
+
PropertySpec pSpec = new PropertySpec();
pSpec.setType("Network");
- pSpec.setPathSet(new String[] {"name", "vm", String.format("value[%d]", gcTagKey)});
-
+ pSpec.getPathSet().add("name");
+ pSpec.getPathSet().add("vm");
+ pSpec.getPathSet().add(String.format("value[%d]", gcTagKey));
+
TraversalSpec vm2NetworkTraversal = new TraversalSpec();
vm2NetworkTraversal.setType("VirtualMachine");
vm2NetworkTraversal.setPath("network");
@@ -693,17 +703,19 @@ public class VirtualMachineMO extends BaseMO {
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
- oSpec.setSelectSet(new SelectionSpec[] { vm2NetworkTraversal });
+ oSpec.getSelectSet().add(vm2NetworkTraversal);
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
- pfSpec.setPropSet(new PropertySpec[] { pSpec });
- pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
-
- ObjectContent[] ocs = _context.getService().retrieveProperties(
- _context.getServiceContent().getPropertyCollector(),
- new PropertyFilterSpec[] { pfSpec });
-
- if(ocs != null && ocs.length > 0) {
+ pfSpec.getPropSet().add(pSpec);
+ pfSpec.getObjectSet().add(oSpec);
+ List pfSpecArr = new ArrayList();
+ pfSpecArr.add(pfSpec);
+
+ List ocs = _context.getService().retrieveProperties(
+ _context.getPropertyCollector(), pfSpecArr);
+
+
+ if(ocs != null && ocs.size() > 0) {
for(ObjectContent oc : ocs) {
ArrayOfManagedObjectReference morVms = null;
String gcTagValue = null;
@@ -720,29 +732,29 @@ public class VirtualMachineMO extends BaseMO {
gcTagValue = val.getValue();
}
}
-
- NetworkDetails details = new NetworkDetails(name, oc.getObj(),
- (morVms != null ? morVms.getManagedObjectReference() : null),
+
+ NetworkDetails details = new NetworkDetails(name, oc.getObj(),
+ (morVms != null ? morVms.getManagedObjectReference().toArray(new ManagedObjectReference[morVms.getManagedObjectReference().size()]) : null),
gcTagValue);
-
+
networks.add(details);
}
s_logger.debug("Retrieved " + networks.size() + " networks with key : " + gcTagKey);
}
-
+
return networks;
}
-
+
/**
- * Retrieve path info to access VM files via vSphere web interface
- * @return [0] vm-name, [1] data-center-name, [2] datastore-name
+ * Retrieve path info to access VM files via vSphere web interface
+ * @return [0] vm-name, [1] data-center-name, [2] datastore-name
* @throws Exception
*/
public String[] getHttpAccessPathInfo() throws Exception {
String[] pathInfo = new String[3];
-
+
Pair dcInfo = getOwnerDatacenter();
-
+
VirtualMachineFileInfo fileInfo = getFileInfo();
String vmxFilePath = fileInfo.getVmPathName();
String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/");
@@ -752,14 +764,14 @@ public class VirtualMachineMO extends BaseMO {
pathInfo[3] = vmxPathTokens[0].trim(); // vSphere datastore name
return pathInfo;
}
-
+
public String getVmxHttpAccessUrl() throws Exception {
Pair dcInfo = getOwnerDatacenter();
-
+
VirtualMachineFileInfo fileInfo = getFileInfo();
String vmxFilePath = fileInfo.getVmPathName();
String vmxPathTokens[] = vmxFilePath.split("\\[|\\]|/");
-
+
StringBuffer sb = new StringBuffer("https://" + _context.getServerAddress() + "/folder/");
sb.append(URLEncoder.encode(vmxPathTokens[2].trim()));
sb.append("/");
@@ -768,18 +780,18 @@ public class VirtualMachineMO extends BaseMO {
sb.append(URLEncoder.encode(dcInfo.second()));
sb.append("&dsName=");
sb.append(URLEncoder.encode(vmxPathTokens[1].trim()));
-
+
return sb.toString();
}
-
+
public boolean setVncConfigInfo(boolean enableVnc, String vncPassword, int vncPort, String keyboard) throws Exception {
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
OptionValue[] vncOptions = VmwareHelper.composeVncOptions(null, enableVnc, vncPassword, vncPort, keyboard);
- vmConfigSpec.setExtraConfig(vncOptions);
- ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, vmConfigSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ vmConfigSpec.getExtraConfig().addAll(Arrays.asList(vncOptions));
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, vmConfigSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -787,12 +799,12 @@ public class VirtualMachineMO extends BaseMO {
}
return false;
}
-
+
public boolean configureVm(VirtualMachineConfigSpec vmConfigSpec) throws Exception {
- ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, vmConfigSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, vmConfigSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -800,12 +812,12 @@ public class VirtualMachineMO extends BaseMO {
}
return false;
}
-
- public boolean configureVm(Ternary[] devices) throws Exception {
-
+
assert(devices != null);
-
+
VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[devices.length];
int i = 0;
@@ -816,12 +828,12 @@ public class VirtualMachineMO extends BaseMO {
deviceConfigSpec.setFileOperation(deviceTernary.third());
deviceConfigSpecArray[i++] = deviceConfigSpec;
}
- configSpec.setDeviceChange(deviceConfigSpecArray);
+ configSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray));
- ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, configSpec);
-
- String result = _context.getServiceUtil().waitForTask(morTask);
- if(result.equals("sucess")) {
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, configSpec);
+
+ boolean result = _context.getVimClient().waitForTask(morTask);
+ if(result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
@@ -829,14 +841,14 @@ public class VirtualMachineMO extends BaseMO {
}
return false;
}
-
+
public Pair getVncPort(String hostNetworkName) throws Exception {
HostMO hostMo = getRunningHost();
VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(hostNetworkName);
VirtualMachineConfigInfo configInfo = getConfigInfo();
- OptionValue[] values = configInfo.getExtraConfig();
-
+ List values = configInfo.getExtraConfig();
+
if(values != null) {
for(OptionValue option : values) {
if(option.getKey().equals("RemoteDisplay.vnc.port")) {
@@ -849,173 +861,173 @@ public class VirtualMachineMO extends BaseMO {
}
return new Pair(summary.getHostIp(), 0);
}
-
+
// vmdkDatastorePath: [datastore name] vmdkFilePath
public void createDisk(String vmdkDatastorePath, int sizeInMb, ManagedObjectReference morDs, int controllerKey) throws Exception {
- createDisk(vmdkDatastorePath, VirtualDiskType.thin, VirtualDiskMode.persistent, null, sizeInMb, morDs, controllerKey);
+ 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);
-
+ s_logger.trace("vCenter API trace - createDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath
+ + ", sizeInMb: " + sizeInMb + ", diskType: " + diskType + ", diskMode: " + diskMode + ", rdmDeviceName: " + rdmDeviceName
+ + ", datastore: " + morDs.getValue() + ", 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) {
-
+ if(diskType == VirtualDiskType.THIN || diskType == VirtualDiskType.PREALLOCATED
+ || diskType == VirtualDiskType.EAGER_ZEROED_THICK) {
+
VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo();
- backingInfo.setDiskMode(diskMode.persistent.toString());
- if(diskType == VirtualDiskType.thin) {
+ backingInfo.setDiskMode(diskMode.PERSISTENT.value());
+ if(diskType == VirtualDiskType.THIN) {
backingInfo.setThinProvisioned(true);
} else {
backingInfo.setThinProvisioned(false);
}
-
- if(diskType == VirtualDiskType.eagerZeroedThick) {
+
+ if(diskType == VirtualDiskType.EAGER_ZEROED_THICK) {
backingInfo.setEagerlyScrub(true);
} else {
backingInfo.setEagerlyScrub(false);
}
-
+
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) {
+ } 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());
+ if(diskType == VirtualDiskType.RDM) {
+ backingInfo.setDiskMode(diskMode.PERSISTENT.value());
}
-
+
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];
+ 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")) {
+ deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.CREATE);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+
+ //deviceConfigSpecArray[0] = deviceConfigSpec;
+ reConfigSpec.getDeviceChange().add(deviceConfigSpec);
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - createDisk() done(failed)");
throw new Exception("Unable to create disk " + vmdkDatastorePath + " due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
_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(),
+ s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: "
+ + new Gson().toJson(vmdkDatastorePathChain) + ", datastore: " + morDs.getValue());
+
+ VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, getScsiDeviceControllerKey(),
vmdkDatastorePathChain, morDs, -1, 1);
- VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ 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")) {
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+
+ //deviceConfigSpecArray[0] = deviceConfigSpec;
+ reConfigSpec.getDeviceChange().add(deviceConfigSpec);
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - attachDisk() done(failed)");
+ s_logger.trace("vCenter API trace - attachDisk() done(failed)");
throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
_context.waitForTaskProgressDone(morTask);
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
+ s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
}
-
+
public void attachDisk(Pair[] vmdkDatastorePathChain, int controllerKey) throws Exception {
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: "
+ s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: "
+ new Gson().toJson(vmdkDatastorePathChain));
-
- VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, controllerKey,
+
+ VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, controllerKey,
vmdkDatastorePathChain, -1, 1);
- VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[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")) {
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+
+ //deviceConfigSpecArray[0] = deviceConfigSpec;
+ reConfigSpec.getDeviceChange().add(deviceConfigSpec);
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - attachDisk() done(failed)");
+ s_logger.trace("vCenter API trace - attachDisk() done(failed)");
throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
_context.waitForTaskProgressDone(morTask);
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
+ s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
}
-
+
// vmdkDatastorePath: [datastore name] vmdkFilePath
public List> detachDisk(String vmdkDatastorePath, boolean deleteBackingFile) throws Exception {
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: "
+ s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: "
+ vmdkDatastorePath + ", deleteBacking: " + deleteBackingFile);
-
+
// Note: if VM has been taken snapshot, original backing file will be renamed, therefore, when we try to find the matching
// VirtualDisk, we only perform prefix matching
Pair deviceInfo = getDiskDevice(vmdkDatastorePath, false);
@@ -1024,29 +1036,29 @@ public class VirtualMachineMO extends BaseMO {
s_logger.trace("vCenter API trace - detachDisk() done (failed)");
throw new Exception("No such disk device: " + vmdkDatastorePath);
}
-
+
List> chain = getDiskDatastorePathChain(deviceInfo.first(), true);
-
- VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+
+ VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
-
+
deviceConfigSpec.setDevice(deviceInfo.first());
if(deleteBackingFile) {
- deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.destroy);
+ deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.DESTROY);
}
- deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.remove);
-
- deviceConfigSpecArray[0] = deviceConfigSpec;
- reConfigSpec.setDeviceChange(deviceConfigSpecArray);
-
- ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec);
- String result = _context.getServiceUtil().waitForTask(morTask);
-
- if(!result.equals("sucess")) {
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
+
+ //deviceConfigSpecArray[0] = deviceConfigSpec;
+ reConfigSpec.getDeviceChange().add(deviceConfigSpec);
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
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);
@@ -1058,65 +1070,65 @@ public class VirtualMachineMO extends BaseMO {
} catch(Exception e) {
s_logger.info("Unable to retrieve snapshot descriptor, will skip updating snapshot reference");
}
-
+
if(snapshotDescriptor != null) {
for(Pair pair: chain) {
DatastoreFile dsFile = new DatastoreFile(pair.first());
snapshotDescriptor.removeDiskReferenceFromSnapshot(dsFile.getFileName());
}
-
+
Pair dcPair = getOwnerDatacenter();
String dsPath = getSnapshotDescriptorDatastorePath();
assert(dsPath != null);
String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), dsPath);
getContext().uploadResourceContent(url, snapshotDescriptor.getVmsdContent());
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachDisk() done (successfully)");
return chain;
}
-
+
public void detachAllDisks() throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - detachAllDisk(). target MOR: " + _mor.get_value());
-
+ s_logger.trace("vCenter API trace - detachAllDisk(). target MOR: " + _mor.getValue());
+
VirtualDisk[] disks = getAllDiskDevice();
if(disks.length > 0) {
- VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
+ VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[disks.length];
-
+
for(int i = 0; i < disks.length; i++) {
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
deviceConfigSpecArray[i].setDevice(disks[i]);
- deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.remove);
+ 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")) {
+ reConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray));
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachAllDisk() done(failed)");
throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
_context.waitForTaskProgressDone(morTask);
}
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachAllDisk() done(successfully)");
}
-
+
// isoDatastorePath: [datastore name] isoFilePath
public void attachIso(String isoDatastorePath, ManagedObjectReference morDs,
boolean connect, boolean connectAtBoot) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: "
- + isoDatastorePath + ", datastore: " + morDs.get_value() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot);
-
+ s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.getValue() + ", isoDatastorePath: "
+ + isoDatastorePath + ", datastore: " + morDs.getValue() + ", connect: " + connect + ", connectAtBoot: " + connectAtBoot);
+
assert(isoDatastorePath != null);
assert(morDs != null);
@@ -1126,54 +1138,54 @@ public class VirtualMachineMO extends BaseMO {
newCdRom = true;
cdRom = new VirtualCdrom();
cdRom.setControllerKey(getIDEDeviceControllerKey());
-
+
int deviceNumber = getNextIDEDeviceNumber();
- cdRom.setUnitNumber(deviceNumber);
+ cdRom.setUnitNumber(deviceNumber);
cdRom.setKey(-deviceNumber);
}
-
+
VirtualDeviceConnectInfo cInfo = new VirtualDeviceConnectInfo();
cInfo.setConnected(connect);
cInfo.setStartConnected(connectAtBoot);
cdRom.setConnectable(cInfo);
-
+
VirtualCdromIsoBackingInfo backingInfo = new VirtualCdromIsoBackingInfo();
backingInfo.setFileName(isoDatastorePath);
backingInfo.setDatastore(morDs);
cdRom.setBacking(backingInfo);
- VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
-
+
deviceConfigSpec.setDevice(cdRom);
if(newCdRom) {
- deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
} else {
- deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.edit);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
}
-
- deviceConfigSpecArray[0] = deviceConfigSpec;
- reConfigSpec.setDeviceChange(deviceConfigSpecArray);
-
- ManagedObjectReference morTask = _context.getService().reconfigVM_Task(_mor, reConfigSpec);
- String result = _context.getServiceUtil().waitForTask(morTask);
-
- if(!result.equals("sucess")) {
+
+ //deviceConfigSpecArray[0] = deviceConfigSpec;
+ reConfigSpec.getDeviceChange().add(deviceConfigSpec);
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachIso() done(failed)");
throw new Exception("Failed to attach ISO due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
-
+
_context.waitForTaskProgressDone(morTask);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachIso() done(successfully)");
}
-
+
public void detachIso(String isoDatastorePath) throws Exception {
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.get_value() + ", isoDatastorePath: "
+ s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.getValue() + ", isoDatastorePath: "
+ isoDatastorePath);
VirtualDevice device = getIsoDevice();
@@ -1182,48 +1194,48 @@ public class VirtualMachineMO extends BaseMO {
s_logger.trace("vCenter API trace - detachIso() done(failed)");
throw new Exception("Unable to find a CDROM device");
}
-
+
VirtualCdromRemotePassthroughBackingInfo backingInfo = new VirtualCdromRemotePassthroughBackingInfo();
backingInfo.setDeviceName("");
device.setBacking(backingInfo);
-
- VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+
+ 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")) {
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
+
+ //deviceConfigSpecArray[0] = deviceConfigSpec;
+ reConfigSpec.getDeviceChange().add(deviceConfigSpec);
+
+ ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
+ boolean result = _context.getVimClient().waitForTask(morTask);
+
+ if(!result) {
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachIso() done(failed)");
throw new Exception("Failed to detachIso due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
_context.waitForTaskProgressDone(morTask);
-
+
if(s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachIso() done(successfully)");
}
-
+
public Pair getVmdkFileInfo(String vmdkDatastorePath) throws Exception {
-
+
if(s_logger.isTraceEnabled())
- s_logger.trace("vCenter API trace - getVmdkFileInfo(). target MOR: " + _mor.get_value() + ", vmdkDatastorePath: "
+ s_logger.trace("vCenter API trace - getVmdkFileInfo(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: "
+ vmdkDatastorePath);
-
+
Pair dcPair = getOwnerDatacenter();
-
+
String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), vmdkDatastorePath);
byte[] content = getContext().getResourceContent(url);
VmdkFileDescriptor descriptor = new VmdkFileDescriptor();
descriptor.parse(content);
-
+
Pair result = new Pair(descriptor, content);
if(s_logger.isTraceEnabled()) {
s_logger.trace("vCenter API trace - getVmdkFileInfo() done");
@@ -1231,34 +1243,34 @@ public class VirtualMachineMO extends BaseMO {
}
return result;
}
-
+
public void exportVm(String exportDir, String exportName, boolean packToOva, boolean leaveOvaFileOnly) throws Exception {
ManagedObjectReference morOvf = _context.getServiceContent().getOvfManager();
-
+
VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo();
HostMO hostMo = new HostMO(_context, runtimeInfo.getHost());
String hostName = hostMo.getHostName();
String vmName = getVmName();
-
+
DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter());
-
- if(runtimeInfo.getPowerState() != VirtualMachinePowerState.poweredOff) {
+
+ if(runtimeInfo.getPowerState() != VirtualMachinePowerState.POWERED_OFF) {
String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName;
s_logger.error(msg);
throw new Exception(msg);
}
-
+
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 });
-
+ HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
+
try {
- if(state == HttpNfcLeaseState.ready) {
+ if(state == HttpNfcLeaseState.READY) {
final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
boolean success = false;
@@ -1267,24 +1279,24 @@ public class VirtualMachineMO extends BaseMO {
HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo();
final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024;
long totalBytesDownloaded = 0;
-
- HttpNfcLeaseDeviceUrl[] deviceUrls = leaseInfo.getDeviceUrl();
+
+ List deviceUrls = leaseInfo.getDeviceUrl();
if(deviceUrls != null) {
- OvfFile[] ovfFiles = new OvfFile[deviceUrls.length];
- for (int i = 0; i < deviceUrls.length; i++) {
- String deviceId = deviceUrls[i].getKey();
- String deviceUrlStr = deviceUrls[i].getUrl();
+ OvfFile[] ovfFiles = new OvfFile[deviceUrls.size()];
+ for (int i = 0; i < deviceUrls.size(); i++) {
+ String deviceId = deviceUrls.get(i).getKey();
+ String deviceUrlStr = deviceUrls.get(i).getUrl();
String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1);
String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk"));
String diskUrlStr = deviceUrlStr.replace("*", hostName);
diskUrlStr = HypervisorHostHelper.resolveHostNameInUrl(dcMo, diskUrlStr);
String diskLocalPath = exportDir + File.separator + diskFileName;
fileNames.add(diskLocalPath);
-
+
if(s_logger.isInfoEnabled()) {
s_logger.info("Download VMDK file for export. url: " + deviceUrlStr);
}
- long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded,
+ long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded,
new ActionDelegate () {
@Override
public void action(Long param) {
@@ -1295,33 +1307,33 @@ public class VirtualMachineMO extends BaseMO {
}
});
totalBytesDownloaded += lengthOfDiskFile;
-
+
OvfFile ovfFile = new OvfFile();
- ovfFile.setPath(diskFileName);
- ovfFile.setDeviceId(deviceId);
- ovfFile.setSize(lengthOfDiskFile);
- ovfFiles[i] = ovfFile;
+ ovfFile.setPath(diskFileName);
+ ovfFile.setDeviceId(deviceId);
+ ovfFile.setSize(lengthOfDiskFile);
+ ovfFiles[i] = ovfFile;
}
-
+
// write OVF descriptor file
- OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
- ovfDescParams.setOvfFiles(ovfFiles);
- OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams);
+ OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
+ ovfDescParams.getOvfFiles().addAll(Arrays.asList(ovfFiles));
+ OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams);
String ovfPath = exportDir + File.separator + exportName + ".ovf";
fileNames.add(ovfPath);
-
+
FileWriter out = new FileWriter(ovfPath);
- out.write(ovfCreateDescriptorResult.getOvfDescriptor());
+ out.write(ovfCreateDescriptorResult.getOvfDescriptor());
out.close();
-
+
// tar files into OVA
if(packToOva) {
// Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature)
s_logger.info("Sync file system before we package OVA...");
-
+
Script commandSync = new Script(true, "sync", 0, s_logger);
commandSync.execute();
-
+
Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(exportDir);
command.add("-cf", exportName + ".ova");
@@ -1329,10 +1341,10 @@ public class VirtualMachineMO extends BaseMO {
for(String name: fileNames) {
command.add((new File(name).getName()));
}
-
+
s_logger.info("Package OVA with commmand: " + command.toString());
command.execute();
-
+
// to be safe, physically test existence of the target OVA file
if((new File(exportDir + File.separator + exportName + ".ova")).exists()) {
success = true;
@@ -1351,7 +1363,7 @@ public class VirtualMachineMO extends BaseMO {
new File(name).delete();
}
}
-
+
if(!success)
throw new Exception("Unable to finish the whole process to package as a OVA file");
}
@@ -1361,7 +1373,7 @@ public class VirtualMachineMO extends BaseMO {
leaseMo.completeLease();
}
}
-
+
// snapshot directory in format of: /vmfs/volumes//
@Deprecated
public void setSnapshotDirectory(String snapshotDir) throws Exception {
@@ -1369,15 +1381,15 @@ public class VirtualMachineMO extends BaseMO {
Pair dcInfo = getOwnerDatacenter();
String vmxUrl = _context.composeDatastoreBrowseUrl(dcInfo.second(), fileInfo.getVmPathName());
byte[] vmxContent = _context.getResourceContent(vmxUrl);
-
+
BufferedReader in = null;
BufferedWriter out = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
+
boolean replaced = false;
try {
in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmxContent)));
- out = new BufferedWriter(new OutputStreamWriter(bos));
+ out = new BufferedWriter(new OutputStreamWriter(bos));
String line;
while((line = in.readLine()) != null) {
if(line.startsWith("workingDir")) {
@@ -1389,7 +1401,7 @@ public class VirtualMachineMO extends BaseMO {
out.newLine();
}
}
-
+
if(!replaced) {
out.newLine();
out.write(String.format("workingDir=\"%s\"", snapshotDir));
@@ -1409,30 +1421,30 @@ public class VirtualMachineMO extends BaseMO {
// its disk backing info anyway.
// redoRegistration();
}
-
+
// destName does not contain extension name
- public void backupCurrentSnapshot(String deviceName, ManagedObjectReference morDestDs,
+ public void backupCurrentSnapshot(String deviceName, ManagedObjectReference morDestDs,
String destDsDirectory, String destName, boolean includeBase) throws Exception {
-
+
SnapshotDescriptor descriptor = getSnapshotDescriptor();
SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain();
if(snapshotInfo.length == 0) {
String msg = "No snapshot found in this VM";
throw new Exception(msg);
}
-
+
HostMO hostMo = getRunningHost();
DatacenterMO dcMo = getOwnerDatacenter().first();
List> mounts = hostMo.getDatastoreMountsOnHost();
VirtualMachineFileInfo vmFileInfo = getFileInfo();
-
- List> backupInfo = new ArrayList>();
-
+
+ List> backupInfo = new ArrayList>();
+
for(int i = 0; i < snapshotInfo.length; i++) {
if(!includeBase && i == snapshotInfo.length - 1) {
break;
}
-
+
SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks();
if(disks != null) {
String destBaseFileName;
@@ -1440,10 +1452,10 @@ public class VirtualMachineMO extends BaseMO {
String destParentFileName;
for(SnapshotDescriptor.DiskInfo disk : disks) {
if(deviceName == null || deviceName.equals(disk.getDeviceName())) {
- String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo,
+ String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo,
mounts, disk.getDiskFileName());
Pair srcDsInfo = getOwnerDatastore(srcVmdkFullDsPath);
-
+
Pair vmdkInfo = getVmdkFileInfo(srcVmdkFullDsPath);
String srcVmdkBaseFilePath = DatastoreFile.getCompanionDatastorePath(
srcVmdkFullDsPath, vmdkInfo.first().getBaseFileName());
@@ -1456,19 +1468,19 @@ public class VirtualMachineMO extends BaseMO {
destBaseFileName = destName + (snapshotInfo.length - i - 1) + "-flat.vmdk";
destParentFileName = null;
}
-
+
s_logger.info("Copy VMDK base file " + srcVmdkBaseFilePath + " to " + destDsDirectory + "/" + destBaseFileName);
- srcDsInfo.first().copyDatastoreFile(srcVmdkBaseFilePath, dcMo.getMor(),
+ srcDsInfo.first().copyDatastoreFile(srcVmdkBaseFilePath, dcMo.getMor(),
morDestDs, destDsDirectory + "/" + destBaseFileName, dcMo.getMor(), true);
-
+
byte[] newVmdkContent = VmdkFileDescriptor.changeVmdkContentBaseInfo(
vmdkInfo.second(), destBaseFileName, destParentFileName);
- String vmdkUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(),
+ String vmdkUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(),
destDsDirectory + "/" + destFileName);
-
+
s_logger.info("Upload VMDK content file to " + destDsDirectory + "/" + destFileName);
getContext().uploadResourceContent(vmdkUploadUrl, newVmdkContent);
-
+
backupInfo.add(new Ternary(
destFileName, destBaseFileName, destParentFileName)
);
@@ -1476,21 +1488,21 @@ public class VirtualMachineMO extends BaseMO {
}
}
}
-
+
byte[] vdiskInfo = VmwareHelper.composeDiskInfo(backupInfo, snapshotInfo.length, includeBase);
- String vdiskUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(),
+ String vdiskUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(),
destDsDirectory + "/" + destName + ".vdisk");
getContext().uploadResourceContent(vdiskUploadUrl, vdiskInfo);
}
-
+
public String[] getCurrentSnapshotDiskChainDatastorePaths(String diskDevice) throws Exception {
HostMO hostMo = getRunningHost();
List> mounts = hostMo.getDatastoreMountsOnHost();
VirtualMachineFileInfo vmFileInfo = getFileInfo();
-
+
SnapshotDescriptor descriptor = getSnapshotDescriptor();
SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain();
-
+
List diskDsFullPaths = new ArrayList();
for(int i = 0; i < snapshotInfo.length; i++) {
SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks();
@@ -1498,7 +1510,7 @@ public class VirtualMachineMO extends BaseMO {
for(SnapshotDescriptor.DiskInfo disk: disks) {
String deviceNameInDisk = disk.getDeviceName();
if(diskDevice == null || diskDevice.equalsIgnoreCase(deviceNameInDisk)) {
- String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo,
+ String vmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo,
mounts, disk.getDiskFileName());
diskDsFullPaths.add(vmdkFullDsPath);
}
@@ -1507,40 +1519,40 @@ public class VirtualMachineMO extends BaseMO {
}
return diskDsFullPaths.toArray(new String[0]);
}
-
- public void cloneFromCurrentSnapshot(String clonedVmName, int cpuSpeedMHz, int memoryMb, String diskDevice,
+
+ public void cloneFromCurrentSnapshot(String clonedVmName, int cpuSpeedMHz, int memoryMb, String diskDevice,
ManagedObjectReference morDs) throws Exception {
assert(morDs != null);
String[] disks = getCurrentSnapshotDiskChainDatastorePaths(diskDevice);
cloneFromDiskChain(clonedVmName, cpuSpeedMHz, memoryMb, disks, morDs);
}
-
- public void cloneFromDiskChain(String clonedVmName, int cpuSpeedMHz, int memoryMb,
+
+ public void cloneFromDiskChain(String clonedVmName, int cpuSpeedMHz, int memoryMb,
String[] disks, ManagedObjectReference morDs) throws Exception {
assert(disks != null);
assert(disks.length >= 1);
-
+
HostMO hostMo = getRunningHost();
VirtualMachineConfigInfo vmConfigInfo = getConfigInfo();
-
+
if(!hostMo.createBlankVm(clonedVmName, 1, cpuSpeedMHz, 0, false, memoryMb, 0, vmConfigInfo.getGuestId(), morDs, false))
throw new Exception("Unable to create a blank VM");
-
+
VirtualMachineMO clonedVmMo = hostMo.findVmOnHyperHost(clonedVmName);
if(clonedVmMo == null)
throw new Exception("Unable to find just-created blank VM");
-
+
boolean bSuccess = false;
try {
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
- deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec();
-
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
+
VirtualDevice device = VmwareHelper.prepareDiskDevice(clonedVmMo, -1, disks, morDs, -1, 1);
-
- deviceConfigSpecArray[0].setDevice(device);
- deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add);
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+
+ deviceConfigSpec.setDevice(device);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
clonedVmMo.configureVm(vmConfigSpec);
bSuccess = true;
} finally {
@@ -1550,52 +1562,52 @@ public class VirtualMachineMO extends BaseMO {
}
}
}
-
+
public void plugDevice(VirtualDevice device) throws Exception {
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
- VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
- deviceConfigSpecArray[0] = new VirtualDeviceConfigSpec();
- deviceConfigSpecArray[0].setDevice(device);
- deviceConfigSpecArray[0].setOperation(VirtualDeviceConfigSpecOperation.add);
-
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
+ deviceConfigSpec.setDevice(device);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
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);
+ //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
+ VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
+ deviceConfigSpec.setDevice(device);
+ deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
+
+ vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
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);
+ deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
}
-
- vmConfigSpec.setDeviceChange(deviceConfigSpecArray);
+
+ vmConfigSpec.getDeviceChange().addAll(Arrays.asList(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();
@@ -1604,25 +1616,25 @@ public class VirtualMachineMO extends BaseMO {
List> vmdkFiles = this.getDiskDatastorePathChain((VirtualDisk)disk, followDiskChain);
for(Pair fileItem : vmdkFiles) {
DatastoreMO srcDsMo = new DatastoreMO(_context, fileItem.second());
-
+
DatastoreFile srcFile = new DatastoreFile(fileItem.first());
DatastoreFile destFile = new DatastoreFile(destDsMo.getName(), destDsDir, srcFile.getFileName());
-
+
Pair vmdkDescriptor = null;
-
+
vmdkDescriptor = getVmdkFileInfo(fileItem.first());
-
+
s_logger.info("Copy VM disk file " + srcFile.getPath() + " to " + destFile.getPath());
- srcDsMo.copyDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(),
+ srcDsMo.copyDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(),
destFile.getPath(), dcMo.getMor(), true);
-
+
if(vmdkDescriptor != null) {
String vmdkBaseFileName = vmdkDescriptor.first().getBaseFileName();
String baseFilePath = srcFile.getCompanionPath(vmdkBaseFileName);
destFile = new DatastoreFile(destDsMo.getName(), destDsDir, vmdkBaseFileName);
-
+
s_logger.info("Copy VM disk file " + baseFilePath + " to " + destFile.getPath());
- srcDsMo.copyDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(),
+ srcDsMo.copyDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(),
destFile.getPath(), dcMo.getMor(), true);
}
}
@@ -1640,67 +1652,67 @@ public class VirtualMachineMO extends BaseMO {
List> vmdkFiles = this.getDiskDatastorePathChain((VirtualDisk)disk, followDiskChain);
for(Pair fileItem : vmdkFiles) {
DatastoreMO srcDsMo = new DatastoreMO(_context, fileItem.second());
-
+
DatastoreFile srcFile = new DatastoreFile(fileItem.first());
DatastoreFile destFile = new DatastoreFile(destDsMo.getName(), destDsDir, srcFile.getFileName());
-
+
Pair vmdkDescriptor = null;
vmdkDescriptor = getVmdkFileInfo(fileItem.first());
-
+
s_logger.info("Move VM disk file " + srcFile.getPath() + " to " + destFile.getPath());
- srcDsMo.moveDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(),
+ srcDsMo.moveDatastoreFile(fileItem.first(), dcMo.getMor(), destDsMo.getMor(),
destFile.getPath(), dcMo.getMor(), true);
-
+
if(vmdkDescriptor != null) {
String vmdkBaseFileName = vmdkDescriptor.first().getBaseFileName();
String baseFilePath = srcFile.getCompanionPath(vmdkBaseFileName);
destFile = new DatastoreFile(destDsMo.getName(), destDsDir, vmdkBaseFileName);
-
+
s_logger.info("Move VM disk file " + baseFilePath + " to " + destFile.getPath());
- srcDsMo.moveDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(),
+ srcDsMo.moveDatastoreFile(baseFilePath, dcMo.getMor(), destDsMo.getMor(),
destFile.getPath(), dcMo.getMor(), true);
}
}
}
}
}
-
+
public int getNextScsiDiskDeviceNumber() throws Exception {
int scsiControllerKey = getScsiDeviceControllerKey();
return getNextDeviceNumber(scsiControllerKey);
}
-
+
public int getScsiDeviceControllerKey() throws Exception {
- VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil().
+ List devices = (List)_context.getVimClient().
getDynamicProperty(_mor, "config.hardware.device");
-
- if(devices != null && devices.length > 0) {
+
+ if(devices != null && devices.size() > 0) {
for(VirtualDevice device : devices) {
if(device instanceof VirtualLsiLogicController) {
return device.getKey();
}
}
}
-
+
assert(false);
throw new Exception("SCSI Controller Not Found");
}
public int getScsiDeviceControllerKeyNoException() throws Exception {
- VirtualDevice[] devices = (VirtualDevice [])_context.getServiceUtil().
+ List devices = (List)_context.getVimClient().
getDynamicProperty(_mor, "config.hardware.device");
-
- if(devices != null && devices.length > 0) {
+
+ if(devices != null && devices.size() > 0) {
for(VirtualDevice device : devices) {
if(device instanceof VirtualLsiLogicController) {
return device.getKey();
}
}
}
-
+
return -1;
}
-
+
public void ensureScsiDeviceController() throws Exception {
int scsiControllerKey = getScsiDeviceControllerKeyNoException();
if(scsiControllerKey < 0) {
@@ -1708,67 +1720,67 @@ public class VirtualMachineMO extends BaseMO {
// Scsi controller
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
- scsiController.setSharedBus(VirtualSCSISharing.noSharing);
+ scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
scsiController.setBusNumber(0);
scsiController.setKey(1);
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
scsiControllerSpec.setDevice(scsiController);
- scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
+ scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
- vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec });
+ vmConfig.getDeviceChange().add(scsiControllerSpec);
if(configureVm(vmConfig)) {
throw new Exception("Unable to add Scsi controller");
}
}
}
-
+
// 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");
-
+ List devices = (List)_context.getVimClient().getDynamicProperty(_mor, "config.hardware.device");
+
s_logger.info("Look for disk device info from volume : " + vmdkDatastorePath);
DatastoreFile dsSrcFile = new DatastoreFile(vmdkDatastorePath);
String srcBaseName = dsSrcFile.getFileBaseName();
-
- if(devices != null && devices.length > 0) {
+
+ if(devices != null && devices.size() > 0) {
for(VirtualDevice device : devices) {
if(device instanceof VirtualDisk) {
s_logger.info("Test against disk device, controller key: " + device.getControllerKey() + ", unit number: " + device.getUnitNumber());
-
+
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