mirror of https://github.com/apache/cloudstack.git
Upgrade to use Vsphere 5.1 SDK jar, fixed all compilation error with new
wrapper class VmwareClient.
This commit is contained in:
parent
8f33229fc1
commit
481f480472
|
|
@ -11,7 +11,7 @@
|
|||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
package com.cloud.hypervisor.vmware;
|
||||
|
|
@ -72,7 +72,7 @@ import com.vmware.vim25.ManagedObjectReference;
|
|||
@Local(value=Discoverer.class)
|
||||
public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter {
|
||||
private static final Logger s_logger = Logger.getLogger(VmwareServerDiscoverer.class);
|
||||
|
||||
|
||||
@Inject ClusterDao _clusterDao;
|
||||
@Inject VmwareManager _vmwareMgr;
|
||||
@Inject AlertManager _alertMgr;
|
||||
|
|
@ -85,27 +85,27 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
@Inject CiscoNexusVSMDeviceDao _nexusDao;
|
||||
@Inject
|
||||
NetworkModel _netmgr;
|
||||
|
||||
|
||||
@Override
|
||||
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url,
|
||||
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url,
|
||||
String username, String password, List<String> hostTags) throws DiscoveryException {
|
||||
|
||||
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost());
|
||||
|
||||
|
||||
if(podId == null) {
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
|
||||
s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
ClusterVO cluster = _clusterDao.findById(clusterId);
|
||||
if(cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) {
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
|
||||
s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
|
||||
if(hosts.size() >= _vmwareMgr.getMaxHostsPerCluster()) {
|
||||
String msg = "VMware cluster " + cluster.getName() + " is too big to add new host now. (current configured cluster size: " + _vmwareMgr.getMaxHostsPerCluster() + ")";
|
||||
|
|
@ -117,12 +117,12 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
String publicTrafficLabel = null;
|
||||
String guestTrafficLabel = null;
|
||||
Map<String, String> vsmCredentials = null;
|
||||
|
||||
|
||||
privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware);
|
||||
if (privateTrafficLabel != null) {
|
||||
s_logger.info("Detected private network label : " + privateTrafficLabel);
|
||||
}
|
||||
|
||||
|
||||
if (_vmwareMgr.getNexusVSwitchGlobalParameter()) {
|
||||
DataCenterVO zone = _dcDao.findById(dcId);
|
||||
NetworkType zoneType = zone.getNetworkType();
|
||||
|
|
@ -145,7 +145,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
context = VmwareContextFactory.create(url.getHost(), username, password);
|
||||
if (privateTrafficLabel != null)
|
||||
context.registerStockObject("privateTrafficLabel", privateTrafficLabel);
|
||||
|
||||
|
||||
if (_vmwareMgr.getNexusVSwitchGlobalParameter()) {
|
||||
if (vsmCredentials != null) {
|
||||
s_logger.info("Stocking credentials of Nexus VSM");
|
||||
|
|
@ -163,26 +163,26 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath()));
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
ManagedObjectReference morCluster = null;
|
||||
Map<String, String> clusterDetails = _clusterDetailsDao.findDetails(clusterId);
|
||||
if(clusterDetails.get("url") != null) {
|
||||
URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url")));
|
||||
morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath()));
|
||||
|
||||
|
||||
if(morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) {
|
||||
s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url"));
|
||||
return null;
|
||||
} else {
|
||||
ClusterMO clusterMo = new ClusterMO(context, morCluster);
|
||||
ClusterDasConfigInfo dasConfig = clusterMo.getDasConfig();
|
||||
if(dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) {
|
||||
if(dasConfig != null && dasConfig.isEnabled() != null && dasConfig.isEnabled().booleanValue()) {
|
||||
clusterDetails.put("NativeHA", "true");
|
||||
_clusterDetailsDao.persist(clusterId, clusterDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(!validateDiscoveredHosts(context, morCluster, morHosts)) {
|
||||
if(morCluster == null)
|
||||
s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster");
|
||||
|
|
@ -195,14 +195,14 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
for(ManagedObjectReference morHost : morHosts) {
|
||||
Map<String, String> details = new HashMap<String, String>();
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
|
||||
|
||||
HostMO hostMo = new HostMO(context, morHost);
|
||||
details.put("url", hostMo.getHostName());
|
||||
details.put("username", username);
|
||||
details.put("password", password);
|
||||
String guid = morHost.getType() + ":" + morHost.get_value() + "@"+ url.getHost();
|
||||
String guid = morHost.getType() + ":" + morHost.getValue() + "@"+ url.getHost();
|
||||
details.put("guid", guid);
|
||||
|
||||
|
||||
params.put("url", hostMo.getHostName());
|
||||
params.put("username", username);
|
||||
params.put("password", password);
|
||||
|
|
@ -219,8 +219,8 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
if (guestTrafficLabel != null) {
|
||||
params.put("guest.network.vswitch.name", guestTrafficLabel);
|
||||
}
|
||||
|
||||
VmwareResource resource = new VmwareResource();
|
||||
|
||||
VmwareResource resource = new VmwareResource();
|
||||
try {
|
||||
resource.configure("VMware", params);
|
||||
} catch (ConfigurationException e) {
|
||||
|
|
@ -228,14 +228,14 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
s_logger.warn("Unable to instantiate " + url.getHost(), e);
|
||||
}
|
||||
resource.start();
|
||||
|
||||
|
||||
resources.put(resource, details);
|
||||
}
|
||||
|
||||
|
||||
// place a place holder guid derived from cluster ID
|
||||
cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString());
|
||||
_clusterDao.update(clusterId, cluster);
|
||||
|
||||
|
||||
return resources;
|
||||
} catch (DiscoveredWithErrorException e) {
|
||||
throw e;
|
||||
|
|
@ -247,59 +247,59 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private boolean validateDiscoveredHosts(VmwareContext context, ManagedObjectReference morCluster, List<ManagedObjectReference> morHosts) throws Exception {
|
||||
if(morCluster == null) {
|
||||
for(ManagedObjectReference morHost : morHosts) {
|
||||
ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent");
|
||||
ManagedObjectReference morParent = (ManagedObjectReference)context.getVimClient().getDynamicProperty(morHost, "parent");
|
||||
if(morParent.getType().equalsIgnoreCase("ClusterComputeResource"))
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
for(ManagedObjectReference morHost : morHosts) {
|
||||
ManagedObjectReference morParent = (ManagedObjectReference)context.getServiceUtil().getDynamicProperty(morHost, "parent");
|
||||
ManagedObjectReference morParent = (ManagedObjectReference)context.getVimClient().getDynamicProperty(morHost, "parent");
|
||||
if(!morParent.getType().equalsIgnoreCase("ClusterComputeResource"))
|
||||
return false;
|
||||
|
||||
if(!morParent.get_value().equals(morCluster.get_value()))
|
||||
|
||||
if(!morParent.getValue().equals(morCluster.getValue()))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void postDiscovery(List<HostVO> hosts, long msId) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean matchHypervisor(String hypervisor) {
|
||||
if(hypervisor == null)
|
||||
return true;
|
||||
|
||||
|
||||
return Hypervisor.HypervisorType.VMware.toString().equalsIgnoreCase(hypervisor);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Hypervisor.HypervisorType getHypervisorType() {
|
||||
return Hypervisor.HypervisorType.VMware;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("Configure VmwareServerDiscoverer, discover name: " + name);
|
||||
|
||||
|
||||
super.configure(name, params);
|
||||
|
||||
|
||||
ComponentLocator locator = ComponentLocator.getCurrentLocator();
|
||||
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
|
||||
if (configDao == null) {
|
||||
throw new ConfigurationException("Unable to get the configuration dao.");
|
||||
}
|
||||
|
||||
|
||||
createVmwareToolsIso();
|
||||
|
||||
if(s_logger.isInfoEnabled()) {
|
||||
|
|
@ -308,7 +308,7 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
private void createVmwareToolsIso() {
|
||||
String isoName = "vmware-tools.iso";
|
||||
VMTemplateVO tmplt = _tmpltDao.findByTemplateName(isoName);
|
||||
|
|
@ -354,11 +354,11 @@ public class VmwareServerDiscoverer extends DiscovererBase implements Discoverer
|
|||
if (host.getType() != com.cloud.host.Host.Type.Routing || host.getHypervisorType() != HypervisorType.VMware) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
_resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage);
|
||||
return new DeleteHostAnswer(true);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean stop() {
|
||||
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
package com.cloud.hypervisor.vmware.manager;
|
||||
|
|
@ -71,6 +71,7 @@ import com.cloud.hypervisor.vmware.mo.TaskMO;
|
|||
import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType;
|
||||
import com.cloud.hypervisor.vmware.mo.VmwareHostType;
|
||||
import com.cloud.utils.ssh.SshHelper;
|
||||
import com.cloud.hypervisor.vmware.util.VmwareClient;
|
||||
import com.cloud.hypervisor.vmware.util.VmwareContext;
|
||||
import com.cloud.network.CiscoNexusVSMDeviceVO;
|
||||
import com.cloud.network.NetworkModel;
|
||||
|
|
@ -94,7 +95,6 @@ import com.cloud.utils.exception.CloudRuntimeException;
|
|||
import com.cloud.utils.script.Script;
|
||||
import com.cloud.vm.DomainRouterVO;
|
||||
import com.google.gson.Gson;
|
||||
import com.vmware.apputils.vim25.ServiceUtil;
|
||||
import com.vmware.vim25.HostConnectSpec;
|
||||
import com.vmware.vim25.ManagedObjectReference;
|
||||
|
||||
|
|
@ -123,7 +123,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
@Inject SecondaryStorageVmManager _ssvmMgr;
|
||||
@Inject CiscoNexusVSMDeviceDao _nexusDao;
|
||||
@Inject ClusterVSMMapDao _vsmMapDao;
|
||||
|
||||
|
||||
ConfigurationServer _configServer;
|
||||
|
||||
String _mountParent;
|
||||
|
|
@ -141,15 +141,15 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
int _additionalPortRangeSize;
|
||||
int _maxHostsPerCluster;
|
||||
int _routerExtraPublicNics = 2;
|
||||
|
||||
|
||||
String _cpuOverprovisioningFactor = "1";
|
||||
String _reserveCpu = "false";
|
||||
|
||||
|
||||
String _memOverprovisioningFactor = "1";
|
||||
String _reserveMem = "false";
|
||||
|
||||
|
||||
String _rootDiskController = DiskControllerType.ide.toString();
|
||||
|
||||
|
||||
Map<String, String> _storageMounts = new HashMap<String, String>();
|
||||
|
||||
Random _rand = new Random(System.currentTimeMillis());
|
||||
|
|
@ -217,7 +217,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
throw new ConfigurationException("Unable to find class " + value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
value = configDao.getValue(Config.VmwareUseNexusVSwitch.key());
|
||||
if(value == null) {
|
||||
_nexusVSwitchActive = false;
|
||||
|
|
@ -261,30 +261,30 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
if(_serviceConsoleName == null) {
|
||||
_serviceConsoleName = "Service Console";
|
||||
}
|
||||
|
||||
|
||||
_managemetPortGroupName = configDao.getValue(Config.VmwareManagementPortGroup.key());
|
||||
if(_managemetPortGroupName == null) {
|
||||
_managemetPortGroupName = "Management Network";
|
||||
}
|
||||
|
||||
|
||||
_defaultSystemVmNicAdapterType = configDao.getValue(Config.VmwareSystemVmNicDeviceType.key());
|
||||
if(_defaultSystemVmNicAdapterType == null)
|
||||
_defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString();
|
||||
|
||||
|
||||
_additionalPortRangeStart = NumbersUtil.parseInt(configDao.getValue(Config.VmwareAdditionalVncPortRangeStart.key()), 59000);
|
||||
if(_additionalPortRangeStart > 65535) {
|
||||
s_logger.warn("Invalid port range start port (" + _additionalPortRangeStart + ") for additional VNC port allocation, reset it to default start port 59000");
|
||||
_additionalPortRangeStart = 59000;
|
||||
}
|
||||
|
||||
|
||||
_additionalPortRangeSize = NumbersUtil.parseInt(configDao.getValue(Config.VmwareAdditionalVncPortRangeSize.key()), 1000);
|
||||
if(_additionalPortRangeSize < 0 || _additionalPortRangeStart + _additionalPortRangeSize > 65535) {
|
||||
s_logger.warn("Invalid port range size (" + _additionalPortRangeSize + " for range starts at " + _additionalPortRangeStart);
|
||||
_additionalPortRangeSize = Math.min(1000, 65535 - _additionalPortRangeStart);
|
||||
}
|
||||
|
||||
|
||||
_routerExtraPublicNics = NumbersUtil.parseInt(configDao.getValue(Config.RouterExtraPublicNics.key()), 2);
|
||||
|
||||
|
||||
_maxHostsPerCluster = NumbersUtil.parseInt(configDao.getValue(Config.VmwarePerClusterHostMax.key()), VmwareManager.MAX_HOSTS_PER_CLUSTER);
|
||||
_cpuOverprovisioningFactor = configDao.getValue(Config.CPUOverprovisioningFactor.key());
|
||||
if(_cpuOverprovisioningFactor == null || _cpuOverprovisioningFactor.isEmpty())
|
||||
|
|
@ -293,22 +293,22 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
_memOverprovisioningFactor = configDao.getValue(Config.MemOverprovisioningFactor.key());
|
||||
if(_memOverprovisioningFactor == null || _memOverprovisioningFactor.isEmpty())
|
||||
_memOverprovisioningFactor = "1";
|
||||
|
||||
|
||||
_reserveCpu = configDao.getValue(Config.VmwareReserveCpu.key());
|
||||
if(_reserveCpu == null || _reserveCpu.isEmpty())
|
||||
_reserveCpu = "false";
|
||||
_reserveMem = configDao.getValue(Config.VmwareReserveMem.key());
|
||||
if(_reserveMem == null || _reserveMem.isEmpty())
|
||||
_reserveMem = "false";
|
||||
|
||||
|
||||
_recycleHungWorker = configDao.getValue(Config.VmwareRecycleHungWorker.key());
|
||||
if(_recycleHungWorker == null || _recycleHungWorker.isEmpty())
|
||||
_recycleHungWorker = "false";
|
||||
|
||||
|
||||
_rootDiskController = configDao.getValue(Config.VmwareRootDiskControllerType.key());
|
||||
if(_rootDiskController == null || _rootDiskController.isEmpty())
|
||||
_rootDiskController = DiskControllerType.ide.toString();
|
||||
|
||||
|
||||
s_logger.info("Additional VNC port allocation range is settled at " + _additionalPortRangeStart + " to " + (_additionalPortRangeStart + _additionalPortRangeSize));
|
||||
|
||||
value = configDao.getValue("vmware.host.scan.interval");
|
||||
|
|
@ -319,7 +319,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
|
||||
if(_configServer == null)
|
||||
_configServer = (ConfigurationServer)ComponentLocator.getComponent(ConfigurationServer.Name);
|
||||
|
||||
|
||||
_agentMgr.registerForHostEvents(this, true, true, true);
|
||||
|
||||
s_logger.info("VmwareManagerImpl has been successfully configured");
|
||||
|
|
@ -352,6 +352,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
return _name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getNexusVSwitchGlobalParameter() {
|
||||
return _nexusVSwitchActive;
|
||||
}
|
||||
|
|
@ -360,22 +361,22 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
public String composeWorkerName() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getPrivateVSwitchName(long dcId, HypervisorType hypervisorType) {
|
||||
return _netMgr.getDefaultManagementTrafficLabel(dcId, hypervisorType);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getPublicVSwitchName(long dcId, HypervisorType hypervisorType) {
|
||||
return _netMgr.getDefaultPublicTrafficLabel(dcId, hypervisorType);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getGuestVSwitchName(long dcId, HypervisorType hypervisorType) {
|
||||
return _netMgr.getDefaultGuestTrafficLabel(dcId, hypervisorType);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<ManagedObjectReference> addHostToPodCluster(VmwareContext serviceContext, long dcId, Long podId, Long clusterId,
|
||||
String hostInventoryPath) throws Exception {
|
||||
|
|
@ -392,7 +393,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
List<ManagedObjectReference> returnedHostList = new ArrayList<ManagedObjectReference>();
|
||||
|
||||
if(mor.getType().equals("ComputeResource")) {
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getServiceUtil().getDynamicProperty(mor, "host");
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getVimClient().getDynamicProperty(mor, "host");
|
||||
assert(hosts != null);
|
||||
|
||||
// For ESX host, we need to enable host firewall to allow VNC access
|
||||
|
|
@ -400,7 +401,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
HostFirewallSystemMO firewallMo = hostMo.getHostFirewallSystemMO();
|
||||
if(firewallMo != null) {
|
||||
if(hostMo.getHostType() == VmwareHostType.ESX) {
|
||||
|
||||
|
||||
firewallMo.enableRuleset("vncServer");
|
||||
firewallMo.refreshFirewall();
|
||||
}
|
||||
|
|
@ -424,15 +425,15 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
returnedHostList.add(hosts[0]);
|
||||
return returnedHostList;
|
||||
} else if(mor.getType().equals("ClusterComputeResource")) {
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getServiceUtil().getDynamicProperty(mor, "host");
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])serviceContext.getVimClient().getDynamicProperty(mor, "host");
|
||||
assert(hosts != null);
|
||||
|
||||
|
||||
if(hosts.length > _maxHostsPerCluster) {
|
||||
String msg = "vCenter cluster size is too big (current configured cluster size: " + _maxHostsPerCluster + ")";
|
||||
s_logger.error(msg);
|
||||
throw new DiscoveredWithErrorException(msg);
|
||||
}
|
||||
|
||||
|
||||
for(ManagedObjectReference morHost: hosts) {
|
||||
// For ESX host, we need to enable host firewall to allow VNC access
|
||||
HostMO hostMo = new HostMO(serviceContext, morHost);
|
||||
|
|
@ -450,8 +451,8 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
if(tokens.length == 2)
|
||||
vlanId = tokens[1];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
s_logger.info("Calling prepareNetwork : " + hostMo.getContext().toString());
|
||||
// prepare at least one network on the vswitch to enable OVF importing
|
||||
if(!_nexusVSwitchActive) {
|
||||
|
|
@ -493,7 +494,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
returnedHostList.add(mor);
|
||||
return returnedHostList;
|
||||
} else {
|
||||
s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.get_value() + " from inventory path: " + hostInventoryPath);
|
||||
s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.getValue() + " from inventory path: " + hostInventoryPath);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -506,8 +507,8 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
private ManagedObjectReference addHostToVCenterCluster(VmwareContext serviceContext, ManagedObjectReference morCluster,
|
||||
String host, String userName, String password) throws Exception {
|
||||
|
||||
ServiceUtil serviceUtil = serviceContext.getServiceUtil();
|
||||
ManagedObjectReference morHost = serviceUtil.getDecendentMoRef(morCluster, "HostSystem", host);
|
||||
VmwareClient vclient = serviceContext.getVimClient();
|
||||
ManagedObjectReference morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host);
|
||||
if(morHost == null) {
|
||||
HostConnectSpec hostSpec = new HostConnectSpec();
|
||||
hostSpec.setUserName(userName);
|
||||
|
|
@ -515,16 +516,16 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
hostSpec.setHostName(host);
|
||||
hostSpec.setForce(true); // forcely take over the host
|
||||
|
||||
ManagedObjectReference morTask = serviceContext.getService().addHost_Task(morCluster, hostSpec, true, null, null);
|
||||
String taskResult = serviceUtil.waitForTask(morTask);
|
||||
if(!taskResult.equals("sucess")) {
|
||||
ManagedObjectReference morTask = serviceContext.getService().addHostTask(morCluster, hostSpec, true, null, null);
|
||||
boolean taskResult = vclient.waitForTask(morTask);
|
||||
if(!taskResult) {
|
||||
s_logger.error("Unable to add host " + host + " to vSphere cluster due to " + TaskMO.getTaskFailureInfo(serviceContext, morTask));
|
||||
throw new CloudRuntimeException("Unable to add host " + host + " to vSphere cluster due to " + taskResult);
|
||||
}
|
||||
serviceContext.waitForTaskProgressDone(morTask);
|
||||
|
||||
// init morHost after it has been created
|
||||
morHost = serviceUtil.getDecendentMoRef(morCluster, "HostSystem", host);
|
||||
morHost = vclient.getDecendentMoRef(morCluster, "HostSystem", host);
|
||||
if(morHost == null) {
|
||||
throw new CloudRuntimeException("Successfully added host into vSphere but unable to find it later on?!. Please make sure you are either using IP address or full qualified domain name for host");
|
||||
}
|
||||
|
|
@ -545,25 +546,27 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
List<HostVO> secStorageHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dcId);
|
||||
if(secStorageHosts.size() > 0)
|
||||
return secStorageHosts.get(0).getStorageUrl();
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getServiceConsolePortGroupName() {
|
||||
@Override
|
||||
public String getServiceConsolePortGroupName() {
|
||||
return _serviceConsoleName;
|
||||
}
|
||||
|
||||
public String getManagementPortGroupName() {
|
||||
|
||||
@Override
|
||||
public String getManagementPortGroupName() {
|
||||
return _managemetPortGroupName;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getManagementPortGroupByHost(HostMO hostMo) throws Exception {
|
||||
if(hostMo.getHostType() == VmwareHostType.ESXi)
|
||||
return this._managemetPortGroupName;
|
||||
return this._serviceConsoleName;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void setupResourceStartupParams(Map<String, Object> params) {
|
||||
params.put("private.network.vswitch.name", _privateNetworkVSwitchName);
|
||||
|
|
@ -585,17 +588,17 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
return _storageMgr;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public long pushCleanupCheckpoint(String hostGuid, String vmName) {
|
||||
return _checkPointMgr.pushCheckPoint(new VmwareCleanupMaid(hostGuid, vmName));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void popCleanupCheckpoint(long checkpoint) {
|
||||
_checkPointMgr.popCheckPoint(checkpoint);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void gcLeftOverVMs(VmwareContext context) {
|
||||
VmwareCleanupMaid.gcLeftOverVMs(context);
|
||||
|
|
@ -623,12 +626,12 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
if(!destIso.exists()) {
|
||||
s_logger.info("Inject SSH key pairs before copying systemvm.iso into secondary storage");
|
||||
_configServer.updateKeyPairs();
|
||||
|
||||
|
||||
try {
|
||||
FileUtil.copyfile(srcIso, destIso);
|
||||
} catch(IOException e) {
|
||||
s_logger.error("Unexpected exception ", e);
|
||||
|
||||
|
||||
String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso.toString() + ", dest location: " + destIso;
|
||||
s_logger.error(msg);
|
||||
throw new CloudRuntimeException(msg);
|
||||
|
|
@ -645,19 +648,19 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
lock.releaseRef();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getSystemVMIsoFileNameOnDatastore() {
|
||||
String version = ComponentLocator.class.getPackage().getImplementationVersion();
|
||||
String fileName = "systemvm-" + version + ".iso";
|
||||
return fileName.replace(':', '-');
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getSystemVMDefaultNicAdapterType() {
|
||||
return this._defaultSystemVmNicAdapterType;
|
||||
}
|
||||
|
||||
|
||||
private File getSystemVMPatchIsoFile() {
|
||||
// locate systemvm.iso
|
||||
URL url = ComponentLocator.class.getProtectionDomain().getCodeSource().getLocation();
|
||||
|
|
@ -866,7 +869,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
if(checkPointIdStr != null) {
|
||||
_checkPointMgr.popCheckPoint(Long.parseLong(checkPointIdStr));
|
||||
}
|
||||
|
||||
|
||||
checkPointIdStr = answer.getContextParam("checkpoint2");
|
||||
if(checkPointIdStr != null) {
|
||||
_checkPointMgr.popCheckPoint(Long.parseLong(checkPointIdStr));
|
||||
|
|
@ -897,9 +900,9 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected final int DEFAULT_DOMR_SSHPORT = 3922;
|
||||
|
||||
|
||||
protected boolean shutdownRouterVM(DomainRouterVO router) {
|
||||
if (s_logger.isDebugEnabled()) {
|
||||
s_logger.debug("Try to shutdown router VM " + router.getInstanceName() + " directly.");
|
||||
|
|
@ -943,27 +946,27 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
public boolean processTimeout(long agentId, long seq) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean beginExclusiveOperation(int timeOutSeconds) {
|
||||
return _exclusiveOpLock.lock(timeOutSeconds);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void endExclusiveOperation() {
|
||||
_exclusiveOpLock.unlock();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Pair<Integer, Integer> getAddiionalVncPortRange() {
|
||||
return new Pair<Integer, Integer>(_additionalPortRangeStart, _additionalPortRangeSize);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getMaxHostsPerCluster() {
|
||||
return this._maxHostsPerCluster;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int getRouterExtraPublicNics() {
|
||||
return this._routerExtraPublicNics;
|
||||
|
|
@ -977,7 +980,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
vsmMapVO = _vsmMapDao.findByClusterId(clusterId);
|
||||
long vsmId = 0;
|
||||
if (vsmMapVO != null) {
|
||||
vsmId = vsmMapVO.getVsmId();
|
||||
vsmId = vsmMapVO.getVsmId();
|
||||
s_logger.info("vsmId is " + vsmId);
|
||||
nexusVSM = _nexusDao.findById(vsmId);
|
||||
s_logger.info("Fetching nexus vsm credentials from database.");
|
||||
|
|
@ -985,7 +988,7 @@ public class VmwareManagerImpl implements VmwareManager, VmwareStorageMount, Lis
|
|||
else {
|
||||
s_logger.info("Found empty vsmMapVO.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> nexusVSMCredentials = new HashMap<String, String>();
|
||||
if (nexusVSM != null) {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
package com.cloud.hypervisor.vmware.manager;
|
||||
|
|
@ -69,24 +69,24 @@ import com.vmware.vim25.VirtualSCSISharing;
|
|||
|
||||
public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
||||
private static final Logger s_logger = Logger.getLogger(VmwareStorageManagerImpl.class);
|
||||
|
||||
|
||||
private final VmwareStorageMount _mountService;
|
||||
private final StorageLayer _storage = new JavaStorageLayer();
|
||||
|
||||
|
||||
private int _timeout;
|
||||
|
||||
|
||||
public VmwareStorageManagerImpl(VmwareStorageMount mountService) {
|
||||
assert(mountService != null);
|
||||
_mountService = mountService;
|
||||
}
|
||||
|
||||
|
||||
public void configure(Map<String, Object> params) {
|
||||
s_logger.info("Configure VmwareStorageManagerImpl");
|
||||
|
||||
|
||||
String value = (String)params.get("scripts.timeout");
|
||||
_timeout = NumbersUtil.parseInt(value, 1440) * 1000;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd) {
|
||||
String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
|
||||
|
|
@ -116,18 +116,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
templateName = cmd.getName();
|
||||
}
|
||||
|
||||
|
||||
VmwareContext context = hostService.getServiceContext(cmd);
|
||||
try {
|
||||
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
|
||||
|
||||
String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().get_value()).getBytes()).toString();
|
||||
|
||||
String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().getValue()).getBytes()).toString();
|
||||
// truncate template name to 32 chars to ensure they work well with vSphere API's.
|
||||
templateUuidName = templateUuidName.replace("-", "");
|
||||
|
||||
templateUuidName = templateUuidName.replace("-", "");
|
||||
|
||||
DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
|
||||
VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true);
|
||||
|
||||
|
||||
if (templateMo == null) {
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName);
|
||||
|
|
@ -153,7 +153,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
return new PrimaryStorageDownloadAnswer(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd) {
|
||||
Long accountId = cmd.getAccountId();
|
||||
|
|
@ -184,15 +184,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
if (vmMo == null) {
|
||||
if(s_logger.isDebugEnabled())
|
||||
s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter");
|
||||
|
||||
|
||||
vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName());
|
||||
if(vmMo == null) {
|
||||
dsMo = new DatastoreMO(hyperHost.getContext(), morDs);
|
||||
|
||||
|
||||
workerVMName = hostService.getWorkerName(context, cmd, 0);
|
||||
|
||||
|
||||
// attach a volume to dummay wrapper VM for taking snapshot and exporting the VM for backup
|
||||
if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier._otherGuest.toString(), morDs, false)) {
|
||||
if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString(), morDs, false)) {
|
||||
String msg = "Unable to create worker VM to execute BackupSnapshotCommand";
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
|
|
@ -202,17 +202,17 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName);
|
||||
}
|
||||
workerVm = vmMo;
|
||||
|
||||
|
||||
// attach volume to worker VM
|
||||
String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath);
|
||||
vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (!vmMo.createSnapshot(snapshotUuid, "Snapshot taken for " + cmd.getSnapshotName(), false, false)) {
|
||||
throw new Exception("Failed to take snapshot " + cmd.getSnapshotName() + " on vm: " + cmd.getVmName());
|
||||
}
|
||||
|
||||
|
||||
snapshotBackupUuid = backupSnapshotToSecondaryStorage(vmMo, accountId, volumeId, cmd.getVolumePath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid,
|
||||
hostService.getWorkerName(context, cmd, 1));
|
||||
|
||||
|
|
@ -220,11 +220,11 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
if (success) {
|
||||
details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage.";
|
||||
}
|
||||
|
||||
|
||||
} finally {
|
||||
if(vmMo != null)
|
||||
vmMo.removeAllSnapshots();
|
||||
|
||||
|
||||
try {
|
||||
if (workerVm != null) {
|
||||
// detach volume and destroy worker vm
|
||||
|
|
@ -233,7 +233,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
} catch (Throwable e) {
|
||||
s_logger.warn("Failed to destroy worker VM: " + workerVMName);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
if (e instanceof RemoteException) {
|
||||
|
|
@ -260,7 +260,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
VmwareContext context = hostService.getServiceContext(cmd);
|
||||
try {
|
||||
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
|
||||
|
||||
|
||||
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
|
||||
if (vmMo == null) {
|
||||
if(s_logger.isDebugEnabled())
|
||||
|
|
@ -276,7 +276,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
|
||||
Ternary<String, Long, Long> result = createTemplateFromVolume(vmMo,
|
||||
accountId, templateId, cmd.getUniqueName(),
|
||||
secondaryStoragePoolURL, volumePath,
|
||||
secondaryStoragePoolURL, volumePath,
|
||||
hostService.getWorkerName(context, cmd, 0));
|
||||
|
||||
return new CreatePrivateTemplateAnswer(cmd, true, null,
|
||||
|
|
@ -326,7 +326,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
return new CreatePrivateTemplateAnswer(cmd, false, details);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd) {
|
||||
Long volumeId = cmd.getVolumeId();
|
||||
|
|
@ -375,7 +375,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
return new CopyVolumeAnswer(cmd, false, "CopyVolumeCommand failed due to exception: " + StringUtils.getExceptionStackInfo(e), null, null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd) {
|
||||
|
||||
|
|
@ -392,7 +392,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
VmwareContext context = hostService.getServiceContext(cmd);
|
||||
try {
|
||||
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
|
||||
|
||||
|
||||
ManagedObjectReference morPrimaryDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStorageNameLabel);
|
||||
if (morPrimaryDs == null) {
|
||||
String msg = "Unable to find datastore: " + primaryStorageNameLabel;
|
||||
|
|
@ -417,22 +417,22 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
|
||||
return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName);
|
||||
}
|
||||
|
||||
|
||||
// templateName: name in secondary storage
|
||||
// templateUuid: will be used at hypervisor layer
|
||||
private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl,
|
||||
String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception {
|
||||
|
||||
s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: "
|
||||
|
||||
s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: "
|
||||
+ secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage
|
||||
+ ", templateName: " + templateName);
|
||||
|
||||
|
||||
String secondaryMountPoint = _mountService.getMountPoint(secondaryStorageUrl);
|
||||
s_logger.info("Secondary storage mount point: " + secondaryMountPoint);
|
||||
|
||||
String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage +
|
||||
|
||||
String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage +
|
||||
templateName + "." + ImageFormat.OVA.getFileExtension();
|
||||
|
||||
|
||||
String srcFileName = getOVFFilePath(srcOVAFileName);
|
||||
if(srcFileName == null) {
|
||||
Script command = new Script("tar", 0, s_logger);
|
||||
|
|
@ -447,40 +447,40 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
throw new Exception(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
srcFileName = getOVFFilePath(srcOVAFileName);
|
||||
if(srcFileName == null) {
|
||||
String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
|
||||
if(srcFileName == null) {
|
||||
String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
String vmName = templateUuid;
|
||||
hyperHost.importVmFromOVF(srcFileName, vmName, datastoreMo, "thin");
|
||||
|
||||
|
||||
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
|
||||
if(vmMo == null) {
|
||||
String msg = "Failed to import OVA template. secondaryStorage: "
|
||||
String msg = "Failed to import OVA template. secondaryStorage: "
|
||||
+ secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage
|
||||
+ ", templateName: " + templateName + ", templateUuid: " + templateUuid;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
if(vmMo.createSnapshot("cloud.template.base", "Base snapshot", false, false)) {
|
||||
vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, templateUuid);
|
||||
vmMo.markAsTemplate();
|
||||
} else {
|
||||
vmMo.destroy();
|
||||
String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid;
|
||||
String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
}
|
||||
|
||||
private Ternary<String, Long, Long> createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName,
|
||||
|
||||
private Ternary<String, Long, Long> createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName,
|
||||
String secStorageUrl, String volumePath, String workerVmName) throws Exception {
|
||||
|
||||
|
||||
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
|
||||
String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId);
|
||||
String installFullPath = secondaryMountPoint + "/" + installPath;
|
||||
|
|
@ -488,16 +488,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
Script command = new Script(false, "mkdir", _timeout, s_logger);
|
||||
command.add("-p");
|
||||
command.add(installFullPath);
|
||||
|
||||
|
||||
String result = command.execute();
|
||||
if(result != null) {
|
||||
String msg = "unable to prepare template directory: "
|
||||
String msg = "unable to prepare template directory: "
|
||||
+ installPath + ", storage: " + secStorageUrl + ", error msg: " + result;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
VirtualMachineMO clonedVm = null;
|
||||
try {
|
||||
Pair<VirtualDisk, String> volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false);
|
||||
|
|
@ -506,15 +506,15 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
if(!vmMo.createSnapshot(templateUniqueName, "Temporary snapshot for template creation", false, false)) {
|
||||
String msg = "Unable to take snapshot for creating template from volume. volume path: " + volumePath;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
// 4 MB is the minimum requirement for VM memory in VMware
|
||||
vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
|
||||
vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
|
||||
VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
|
||||
clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);
|
||||
if(clonedVm == null) {
|
||||
|
|
@ -522,9 +522,9 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false);
|
||||
|
||||
|
||||
long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length();
|
||||
VmdkProcessor processor = new VmdkProcessor();
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
|
|
@ -534,54 +534,54 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
|
||||
postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);
|
||||
return new Ternary<String, Long, Long>(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize);
|
||||
|
||||
|
||||
} finally {
|
||||
if(clonedVm != null) {
|
||||
clonedVm.detachAllDisks();
|
||||
clonedVm.destroy();
|
||||
}
|
||||
|
||||
|
||||
vmMo.removeSnapshot(templateUniqueName, false);
|
||||
}
|
||||
}
|
||||
|
||||
private Ternary<String, Long, Long> createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName,
|
||||
|
||||
private Ternary<String, Long, Long> createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName,
|
||||
String secStorageUrl, long volumeId, String backedUpSnapshotUuid) throws Exception {
|
||||
|
||||
|
||||
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
|
||||
String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId);
|
||||
String installFullPath = secondaryMountPoint + "/" + installPath;
|
||||
String installFullName = installFullPath + "/" + templateUniqueName + ".ova";
|
||||
String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId)
|
||||
String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId)
|
||||
+ "/" + backedUpSnapshotUuid + ".ova";
|
||||
String result;
|
||||
Script command;
|
||||
|
||||
|
||||
synchronized(installPath.intern()) {
|
||||
command = new Script(false, "mkdir", _timeout, s_logger);
|
||||
command.add("-p");
|
||||
command.add(installFullPath);
|
||||
|
||||
|
||||
result = command.execute();
|
||||
if(result != null) {
|
||||
String msg = "unable to prepare template directory: "
|
||||
String msg = "unable to prepare template directory: "
|
||||
+ installPath + ", storage: " + secStorageUrl + ", error msg: " + result;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
command = new Script(false, "cp", _timeout, s_logger);
|
||||
command.add(snapshotFullName);
|
||||
command.add(installFullName);
|
||||
result = command.execute();
|
||||
if(result != null) {
|
||||
String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath;
|
||||
String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
// untar OVA file at template directory
|
||||
command = new Script("tar", 0, s_logger);
|
||||
command.add("--no-same-owner");
|
||||
|
|
@ -590,12 +590,12 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
s_logger.info("Executing command: " + command.toString());
|
||||
result = command.execute();
|
||||
if(result != null) {
|
||||
String msg = "unable to untar snapshot " + snapshotFullName + " to "
|
||||
+ installFullPath;
|
||||
String msg = "unable to untar snapshot " + snapshotFullName + " to "
|
||||
+ installFullPath;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length();
|
||||
VmdkProcessor processor = new VmdkProcessor();
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
|
|
@ -605,45 +605,45 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
|
||||
postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);
|
||||
return new Ternary<String, Long, Long>(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize);
|
||||
|
||||
|
||||
} catch(Exception e) {
|
||||
// TODO, clean up left over files
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void postCreatePrivateTemplate(String installFullPath, long templateId,
|
||||
|
||||
private void postCreatePrivateTemplate(String installFullPath, long templateId,
|
||||
String templateName, long size, long virtualSize) throws Exception {
|
||||
|
||||
// TODO a bit ugly here
|
||||
BufferedWriter out = null;
|
||||
try {
|
||||
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties")));
|
||||
out.write("filename=" + templateName + ".ova");
|
||||
out.write("filename=" + templateName + ".ova");
|
||||
out.newLine();
|
||||
out.write("description=");
|
||||
out.write("description=");
|
||||
out.newLine();
|
||||
out.write("checksum=");
|
||||
out.write("checksum=");
|
||||
out.newLine();
|
||||
out.write("hvm=false");
|
||||
out.write("hvm=false");
|
||||
out.newLine();
|
||||
out.write("size=" + size);
|
||||
out.write("size=" + size);
|
||||
out.newLine();
|
||||
out.write("ova=true");
|
||||
out.write("ova=true");
|
||||
out.newLine();
|
||||
out.write("id=" + templateId);
|
||||
out.write("id=" + templateId);
|
||||
out.newLine();
|
||||
out.write("public=false");
|
||||
out.write("public=false");
|
||||
out.newLine();
|
||||
out.write("ova.filename=" + templateName + ".ova");
|
||||
out.write("ova.filename=" + templateName + ".ova");
|
||||
out.newLine();
|
||||
out.write("uniquename=" + templateName);
|
||||
out.newLine();
|
||||
out.write("ova.virtualsize=" + virtualSize);
|
||||
out.write("ova.virtualsize=" + virtualSize);
|
||||
out.newLine();
|
||||
out.write("virtualsize=" + virtualSize);
|
||||
out.write("virtualsize=" + virtualSize);
|
||||
out.newLine();
|
||||
out.write("ova.size=" + size);
|
||||
out.write("ova.size=" + size);
|
||||
out.newLine();
|
||||
} finally {
|
||||
if(out != null)
|
||||
|
|
@ -651,21 +651,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
}
|
||||
|
||||
private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
|
||||
private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
|
||||
long accountId, long volumeId, String secStorageUrl, String snapshotBackupUuid) throws Exception {
|
||||
|
||||
restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName,
|
||||
|
||||
restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName,
|
||||
secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), snapshotBackupUuid);
|
||||
return null;
|
||||
}
|
||||
|
||||
private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
|
||||
|
||||
private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
|
||||
String secStorageUrl, String secStorageDir, String backupName) throws Exception {
|
||||
|
||||
|
||||
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
|
||||
String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/"
|
||||
String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/"
|
||||
+ backupName + "." + ImageFormat.OVA.getFileExtension();
|
||||
|
||||
|
||||
String srcFileName = getOVFFilePath(srcOVAFileName);
|
||||
if(srcFileName == null) {
|
||||
Script command = new Script("tar", 0, s_logger);
|
||||
|
|
@ -680,21 +680,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
throw new Exception(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
srcFileName = getOVFFilePath(srcOVAFileName);
|
||||
if(srcFileName == null) {
|
||||
String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
|
||||
String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
VirtualMachineMO clonedVm = null;
|
||||
try {
|
||||
hyperHost.importVmFromOVF(srcFileName, newVolumeName, primaryDsMo, "thin");
|
||||
clonedVm = hyperHost.findVmOnHyperHost(newVolumeName);
|
||||
if(clonedVm == null)
|
||||
throw new Exception("Unable to create container VM for volume creation");
|
||||
|
||||
|
||||
clonedVm.moveAllVmDiskFiles(primaryDsMo, "", false);
|
||||
clonedVm.detachAllDisks();
|
||||
} finally {
|
||||
|
|
@ -704,24 +704,24 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId,
|
||||
String volumePath, String snapshotUuid, String secStorageUrl,
|
||||
|
||||
private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId,
|
||||
String volumePath, String snapshotUuid, String secStorageUrl,
|
||||
String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception {
|
||||
|
||||
|
||||
String backupUuid = UUID.randomUUID().toString();
|
||||
exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl,
|
||||
exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl,
|
||||
getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName);
|
||||
return backupUuid;
|
||||
}
|
||||
|
||||
private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath,
|
||||
|
||||
private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath,
|
||||
String secStorageUrl, String secStorageDir, String exportName,
|
||||
String workerVmName) throws Exception {
|
||||
|
||||
|
||||
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
|
||||
String exportPath = secondaryMountPoint + "/" + secStorageDir;
|
||||
|
||||
|
||||
synchronized(exportPath.intern()) {
|
||||
if(!new File(exportPath).exists()) {
|
||||
Script command = new Script(false, "mkdir", _timeout, s_logger);
|
||||
|
|
@ -734,16 +734,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
|
||||
VirtualMachineMO clonedVm = null;
|
||||
try {
|
||||
|
||||
|
||||
Pair<VirtualDisk, String> volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false);
|
||||
if(volumeDeviceInfo == null) {
|
||||
String msg = "Unable to find related disk device for volume. volume path: " + volumePath;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
// 4 MB is the minimum requirement for VM memory in VMware
|
||||
vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
|
||||
vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
|
||||
VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
|
||||
clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);
|
||||
if(clonedVm == null) {
|
||||
|
|
@ -751,7 +751,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
clonedVm.exportVm(exportPath, exportName, true, true);
|
||||
} finally {
|
||||
if(clonedVm != null) {
|
||||
|
|
@ -760,7 +760,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String deleteSnapshotOnSecondaryStorge(long accountId, long volumeId, String secStorageUrl, String backupUuid) throws Exception {
|
||||
|
||||
String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl);
|
||||
|
|
@ -769,18 +769,18 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
if(file.exists()) {
|
||||
if(file.delete())
|
||||
return null;
|
||||
|
||||
|
||||
} else {
|
||||
return "Backup file does not exist. backupUuid: " + backupUuid;
|
||||
}
|
||||
|
||||
|
||||
return "Failed to delete snapshot backup file, backupUuid: " + backupUuid;
|
||||
}
|
||||
|
||||
private Pair<String, String> copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd,
|
||||
String vmName, long volumeId, String poolId, String volumePath,
|
||||
|
||||
private Pair<String, String> copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd,
|
||||
String vmName, long volumeId, String poolId, String volumePath,
|
||||
String secStorageUrl, String workerVmName) throws Exception {
|
||||
|
||||
|
||||
String volumeFolder = String.valueOf(volumeId) + "/";
|
||||
VirtualMachineMO workerVm=null;
|
||||
VirtualMachineMO vmMo=null;
|
||||
|
|
@ -804,21 +804,21 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
vmConfig.setName(workerVmName);
|
||||
vmConfig.setMemoryMB((long) 4);
|
||||
vmConfig.setNumCPUs(1);
|
||||
vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString());
|
||||
vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.toString());
|
||||
VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
|
||||
fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
|
||||
vmConfig.setFiles(fileInfo);
|
||||
|
||||
// Scsi controller
|
||||
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
|
||||
scsiController.setSharedBus(VirtualSCSISharing.noSharing);
|
||||
scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
|
||||
scsiController.setBusNumber(0);
|
||||
scsiController.setKey(1);
|
||||
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
|
||||
scsiControllerSpec.setDevice(scsiController);
|
||||
scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
|
||||
vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec });
|
||||
|
||||
scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
|
||||
vmConfig.getDeviceChange().add(scsiControllerSpec);
|
||||
|
||||
hyperHost.createVm(vmConfig);
|
||||
workerVm = hyperHost.findVmOnHyperHost(workerVmName);
|
||||
if (workerVm == null) {
|
||||
|
|
@ -826,7 +826,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
//attach volume to worker VM
|
||||
String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath);
|
||||
workerVm.attachDisk(new String[] { datastoreVolumePath }, morDs);
|
||||
|
|
@ -835,7 +835,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
|
||||
vmMo.createSnapshot(exportName, "Temporary snapshot for copy-volume command", false, false);
|
||||
|
||||
exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName,
|
||||
exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName,
|
||||
hostService.getWorkerName(hyperHost.getContext(), cmd, 1));
|
||||
return new Pair<String, String>(volumeFolder, exportName);
|
||||
|
||||
|
|
@ -849,16 +849,16 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
}
|
||||
|
||||
private Pair<String, String> copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId,
|
||||
private Pair<String, String> 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<String, String>(volumeFolder, newVolume);
|
||||
}
|
||||
|
||||
|
||||
private String getOVFFilePath(String srcOVAFileName) {
|
||||
File file = new File(srcOVAFileName);
|
||||
assert(_storage != null);
|
||||
|
|
@ -873,11 +873,11 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private static String getTemplateRelativeDirInSecStorage(long accountId, long templateId) {
|
||||
return "template/tmpl/" + accountId + "/" + templateId;
|
||||
}
|
||||
|
||||
|
||||
private static String getSnapshotRelativeDirInSecStorage(long accountId, long volumeId) {
|
||||
return "snapshots/" + accountId + "/" + volumeId;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
package com.cloud.hypervisor.vmware.resource;
|
||||
|
|
@ -19,22 +19,22 @@ package com.cloud.hypervisor.vmware.resource;
|
|||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.cloud.hypervisor.vmware.manager.VmwareManager;
|
||||
import com.cloud.hypervisor.vmware.util.VmwareClient;
|
||||
import com.cloud.hypervisor.vmware.util.VmwareContext;
|
||||
import com.cloud.utils.StringUtils;
|
||||
import com.cloud.utils.component.ComponentLocator;
|
||||
import com.vmware.apputils.version.ExtendedAppUtil;
|
||||
|
||||
public class VmwareContextFactory {
|
||||
|
||||
|
||||
private static final Logger s_logger = Logger.getLogger(VmwareContextFactory.class);
|
||||
|
||||
|
||||
private static volatile int s_seq = 1;
|
||||
private static VmwareManager s_vmwareMgr;
|
||||
|
||||
|
||||
static {
|
||||
// skip certificate check
|
||||
System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");
|
||||
|
||||
|
||||
ComponentLocator locator = ComponentLocator.getLocator("management-server");
|
||||
s_vmwareMgr = locator.getManager(VmwareManager.class);
|
||||
}
|
||||
|
|
@ -45,17 +45,17 @@ public class VmwareContextFactory {
|
|||
assert(vCenterPassword != null);
|
||||
|
||||
String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService";
|
||||
String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword };
|
||||
//String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword };
|
||||
|
||||
if(s_logger.isDebugEnabled())
|
||||
s_logger.debug("initialize VmwareContext. url: " + serviceUrl + ", username: " + vCenterUserName + ", password: " + StringUtils.getMaskedPasswordForDisplay(vCenterPassword));
|
||||
|
||||
ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params);
|
||||
|
||||
appUtil.connect();
|
||||
VmwareContext context = new VmwareContext(appUtil, vCenterAddress);
|
||||
|
||||
VmwareClient vimClient = new VmwareClient(vCenterAddress + "-" + s_seq++);
|
||||
vimClient.connect(serviceUrl, vCenterUserName, vCenterPassword);
|
||||
|
||||
VmwareContext context = new VmwareContext(vimClient, vCenterAddress);
|
||||
context.registerStockObject(VmwareManager.CONTEXT_STOCK_NAME, s_vmwareMgr);
|
||||
|
||||
|
||||
context.registerStockObject("serviceconsole", s_vmwareMgr.getServiceConsolePortGroupName());
|
||||
context.registerStockObject("manageportgroup", s_vmwareMgr.getManagementPortGroupName());
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -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<String, VmwareContext> s_contextMap = new HashMap<String, VmwareContext>();
|
||||
|
||||
|
||||
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<Map.Entry<String, VmwareContext>> entryIter = s_contextMap.entrySet().iterator(); entryIter.hasNext();) {
|
||||
|
|
@ -68,7 +67,7 @@ public class VmwareSecondaryStorageContextFactory {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Pair<ManagedObjectReference, String>> hostsInCluster = clusterMo.getClusterHosts();
|
||||
for(Pair<ManagedObjectReference, String> 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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<DatacenterMO, String> 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<DynamicProperty> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> properties = _context.getService().retrieveProperties(
|
||||
_context.getPropertyCollector(), pfSpecArr);
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - retrieveProperties() done");
|
||||
return properties;
|
||||
return properties.toArray(new ObjectContent[properties.size()]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.get_value() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec));
|
||||
|
||||
s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.getValue() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec));
|
||||
|
||||
assert(vmSpec != null);
|
||||
DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter());
|
||||
ManagedObjectReference morPool = getHyperHostOwnerResourcePool();
|
||||
|
||||
ManagedObjectReference morTask = _context.getService().createVM_Task(
|
||||
|
||||
ManagedObjectReference morTask = _context.getService().createVMTask(
|
||||
dcMo.getVmFolder(), vmSpec, morPool, null);
|
||||
String result = _context.getServiceUtil().waitForTask(morTask);
|
||||
|
||||
if(result.equals("sucess")) {
|
||||
boolean result = _context.getVimClient().waitForTask(morTask);
|
||||
|
||||
if(result) {
|
||||
_context.waitForTaskProgressDone(morTask);
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - createVM_Task() done(successfully)");
|
||||
return true;
|
||||
} else {
|
||||
s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - createVM_Task() done(failed)");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void importVmFromOVF(String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption) throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.get_value() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName
|
||||
+ ", datastore: " + dsMo.getMor().get_value() + ", diskOption: " + diskOption);
|
||||
s_logger.trace("vCenter API trace - importVmFromOVF(). target MOR: " + _mor.getValue() + ", ovfFilePath: " + ovfFilePath + ", vmName: " + vmName
|
||||
+ ", datastore: " + dsMo.getMor().getValue() + ", diskOption: " + diskOption);
|
||||
|
||||
ManagedObjectReference morRp = getHyperHostOwnerResourcePool();
|
||||
assert(morRp != null);
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.get_value());
|
||||
|
||||
s_logger.trace("vCenter API trace - importVmFromOVF(). resource pool: " + morRp.getValue());
|
||||
|
||||
HypervisorHostHelper.importVmFromOVF(this, ovfFilePath, vmName, dsMo, diskOption, morRp, null);
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - importVmFromOVF() done");
|
||||
}
|
||||
|
|
@ -268,83 +270,83 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
|
|||
@Override
|
||||
public boolean createBlankVm(String vmName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB,
|
||||
String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception {
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.get_value() + ", vmName: " + vmName + ", cpuCount: " + cpuCount
|
||||
+ ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB
|
||||
+ ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.get_value() + ", snapshotDirToParent: " + snapshotDirToParent);
|
||||
|
||||
s_logger.trace("vCenter API trace - createBlankVm(). target MOR: " + _mor.getValue() + ", vmName: " + vmName + ", cpuCount: " + cpuCount
|
||||
+ ", cpuSpeedMhz: " + cpuSpeedMHz + ", cpuReservedMHz: " + cpuReservedMHz + ", limitCpu: " + limitCpuUse + ", memoryMB: " + memoryMB
|
||||
+ ", guestOS: " + guestOsIdentifier + ", datastore: " + morDs.getValue() + ", snapshotDirToParent: " + snapshotDirToParent);
|
||||
|
||||
boolean result = HypervisorHostHelper.createBlankVm(this, vmName, cpuCount, cpuSpeedMHz, cpuReservedMHz, limitCpuUse,
|
||||
memoryMB, memoryReserveMB, guestOsIdentifier, morDs, snapshotDirToParent);
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - createBlankVm() done");
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress,
|
||||
public ManagedObjectReference mountDatastore(boolean vmfsDatastore, String poolHostAddress,
|
||||
int poolHostPort, String poolPath, String poolUuid) throws Exception {
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.get_value() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress
|
||||
s_logger.trace("vCenter API trace - mountDatastore(). target MOR: " + _mor.getValue() + ", vmfs: " + vmfsDatastore + ", poolHost: " + poolHostAddress
|
||||
+ ", poolHostPort: " + poolHostPort + ", poolPath: " + poolPath + ", poolUuid: " + poolUuid);
|
||||
|
||||
|
||||
ManagedObjectReference morDs = null;
|
||||
ManagedObjectReference morDsFirst = null;
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host");
|
||||
if(hosts != null && hosts.length > 0) {
|
||||
for(ManagedObjectReference morHost : hosts) {
|
||||
HostMO hostMo = new HostMO(_context, morHost);
|
||||
morDs = hostMo.mountDatastore(vmfsDatastore, poolHostAddress, poolHostPort, poolPath, poolUuid);
|
||||
if(morDsFirst == null)
|
||||
morDsFirst = morDs;
|
||||
|
||||
|
||||
// assume datastore is in scope of datacenter
|
||||
assert(morDsFirst.get_value().equals(morDs.get_value()));
|
||||
assert(morDsFirst.getValue().equals(morDs.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(morDs == null) {
|
||||
String msg = "Failed to mount datastore in all hosts within the cluster";
|
||||
s_logger.error(msg);
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - mountDatastore() done(failed)");
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - mountDatastore() done(successfully)");
|
||||
|
||||
|
||||
return morDs;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void unmountDatastore(String poolUuid) throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid);
|
||||
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
|
||||
s_logger.trace("vCenter API trace - unmountDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid);
|
||||
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host");
|
||||
if(hosts != null && hosts.length > 0) {
|
||||
for(ManagedObjectReference morHost : hosts) {
|
||||
HostMO hostMo = new HostMO(_context, morHost);
|
||||
hostMo.unmountDatastore(poolUuid);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - unmountDatastore() done");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ManagedObjectReference findDatastore(String poolUuid) throws Exception {
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findDatastore(). target MOR: " + _mor.get_value() + ", poolUuid: " + poolUuid);
|
||||
|
||||
CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
|
||||
s_logger.trace("vCenter API trace - findDatastore(). target MOR: " + _mor.getValue() + ", poolUuid: " + poolUuid);
|
||||
|
||||
CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(_context,
|
||||
_context.getServiceContent().getCustomFieldsManager());
|
||||
int key = cfmMo.getCustomFieldKey("Datastore", CustomFieldConstants.CLOUD_UUID);
|
||||
assert(key != 0);
|
||||
|
|
@ -352,16 +354,16 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
|
|||
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"name", String.format("value[%d]", key)});
|
||||
if(ocs != null) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
if(oc.getPropSet(0).getVal().equals(poolUuid))
|
||||
if(oc.getPropSet().get(0).getVal().equals(poolUuid))
|
||||
return oc.getObj();
|
||||
|
||||
if(oc.getPropSet().length > 1) {
|
||||
DynamicProperty prop = oc.getPropSet(1);
|
||||
|
||||
if(oc.getPropSet().size() > 1) {
|
||||
DynamicProperty prop = oc.getPropSet().get(1);
|
||||
if(prop != null && prop.getVal() != null) {
|
||||
if(prop.getVal() instanceof CustomFieldStringValue) {
|
||||
String val = ((CustomFieldStringValue)prop.getVal()).getValue();
|
||||
if(val.equalsIgnoreCase(poolUuid)) {
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findDatastore() done(successfully)");
|
||||
return oc.getObj();
|
||||
|
|
@ -371,31 +373,31 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findDatastore() done(failed)");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findDatastoreByExportPath(). target MOR: " + _mor.get_value() + ", exportPath: " + exportPath);
|
||||
|
||||
s_logger.trace("vCenter API trace - findDatastoreByExportPath(). target MOR: " + _mor.getValue() + ", exportPath: " + exportPath);
|
||||
|
||||
ObjectContent[] ocs = getDatastorePropertiesOnHyperHost(new String[] {"info"});
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet(0).getVal();
|
||||
DatastoreInfo dsInfo = (DatastoreInfo)oc.getPropSet().get(0).getVal();
|
||||
if(dsInfo != null && dsInfo instanceof NasDatastoreInfo) {
|
||||
NasDatastoreInfo info = (NasDatastoreInfo)dsInfo;
|
||||
if(info != null) {
|
||||
String vmwareUrl = info.getUrl();
|
||||
if(vmwareUrl.charAt(vmwareUrl.length() - 1) == '/')
|
||||
vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1);
|
||||
|
||||
|
||||
URI uri = new URI(vmwareUrl);
|
||||
if(uri.getPath().equals("/" + exportPath)) {
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(successfully)");
|
||||
return oc.getObj();
|
||||
|
|
@ -404,49 +406,49 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findDatastoreByExportPath() done(failed)");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ManagedObjectReference findMigrationTarget(VirtualMachineMO vmMo) throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.get_value() + ", vm: " + vmMo.getName());
|
||||
s_logger.trace("vCenter API trace - findMigrationTarget(). target MOR: " + _mor.getValue() + ", vm: " + vmMo.getName());
|
||||
|
||||
ClusterHostRecommendation[] candidates = recommendHostsForVm(vmMo);
|
||||
if(candidates != null && candidates.length > 0) {
|
||||
List<ClusterHostRecommendation> candidates = recommendHostsForVm(vmMo);
|
||||
if(candidates != null && candidates.size() > 0) {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findMigrationTarget() done(successfully)");
|
||||
return candidates[0].getHost();
|
||||
return candidates.get(0).getHost();
|
||||
}
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - findMigrationTarget() done(failed)");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean isHyperHostConnected() throws Exception {
|
||||
ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"runtime"});
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)oc.getPropSet(0).getVal();
|
||||
// as long as we have one host connected, we assume the cluster is up
|
||||
if(runtimeInfo.getConnectionState() == HostSystemConnectionState.connected)
|
||||
HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)oc.getPropSet().get(0).getVal();
|
||||
// as long as we have one host connected, we assume the cluster is up
|
||||
if(runtimeInfo.getConnectionState() == HostSystemConnectionState.CONNECTED)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getHyperHostDefaultGateway() throws Exception {
|
||||
ObjectContent[] ocs = getHostPropertiesOnCluster(new String[] {"config.network.routeTableInfo.ipRoute"});
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
ArrayOfHostIpRouteEntry entries = (ArrayOfHostIpRouteEntry)oc.getPropSet(0).getVal();
|
||||
ArrayOfHostIpRouteEntry entries = (ArrayOfHostIpRouteEntry)oc.getPropSet().get(0).getVal();
|
||||
if(entries != null) {
|
||||
for(HostIpRouteEntry entry : entries.getHostIpRouteEntry()) {
|
||||
if(entry.getNetwork().equalsIgnoreCase("0.0.0.0"))
|
||||
|
|
@ -455,28 +457,28 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
throw new Exception("Could not find host default gateway, host is not properly configured?");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public VmwareHypervisorHostResourceSummary getHyperHostResourceSummary() throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.get_value());
|
||||
s_logger.trace("vCenter API trace - getHyperHostResourceSummary(). target MOR: " + _mor.getValue());
|
||||
|
||||
VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary();
|
||||
|
||||
ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getServiceUtil().getDynamicProperty(
|
||||
|
||||
ComputeResourceSummary vmwareSummary = (ComputeResourceSummary)_context.getVimClient().getDynamicProperty(
|
||||
_mor, "summary");
|
||||
|
||||
// TODO, need to use traversal to optimize retrieve of
|
||||
|
||||
// TODO, need to use traversal to optimize retrieve of
|
||||
int cpuNumInCpuThreads = 1;
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host");
|
||||
if(hosts != null && hosts.length > 0) {
|
||||
for(ManagedObjectReference morHost : hosts) {
|
||||
HostMO hostMo = new HostMO(_context, morHost);
|
||||
HostHardwareSummary hardwareSummary = hostMo.getHostHardwareSummary();
|
||||
|
||||
|
||||
if(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuThreads() > cpuNumInCpuThreads)
|
||||
cpuNumInCpuThreads = hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuThreads();
|
||||
}
|
||||
|
|
@ -484,74 +486,74 @@ public class ClusterMO extends BaseMO implements VmwareHypervisorHost {
|
|||
summary.setCpuCount(cpuNumInCpuThreads);
|
||||
summary.setCpuSpeed(vmwareSummary.getTotalCpu());
|
||||
summary.setMemoryBytes(vmwareSummary.getTotalMemory());
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done");
|
||||
return summary;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public VmwareHypervisorHostNetworkSummary getHyperHostNetworkSummary(String esxServiceConsolePort) throws Exception {
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.get_value() + ", mgmtPortgroup: " + esxServiceConsolePort);
|
||||
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "host");
|
||||
s_logger.trace("vCenter API trace - getHyperHostNetworkSummary(). target MOR: " + _mor.getValue() + ", mgmtPortgroup: " + esxServiceConsolePort);
|
||||
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "host");
|
||||
if(hosts != null && hosts.length > 0) {
|
||||
VmwareHypervisorHostNetworkSummary summary = new HostMO(_context, hosts[0]).getHyperHostNetworkSummary(esxServiceConsolePort);
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(successfully)");
|
||||
return summary;
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostResourceSummary() done(failed)");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ComputeResourceSummary getHyperHostHardwareSummary() throws Exception {
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.get_value());
|
||||
s_logger.trace("vCenter API trace - getHyperHostHardwareSummary(). target MOR: " + _mor.getValue());
|
||||
|
||||
ClusterComputeResourceSummary hardwareSummary = (ClusterComputeResourceSummary)
|
||||
_context.getServiceUtil().getDynamicProperty(_mor, "summary");
|
||||
_context.getVimClient().getDynamicProperty(_mor, "summary");
|
||||
|
||||
if(s_logger.isTraceEnabled())
|
||||
s_logger.trace("vCenter API trace - getHyperHostHardwareSummary() done");
|
||||
return hardwareSummary;
|
||||
}
|
||||
|
||||
public ClusterHostRecommendation[] recommendHostsForVm(VirtualMachineMO vmMo) throws Exception {
|
||||
return _context.getService().recommendHostsForVm(_mor, vmMo.getMor(),
|
||||
public List<ClusterHostRecommendation> recommendHostsForVm(VirtualMachineMO vmMo) throws Exception {
|
||||
return _context.getService().recommendHostsForVm(_mor, vmMo.getMor(),
|
||||
getHyperHostOwnerResourcePool());
|
||||
}
|
||||
|
||||
|
||||
public List<Pair<ManagedObjectReference, String>> getClusterHosts() throws Exception {
|
||||
List<Pair<ManagedObjectReference, String>> hosts = new ArrayList<Pair<ManagedObjectReference, String>>();
|
||||
|
||||
|
||||
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<ManagedObjectReference, String>(morHost, name));
|
||||
}
|
||||
}
|
||||
return hosts;
|
||||
}
|
||||
|
||||
|
||||
public HashMap<String, Integer> getVmVncPortsOnCluster() throws Exception {
|
||||
ObjectContent[] ocs = getVmPropertiesOnHyperHost(
|
||||
new String[] { "name", "config.extraConfig[\"RemoteDisplay.vnc.port\"]" }
|
||||
);
|
||||
|
||||
|
||||
HashMap<String, Integer> portInfo = new HashMap<String, Integer>();
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DynamicProperty[] objProps = oc.getPropSet();
|
||||
List<DynamicProperty> 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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,32 +26,32 @@ public class CustomFieldsManagerMO extends BaseMO {
|
|||
public CustomFieldsManagerMO(VmwareContext context, ManagedObjectReference mor) {
|
||||
super(context, mor);
|
||||
}
|
||||
|
||||
|
||||
public CustomFieldsManagerMO(VmwareContext context, String morType, String morValue) {
|
||||
super(context, morType, morValue);
|
||||
}
|
||||
|
||||
public CustomFieldDef addCustomerFieldDef(String fieldName, String morType,
|
||||
|
||||
public CustomFieldDef addCustomerFieldDef(String fieldName, String morType,
|
||||
PrivilegePolicyDef fieldDefPolicy, PrivilegePolicyDef fieldPolicy) throws Exception {
|
||||
return _context.getService().addCustomFieldDef(getMor(), fieldName, morType, fieldDefPolicy, fieldPolicy);
|
||||
}
|
||||
|
||||
|
||||
public void removeCustomFieldDef(int key) throws Exception {
|
||||
_context.getService().removeCustomFieldDef(getMor(), key);
|
||||
}
|
||||
|
||||
|
||||
public void renameCustomFieldDef(int key, String name) throws Exception {
|
||||
_context.getService().renameCustomFieldDef(getMor(), key, name);
|
||||
}
|
||||
|
||||
|
||||
public void setField(ManagedObjectReference morEntity, int key, String value) throws Exception {
|
||||
_context.getService().setField(getMor(), morEntity, key, value);
|
||||
}
|
||||
|
||||
|
||||
public CustomFieldDef[] getFields() throws Exception {
|
||||
return (CustomFieldDef[])_context.getServiceUtil().getDynamicProperty(getMor(), "field");
|
||||
return (CustomFieldDef[])_context.getVimClient().getDynamicProperty(getMor(), "field");
|
||||
}
|
||||
|
||||
|
||||
public int getCustomFieldKey(String morType, String fieldName) throws Exception {
|
||||
CustomFieldDef[] fields = getFields();
|
||||
if(fields != null) {
|
||||
|
|
@ -62,12 +62,12 @@ public class CustomFieldsManagerMO extends BaseMO {
|
|||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
public int ensureCustomFieldDef(String morType, String fieldName) throws Exception {
|
||||
int key = getCustomFieldKey(morType, fieldName);
|
||||
if(key > 0)
|
||||
return key;
|
||||
|
||||
|
||||
try {
|
||||
CustomFieldDef field = addCustomerFieldDef(fieldName, morType, null, null);
|
||||
return field.getKey();
|
||||
|
|
@ -75,10 +75,10 @@ public class CustomFieldsManagerMO extends BaseMO {
|
|||
// assuming that someone is adding it
|
||||
key = getCustomFieldKey(morType, fieldName);
|
||||
}
|
||||
|
||||
|
||||
if(key == 0)
|
||||
throw new Exception("Unable to setup custom field facility for " + morType + ":" + fieldName);
|
||||
|
||||
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" });
|
||||
if(ocs != null && ocs.size() > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DynamicProperty[] props = oc.getPropSet();
|
||||
List<DynamicProperty> 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<VirtualMachineMO> 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<VirtualMachineMO> list = new ArrayList<VirtualMachineMO>();
|
||||
|
||||
ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name", String.format("value[%d]", key)});
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
|
||||
List<ObjectContent> 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<DynamicProperty> 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<Pair<ManagedObjectReference, String>> getAllVmsOnDatacenter() throws Exception {
|
||||
List<Pair<ManagedObjectReference, String>> vms = new ArrayList<Pair<ManagedObjectReference, String>>();
|
||||
|
||||
ObjectContent[] ocs = getVmPropertiesOnDatacenterVmFolder(new String[] { "name" });
|
||||
|
||||
List<ObjectContent> 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<ManagedObjectReference, String>(oc.getObj(), vmName));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return vms;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ManagedObjectReference findDatastore(String name) throws Exception {
|
||||
assert(name != null);
|
||||
|
||||
ObjectContent[] ocs = getDatastorePropertiesOnDatacenter(new String[] { "name" });
|
||||
|
||||
List<ObjectContent> 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<ObjectContent> 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<ObjectContent> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
|
||||
|
||||
}
|
||||
|
||||
public ObjectContent[] getDatastorePropertiesOnDatacenter(String[] propertyPaths) throws Exception {
|
||||
|
||||
|
||||
public List<ObjectContent> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
|
||||
|
||||
}
|
||||
|
||||
public ObjectContent[] getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception {
|
||||
|
||||
public List<ObjectContent> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
|
||||
}
|
||||
|
||||
public static Pair<DatacenterMO, String> getOwnerDatacenter(VmwareContext context,
|
||||
|
||||
public static Pair<DatacenterMO, String> 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<DatacenterMO, String>(new DatacenterMO(context, ocs[0].getObj()), dcName);
|
||||
pfSpec.getPropSet().add(pSpec);
|
||||
pfSpec.getObjectSet().add(oSpec);
|
||||
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> 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<DatacenterMO, String>(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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> ocs = _context.getService().retrieveProperties(
|
||||
_context.getPropertyCollector(), pfSpecArr);
|
||||
|
||||
if(ocs != null) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DynamicProperty[] props = oc.getPropSet();
|
||||
List<DynamicProperty> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> ocs = _context.getService().retrieveProperties(
|
||||
_context.getPropertyCollector(), pfSpecArr);
|
||||
|
||||
if(ocs != null) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DynamicProperty[] props = oc.getPropSet();
|
||||
List<DynamicProperty> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
ObjectContent[] ocs = _context.getService().retrieveProperties(
|
||||
_context.getServiceContent().getPropertyCollector(),
|
||||
new PropertyFilterSpec[] { pfSpec });
|
||||
List<ObjectContent> ocs = _context.getService().retrieveProperties(
|
||||
_context.getPropertyCollector(), pfSpecArr);
|
||||
|
||||
if (ocs != null) {
|
||||
for (ObjectContent oc : ocs) {
|
||||
DynamicProperty[] props = oc.getPropSet();
|
||||
List<DynamicProperty> 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<ManagedObjectReference, String> 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);
|
||||
|
|
|
|||
|
|
@ -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<DatacenterMO, String> _ownerDc;
|
||||
|
||||
|
||||
private String _name;
|
||||
private Pair<DatacenterMO, String> _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<DatacenterMO, String> dcInfo = getOwnerDatacenter();
|
||||
return dcInfo.second() + "/" + getName();
|
||||
}
|
||||
|
||||
|
||||
public Pair<DatacenterMO, String> 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<DatacenterMO, String>(new DatacenterMO(_context, ocs[0].getObj()), dcName);
|
||||
pfSpec.getPropSet().add(pSpec);
|
||||
pfSpec.getObjectSet().add(oSpec);
|
||||
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
List<ObjectContent> 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<DatacenterMO, String>(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<DatacenterMO, String> dcPair = getOwnerDatacenter();
|
||||
|
||||
|
||||
List<String> files = new ArrayList<String>();
|
||||
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<DatacenterMO, String> 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<FileInfo> 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<FileInfo> 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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<ObjectContent> ocs = getDatastorePropertiesOnHostDatastoreSystem(
|
||||
new String[] { "name", String.format("value[%d]", key) });
|
||||
if(ocs != null) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
if(oc.getPropSet(0).getVal().equals(name))
|
||||
if(oc.getPropSet().get(0).getVal().equals(name))
|
||||
return oc.getObj();
|
||||
|
||||
if(oc.getPropSet().length > 1) {
|
||||
DynamicProperty prop = oc.getPropSet(1);
|
||||
|
||||
if(oc.getPropSet().size() > 1) {
|
||||
DynamicProperty prop = oc.getPropSet().get(1);
|
||||
if(prop != null && prop.getVal() != null) {
|
||||
if(prop.getVal() instanceof CustomFieldStringValue) {
|
||||
String val = ((CustomFieldStringValue)prop.getVal()).getValue();
|
||||
|
|
@ -70,11 +73,11 @@ public class HostDatastoreSystemMO extends BaseMO {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// storeUrl in nfs://host/exportpath format
|
||||
public ManagedObjectReference findDatastoreByUrl(String storeUrl) throws Exception {
|
||||
assert(storeUrl != null);
|
||||
|
||||
|
||||
ManagedObjectReference[] datastores = getDatastores();
|
||||
if(datastores != null && datastores.length > 0) {
|
||||
for(ManagedObjectReference morDatastore : datastores) {
|
||||
|
|
@ -87,7 +90,7 @@ public class HostDatastoreSystemMO extends BaseMO {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -95,30 +98,30 @@ public class HostDatastoreSystemMO extends BaseMO {
|
|||
// we should be able to find the datastore by name
|
||||
public ManagedObjectReference findDatastoreByExportPath(String exportPath) throws Exception {
|
||||
assert(exportPath != null);
|
||||
|
||||
|
||||
ManagedObjectReference[] datastores = getDatastores();
|
||||
if(datastores != null && datastores.length > 0) {
|
||||
for(ManagedObjectReference morDatastore : datastores) {
|
||||
DatastoreMO dsMo = new DatastoreMO(_context, morDatastore);
|
||||
if(dsMo.getInventoryPath().equals(exportPath))
|
||||
if(dsMo.getInventoryPath().equals(exportPath))
|
||||
return morDatastore;
|
||||
|
||||
|
||||
NasDatastoreInfo info = getNasDatastoreInfo(morDatastore);
|
||||
if(info != null) {
|
||||
String vmwareUrl = info.getUrl();
|
||||
if(vmwareUrl.charAt(vmwareUrl.length() - 1) == '/')
|
||||
vmwareUrl = vmwareUrl.substring(0, vmwareUrl.length() - 1);
|
||||
|
||||
|
||||
URI uri = new URI(vmwareUrl);
|
||||
if(uri.getPath().equals("/" + exportPath))
|
||||
return morDatastore;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public boolean deleteDatastore(String name) throws Exception {
|
||||
ManagedObjectReference morDatastore = findDatastore(name);
|
||||
if(morDatastore != null) {
|
||||
|
|
@ -127,59 +130,60 @@ public class HostDatastoreSystemMO extends BaseMO {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public ManagedObjectReference createNfsDatastore(String host, int port,
|
||||
|
||||
public ManagedObjectReference createNfsDatastore(String host, int port,
|
||||
String exportPath, String uuid) throws Exception {
|
||||
|
||||
|
||||
HostNasVolumeSpec spec = new HostNasVolumeSpec();
|
||||
spec.setRemoteHost(host);
|
||||
spec.setRemotePath(exportPath);
|
||||
spec.setType("nfs");
|
||||
spec.setLocalPath(uuid);
|
||||
|
||||
|
||||
// readOnly/readWrite
|
||||
spec.setAccessMode("readWrite");
|
||||
return _context.getService().createNasDatastore(_mor, spec);
|
||||
}
|
||||
|
||||
|
||||
public ManagedObjectReference[] getDatastores() throws Exception {
|
||||
return (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(
|
||||
return (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(
|
||||
_mor, "datastore");
|
||||
}
|
||||
|
||||
|
||||
public DatastoreInfo getDatastoreInfo(ManagedObjectReference morDatastore) throws Exception {
|
||||
return (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info");
|
||||
return (DatastoreInfo)_context.getVimClient().getDynamicProperty(morDatastore, "info");
|
||||
}
|
||||
|
||||
|
||||
public NasDatastoreInfo getNasDatastoreInfo(ManagedObjectReference morDatastore) throws Exception {
|
||||
DatastoreInfo info = (DatastoreInfo)_context.getServiceUtil().getDynamicProperty(morDatastore, "info");
|
||||
DatastoreInfo info = (DatastoreInfo)_context.getVimClient().getDynamicProperty(morDatastore, "info");
|
||||
if(info instanceof NasDatastoreInfo)
|
||||
return (NasDatastoreInfo)info;
|
||||
return null;
|
||||
}
|
||||
|
||||
public ObjectContent[] getDatastorePropertiesOnHostDatastoreSystem(String[] propertyPaths) throws Exception {
|
||||
|
||||
|
||||
public List<ObjectContent> 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<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
|
||||
return _context.getService().retrieveProperties(
|
||||
_context.getServiceContent().getPropertyCollector(),
|
||||
new PropertyFilterSpec[] { pfSpec });
|
||||
_context.getPropertyCollector(), pfSpecArr);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -20,6 +20,7 @@ import java.io.BufferedReader;
|
|||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
|
|
@ -33,108 +34,108 @@ import com.vmware.vim25.OvfFileItem;
|
|||
|
||||
public class HttpNfcLeaseMO extends BaseMO {
|
||||
private static final Logger s_logger = Logger.getLogger(HttpNfcLeaseMO.class);
|
||||
|
||||
|
||||
public HttpNfcLeaseMO(VmwareContext context, ManagedObjectReference morHttpNfcLease) {
|
||||
super(context, morHttpNfcLease);
|
||||
}
|
||||
|
||||
|
||||
public HttpNfcLeaseMO(VmwareContext context, String morType, String morValue) {
|
||||
super(context, morType, morValue);
|
||||
}
|
||||
|
||||
public HttpNfcLeaseState getState() throws Exception {
|
||||
return (HttpNfcLeaseState)_context.getServiceUtil().getDynamicProperty(_mor, "state");
|
||||
return (HttpNfcLeaseState)_context.getVimClient().getDynamicProperty(_mor, "state");
|
||||
}
|
||||
|
||||
|
||||
public HttpNfcLeaseState waitState(HttpNfcLeaseState[] states) throws Exception {
|
||||
assert(states != null);
|
||||
assert(states.length > 0);
|
||||
|
||||
|
||||
HttpNfcLeaseState state;
|
||||
while(true) {
|
||||
state = getState();
|
||||
if(state == HttpNfcLeaseState.ready || state == HttpNfcLeaseState.error)
|
||||
if(state == HttpNfcLeaseState.READY || state == HttpNfcLeaseState.ERROR)
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public HttpNfcLeaseInfo getLeaseInfo() throws Exception {
|
||||
return (HttpNfcLeaseInfo)_context.getServiceUtil().getDynamicProperty(_mor, "info");
|
||||
return (HttpNfcLeaseInfo)_context.getVimClient().getDynamicProperty(_mor, "info");
|
||||
}
|
||||
|
||||
public HttpNfcLeaseManifestEntry[] getLeaseManifest() throws Exception {
|
||||
|
||||
public List<HttpNfcLeaseManifestEntry> getLeaseManifest() throws Exception {
|
||||
return _context.getService().httpNfcLeaseGetManifest(_mor);
|
||||
}
|
||||
|
||||
|
||||
public void completeLease() throws Exception {
|
||||
_context.getService().httpNfcLeaseComplete(_mor);
|
||||
}
|
||||
|
||||
|
||||
public void abortLease() throws Exception {
|
||||
_context.getService().httpNfcLeaseAbort(_mor, null);
|
||||
}
|
||||
|
||||
|
||||
public void updateLeaseProgress(int percent) throws Exception {
|
||||
// make sure percentage is in right range
|
||||
if(percent < 0)
|
||||
percent = 0;
|
||||
else if(percent > 100)
|
||||
percent = 100;
|
||||
|
||||
|
||||
_context.getService().httpNfcLeaseProgress(_mor, percent);
|
||||
}
|
||||
|
||||
|
||||
public ProgressReporter createProgressReporter() {
|
||||
return new ProgressReporter();
|
||||
}
|
||||
|
||||
public static long calcTotalBytes(OvfCreateImportSpecResult ovfImportResult) {
|
||||
OvfFileItem[] fileItemArr = ovfImportResult.getFileItem();
|
||||
long totalBytes = 0;
|
||||
if (fileItemArr != null) {
|
||||
for (OvfFileItem fi : fileItemArr) {
|
||||
totalBytes += fi.getSize();
|
||||
}
|
||||
}
|
||||
return totalBytes;
|
||||
}
|
||||
|
||||
public static String readOvfContent(String ovfFilePath) throws IOException {
|
||||
StringBuffer strContent = new StringBuffer();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath)));
|
||||
String lineStr;
|
||||
while ((lineStr = in.readLine()) != null) {
|
||||
strContent.append(lineStr);
|
||||
}
|
||||
|
||||
in.close();
|
||||
return strContent.toString();
|
||||
public static long calcTotalBytes(OvfCreateImportSpecResult ovfImportResult) {
|
||||
List<OvfFileItem> fileItemArr = ovfImportResult.getFileItem();
|
||||
long totalBytes = 0;
|
||||
if (fileItemArr != null) {
|
||||
for (OvfFileItem fi : fileItemArr) {
|
||||
totalBytes += fi.getSize();
|
||||
}
|
||||
}
|
||||
return totalBytes;
|
||||
}
|
||||
|
||||
|
||||
public static String readOvfContent(String ovfFilePath) throws IOException {
|
||||
StringBuffer strContent = new StringBuffer();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ovfFilePath)));
|
||||
String lineStr;
|
||||
while ((lineStr = in.readLine()) != null) {
|
||||
strContent.append(lineStr);
|
||||
}
|
||||
|
||||
in.close();
|
||||
return strContent.toString();
|
||||
}
|
||||
|
||||
public class ProgressReporter extends Thread {
|
||||
volatile int _percent;
|
||||
volatile boolean _done;
|
||||
|
||||
|
||||
public ProgressReporter() {
|
||||
_percent = 0;
|
||||
_done = false;
|
||||
|
||||
|
||||
setDaemon(true);
|
||||
start();
|
||||
}
|
||||
|
||||
|
||||
public void reportProgress(int percent) {
|
||||
_percent = percent;
|
||||
}
|
||||
|
||||
|
||||
public void close() {
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("close ProgressReporter, interrupt reporter runner to let it quit");
|
||||
|
||||
|
||||
_done = true;
|
||||
interrupt();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while(!_done) {
|
||||
|
|
@ -149,7 +150,7 @@ public class HttpNfcLeaseMO extends BaseMO {
|
|||
s_logger.warn("Unexpected exception ", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("ProgressReporter stopped");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,16 +69,16 @@ public class HypervisorHostHelper {
|
|||
private static final Logger s_logger = Logger.getLogger(HypervisorHostHelper.class);
|
||||
private static final int DEFAULT_LOCK_TIMEOUT_SECONDS = 600;
|
||||
private static final String s_policyNamePrefix = "cloud.policy.";
|
||||
|
||||
|
||||
// make vmware-base loosely coupled with cloud-specific stuff, duplicate VLAN.UNTAGGED constant here
|
||||
private static final String UNTAGGED_VLAN_NAME = "untagged";
|
||||
|
||||
public static VirtualMachineMO findVmFromObjectContent(VmwareContext context,
|
||||
|
||||
public static VirtualMachineMO findVmFromObjectContent(VmwareContext context,
|
||||
ObjectContent[] ocs, String name) {
|
||||
|
||||
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DynamicProperty prop = oc.getPropSet(0);
|
||||
DynamicProperty prop = oc.getPropSet().get(0);
|
||||
assert(prop != null);
|
||||
if(prop.getVal().toString().equals(name))
|
||||
return new VirtualMachineMO(context, oc.getObj());
|
||||
|
|
@ -86,20 +86,20 @@ public class HypervisorHostHelper {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static ManagedObjectReference findDatastoreWithBackwardsCompatibility(VmwareHypervisorHost hyperHost, String uuidName) throws Exception {
|
||||
ManagedObjectReference morDs = hyperHost.findDatastore(uuidName.replace("-", ""));
|
||||
if(morDs == null)
|
||||
morDs = hyperHost.findDatastore(uuidName);
|
||||
|
||||
|
||||
return morDs;
|
||||
}
|
||||
|
||||
|
||||
public static DatastoreMO getHyperHostDatastoreMO(VmwareHypervisorHost hyperHost, String datastoreName) throws Exception {
|
||||
ObjectContent[] ocs = hyperHost.getDatastorePropertiesOnHyperHost(new String[] { "name"} );
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
for(ObjectContent oc : ocs) {
|
||||
DynamicProperty[] objProps = oc.getPropSet();
|
||||
List<DynamicProperty> objProps = oc.getPropSet();
|
||||
if(objProps != null) {
|
||||
for(DynamicProperty objProp : objProps) {
|
||||
if(objProp.getVal().toString().equals(datastoreName))
|
||||
|
|
@ -110,7 +110,7 @@ public class HypervisorHostHelper {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static String getPublicNetworkNamePrefix(String vlanId) {
|
||||
if (UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
|
||||
return "cloud.public.untagged";
|
||||
|
|
@ -118,24 +118,24 @@ public class HypervisorHostHelper {
|
|||
return "cloud.public." + vlanId;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String composeCloudNetworkName(String prefix, String vlanId, Integer networkRateMbps, String vSwitchName) {
|
||||
StringBuffer sb = new StringBuffer(prefix);
|
||||
if(vlanId == null || UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId))
|
||||
sb.append(".untagged");
|
||||
else
|
||||
sb.append(".").append(vlanId);
|
||||
|
||||
|
||||
if(networkRateMbps != null && networkRateMbps.intValue() > 0)
|
||||
sb.append(".").append(String.valueOf(networkRateMbps));
|
||||
else
|
||||
sb.append(".0");
|
||||
sb.append(".").append(VersioningContants.PORTGROUP_NAMING_VERSION);
|
||||
sb.append("-").append(vSwitchName);
|
||||
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
public static Map<String, String> getValidatedVsmCredentials(VmwareContext context) throws Exception {
|
||||
Map<String, String> vsmCredentials = context.getStockObject("vsmcredentials");
|
||||
String msg;
|
||||
|
|
@ -415,7 +415,7 @@ public class HypervisorHostHelper {
|
|||
boolean createGCTag = false;
|
||||
String networkName;
|
||||
Integer vid = null;
|
||||
|
||||
|
||||
if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
|
||||
createGCTag = true;
|
||||
vid = Integer.parseInt(vlanId);
|
||||
|
|
@ -466,8 +466,8 @@ public class HypervisorHostHelper {
|
|||
bWaitPortGroupReady = true;
|
||||
updatePortProfile(context, ethPortProfileName, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
|
||||
}
|
||||
// Wait for dvPortGroup on vCenter
|
||||
if(bWaitPortGroupReady)
|
||||
// Wait for dvPortGroup on vCenter
|
||||
if(bWaitPortGroupReady)
|
||||
morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs);
|
||||
else
|
||||
morNetwork = dataCenterMo.getDvPortGroupMor(networkName);
|
||||
|
|
@ -476,7 +476,7 @@ public class HypervisorHostHelper {
|
|||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
if(createGCTag) {
|
||||
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
|
||||
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true");
|
||||
|
|
@ -511,39 +511,39 @@ public class HypervisorHostHelper {
|
|||
currentTrafficShapingPolicy = spec.getDefaultPortConfig().getInShapingPolicy();
|
||||
// TODO(sateesh): Extract and compare vendor specific configuration specification as well.
|
||||
// DistributedVirtualSwitchKeyedOpaqueBlob[] vendorSpecificConfig = spec.getVendorSpecificConfig();
|
||||
|
||||
|
||||
assert(currentTrafficShapingPolicy != null);
|
||||
|
||||
|
||||
LongPolicy averageBandwidth = currentTrafficShapingPolicy.getAverageBandwidth();
|
||||
LongPolicy burstSize = currentTrafficShapingPolicy.getBurstSize();
|
||||
LongPolicy peakBandwidth = currentTrafficShapingPolicy.getPeakBandwidth();
|
||||
BoolPolicy isEnabled = currentTrafficShapingPolicy.getEnabled();
|
||||
|
||||
if(!isEnabled.getValue())
|
||||
|
||||
if(!isEnabled.isValue())
|
||||
return false;
|
||||
|
||||
|
||||
if(averageBandwidth != null && !averageBandwidth.equals(shapingPolicy.getAverageBandwidth())) {
|
||||
if(s_logger.isInfoEnabled()) {
|
||||
s_logger.info("Average bandwidth setting in shaping policy doesn't match with existing setting.");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} else if(burstSize != null && !burstSize.equals(shapingPolicy.getBurstSize())) {
|
||||
if(s_logger.isInfoEnabled()) {
|
||||
s_logger.info("Burst size setting in shaping policy doesn't match with existing setting.");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} else if(peakBandwidth != null && !peakBandwidth.equals(shapingPolicy.getPeakBandwidth())) {
|
||||
if(s_logger.isInfoEnabled()) {
|
||||
s_logger.info("Peak bandwidth setting in shaping policy doesn't match with existing setting.");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Pair<ManagedObjectReference, String> prepareNetwork(String vSwitchName, String namePrefix,
|
||||
HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps,
|
||||
HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps,
|
||||
long timeOutMs, boolean syncPeerHosts) throws Exception {
|
||||
|
||||
HostVirtualSwitch vSwitch;
|
||||
|
|
@ -558,12 +558,12 @@ public class HypervisorHostHelper {
|
|||
boolean createGCTag = false;
|
||||
String networkName;
|
||||
Integer vid = null;
|
||||
|
||||
|
||||
if(vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
|
||||
createGCTag = true;
|
||||
vid = Integer.parseInt(vlanId);
|
||||
}
|
||||
|
||||
|
||||
networkName = composeCloudNetworkName(namePrefix, vlanId, networkRateMbps, vSwitchName);
|
||||
HostNetworkSecurityPolicy secPolicy = null;
|
||||
if (namePrefix.equalsIgnoreCase("cloud.private")) {
|
||||
|
|
@ -577,11 +577,11 @@ public class HypervisorHostHelper {
|
|||
shapingPolicy = new HostNetworkTrafficShapingPolicy();
|
||||
shapingPolicy.setEnabled(true);
|
||||
shapingPolicy.setAverageBandwidth((long)networkRateMbps.intValue()*1024L*1024L);
|
||||
|
||||
//
|
||||
|
||||
//
|
||||
// TODO : people may have different opinion on how to set the following
|
||||
//
|
||||
|
||||
|
||||
// give 50% premium to peek
|
||||
shapingPolicy.setPeakBandwidth((long)(shapingPolicy.getAverageBandwidth()*1.5));
|
||||
|
||||
|
|
@ -602,7 +602,7 @@ public class HypervisorHostHelper {
|
|||
}
|
||||
|
||||
ManagedObjectReference morNetwork;
|
||||
if(bWaitPortGroupReady)
|
||||
if(bWaitPortGroupReady)
|
||||
morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);
|
||||
else
|
||||
morNetwork = hostMo.getNetworkMor(networkName);
|
||||
|
|
@ -611,24 +611,24 @@ public class HypervisorHostHelper {
|
|||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
if(createGCTag) {
|
||||
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
|
||||
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true");
|
||||
}
|
||||
|
||||
|
||||
if(syncPeerHosts) {
|
||||
ManagedObjectReference morParent = hostMo.getParentMor();
|
||||
if(morParent != null && morParent.getType().equals("ClusterComputeResource")) {
|
||||
// to be conservative, lock cluster
|
||||
GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.get_value());
|
||||
GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.getValue());
|
||||
try {
|
||||
if(lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {
|
||||
try {
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getServiceUtil().getDynamicProperty(morParent, "host");
|
||||
ManagedObjectReference[] hosts = (ManagedObjectReference[])hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host");
|
||||
if(hosts != null) {
|
||||
for(ManagedObjectReference otherHost: hosts) {
|
||||
if(!otherHost.get_value().equals(hostMo.getMor().get_value())) {
|
||||
if(!otherHost.getValue().equals(hostMo.getMor().getValue())) {
|
||||
HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);
|
||||
try {
|
||||
if(s_logger.isDebugEnabled())
|
||||
|
|
@ -655,7 +655,7 @@ public class HypervisorHostHelper {
|
|||
s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName);
|
||||
return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
|
||||
}
|
||||
|
||||
|
||||
private static boolean isSpecMatch(HostPortGroupSpec spec, Integer vlanId, HostNetworkTrafficShapingPolicy shapingPolicy) {
|
||||
// check VLAN configuration
|
||||
if(vlanId != null) {
|
||||
|
|
@ -670,17 +670,17 @@ public class HypervisorHostHelper {
|
|||
HostNetworkTrafficShapingPolicy policyInSpec = null;
|
||||
if(spec.getPolicy() != null)
|
||||
policyInSpec = spec.getPolicy().getShapingPolicy();
|
||||
|
||||
|
||||
if(policyInSpec != null && shapingPolicy == null || policyInSpec == null && shapingPolicy != null)
|
||||
return false;
|
||||
|
||||
|
||||
if(policyInSpec == null && shapingPolicy == null)
|
||||
return true;
|
||||
|
||||
|
||||
// so far policyInSpec and shapingPolicy should both not be null
|
||||
if(policyInSpec.getEnabled() == null || !policyInSpec.getEnabled().booleanValue())
|
||||
if(policyInSpec.isEnabled() == null || !policyInSpec.isEnabled().booleanValue())
|
||||
return false;
|
||||
|
||||
|
||||
if(policyInSpec.getAverageBandwidth() == null || policyInSpec.getAverageBandwidth().longValue() != shapingPolicy.getAverageBandwidth().longValue())
|
||||
return false;
|
||||
|
||||
|
|
@ -689,10 +689,10 @@ public class HypervisorHostHelper {
|
|||
|
||||
if(policyInSpec.getBurstSize() == null || policyInSpec.getBurstSize().longValue() != shapingPolicy.getBurstSize().longValue())
|
||||
return false;
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static ManagedObjectReference waitForNetworkReady(HostMO hostMo,
|
||||
String networkName, long timeOutMs) throws Exception {
|
||||
|
||||
|
|
@ -713,14 +713,14 @@ public class HypervisorHostHelper {
|
|||
|
||||
return morNetwork;
|
||||
}
|
||||
|
||||
public static boolean createBlankVm(VmwareHypervisorHost host, String vmName,
|
||||
int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier,
|
||||
|
||||
public static boolean createBlankVm(VmwareHypervisorHost host, String vmName,
|
||||
int cpuCount, int cpuSpeedMHz, int cpuReservedMHz, boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier,
|
||||
ManagedObjectReference morDs, boolean snapshotDirToParent) throws Exception {
|
||||
|
||||
|
||||
if(s_logger.isInfoEnabled())
|
||||
s_logger.info("Create blank VM. cpuCount: " + cpuCount + ", cpuSpeed(MHz): " + cpuSpeedMHz + ", mem(Mb): " + memoryMB);
|
||||
|
||||
|
||||
// VM config basics
|
||||
VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();
|
||||
vmConfig.setName(vmName);
|
||||
|
|
@ -728,62 +728,63 @@ public class HypervisorHostHelper {
|
|||
|
||||
// Scsi controller
|
||||
VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
|
||||
scsiController.setSharedBus(VirtualSCSISharing.noSharing);
|
||||
scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
|
||||
scsiController.setBusNumber(0);
|
||||
scsiController.setKey(1);
|
||||
VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
|
||||
scsiControllerSpec.setDevice(scsiController);
|
||||
scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
|
||||
scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
|
||||
|
||||
VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
|
||||
DatastoreMO dsMo = new DatastoreMO(host.getContext(), morDs);
|
||||
fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
|
||||
vmConfig.setFiles(fileInfo);
|
||||
|
||||
|
||||
VirtualMachineVideoCard videoCard = new VirtualMachineVideoCard();
|
||||
videoCard.setControllerKey(100);
|
||||
videoCard.setUseAutoDetect(true);
|
||||
|
||||
|
||||
VirtualDeviceConfigSpec videoDeviceSpec = new VirtualDeviceConfigSpec();
|
||||
videoDeviceSpec.setDevice(videoCard);
|
||||
videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
|
||||
|
||||
vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec, videoDeviceSpec });
|
||||
videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
|
||||
|
||||
vmConfig.getDeviceChange().add(scsiControllerSpec);
|
||||
vmConfig.getDeviceChange().add(videoDeviceSpec);
|
||||
if(host.createVm(vmConfig)) {
|
||||
VirtualMachineMO vmMo = host.findVmOnHyperHost(vmName);
|
||||
assert(vmMo != null);
|
||||
|
||||
|
||||
int ideControllerKey = -1;
|
||||
while(ideControllerKey < 0) {
|
||||
ideControllerKey = vmMo.tryGetIDEDeviceControllerKey();
|
||||
if(ideControllerKey >= 0)
|
||||
break;
|
||||
|
||||
|
||||
s_logger.info("Waiting for IDE controller be ready in VM: " + vmName);
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
|
||||
|
||||
if(snapshotDirToParent) {
|
||||
String snapshotDir = String.format("/vmfs/volumes/%s/", dsMo.getName());
|
||||
|
||||
|
||||
s_logger.info("Switch snapshot working directory to " + snapshotDir + " for " + vmName);
|
||||
vmMo.setSnapshotDirectory(snapshotDir);
|
||||
|
||||
|
||||
// Don't have a good way to test if the VM is really ready for use through normal API after configuration file manipulation,
|
||||
// delay 3 seconds
|
||||
Thread.sleep(3000);
|
||||
}
|
||||
|
||||
|
||||
s_logger.info("Blank VM: " + vmName + " is ready for use");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public static String resolveHostNameInUrl(DatacenterMO dcMo, String url) {
|
||||
|
||||
|
||||
s_logger.info("Resolving host name in url through vCenter, url: " + url);
|
||||
|
||||
|
||||
URI uri;
|
||||
try {
|
||||
uri = new URI(url);
|
||||
|
|
@ -791,13 +792,13 @@ public class HypervisorHostHelper {
|
|||
s_logger.warn("URISyntaxException on url " + url);
|
||||
return url;
|
||||
}
|
||||
|
||||
|
||||
String host = uri.getHost();
|
||||
if(NetUtils.isValidIp(host)) {
|
||||
s_logger.info("host name in url is already in IP address, url: " + url);
|
||||
return url;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
ManagedObjectReference morHost = dcMo.findHost(host);
|
||||
if(morHost != null) {
|
||||
|
|
@ -807,18 +808,18 @@ public class HypervisorHostHelper {
|
|||
managementPortGroupName = (String)dcMo.getContext().getStockObject("manageportgroup");
|
||||
else
|
||||
managementPortGroupName = (String)dcMo.getContext().getStockObject("serviceconsole");
|
||||
|
||||
|
||||
VmwareHypervisorHostNetworkSummary summary = hostMo.getHyperHostNetworkSummary(managementPortGroupName);
|
||||
if(summary == null) {
|
||||
s_logger.warn("Unable to resolve host name in url through vSphere, url: " + url);
|
||||
return url;
|
||||
}
|
||||
|
||||
|
||||
String hostIp = summary.getHostIp();
|
||||
|
||||
|
||||
try {
|
||||
URI resolvedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostIp, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
|
||||
|
||||
|
||||
s_logger.info("url " + url + " is resolved to " + resolvedUri.toString() + " through vCenter");
|
||||
return resolvedUri.toString();
|
||||
} catch (URISyntaxException e) {
|
||||
|
|
@ -829,77 +830,77 @@ public class HypervisorHostHelper {
|
|||
} catch(Exception e) {
|
||||
s_logger.warn("Unexpected exception ", e);
|
||||
}
|
||||
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption,
|
||||
|
||||
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption,
|
||||
ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {
|
||||
|
||||
|
||||
assert(morRp != null);
|
||||
|
||||
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
|
||||
importSpecParams.setHostSystem(morHost);
|
||||
importSpecParams.setLocale("US");
|
||||
importSpecParams.setEntityName(vmName);
|
||||
|
||||
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
|
||||
importSpecParams.setHostSystem(morHost);
|
||||
importSpecParams.setLocale("US");
|
||||
importSpecParams.setEntityName(vmName);
|
||||
importSpecParams.setDeploymentOption("");
|
||||
importSpecParams.setDiskProvisioning(diskOption); // diskOption: thin, thick, etc
|
||||
importSpecParams.setPropertyMapping(null);
|
||||
|
||||
//importSpecParams.setPropertyMapping(null);
|
||||
|
||||
String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath);
|
||||
VmwareContext context = host.getContext();
|
||||
OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(
|
||||
context.getServiceContent().getOvfManager(), ovfDescriptor, morRp,
|
||||
context.getServiceContent().getOvfManager(), ovfDescriptor, morRp,
|
||||
dsMo.getMor(), importSpecParams);
|
||||
|
||||
|
||||
if(ovfImportResult == null) {
|
||||
String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
|
||||
String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
|
||||
+ vmName + ", diskOption: " + diskOption;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
|
||||
|
||||
DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
|
||||
ManagedObjectReference morLease = context.getService().importVApp(morRp,
|
||||
ManagedObjectReference morLease = context.getService().importVApp(morRp,
|
||||
ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
|
||||
if(morLease == null) {
|
||||
String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
|
||||
String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: "
|
||||
+ vmName + ", diskOption: " + diskOption;
|
||||
s_logger.error(msg);
|
||||
throw new Exception(msg);
|
||||
}
|
||||
final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
|
||||
HttpNfcLeaseState state = leaseMo.waitState(
|
||||
new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
|
||||
new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
|
||||
try {
|
||||
if(state == HttpNfcLeaseState.ready) {
|
||||
if(state == HttpNfcLeaseState.READY) {
|
||||
final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
|
||||
File ovfFile = new File(ovfFilePath);
|
||||
|
||||
File ovfFile = new File(ovfFilePath);
|
||||
|
||||
HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
|
||||
HttpNfcLeaseDeviceUrl[] deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
|
||||
List<HttpNfcLeaseDeviceUrl> 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<Long> () {
|
||||
public void action(Long param) {
|
||||
progressReporter.reportProgress((int)(param * 100 / totalBytes));
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
bytesAlreadyWritten += ovfFileItem.getSize();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
progressReporter.close();
|
||||
|
|
|
|||
|
|
@ -23,17 +23,17 @@ public class NetworkMO extends BaseMO {
|
|||
public NetworkMO(VmwareContext context, ManagedObjectReference morCluster) {
|
||||
super(context, morCluster);
|
||||
}
|
||||
|
||||
|
||||
public NetworkMO(VmwareContext context, String morType, String morValue) {
|
||||
super(context, morType, morValue);
|
||||
}
|
||||
|
||||
|
||||
public void destroyNetwork() throws Exception {
|
||||
_context.getService().destroyNetwork(_mor);
|
||||
_context.getService().destroyNetwork(_mor);
|
||||
}
|
||||
|
||||
|
||||
public ManagedObjectReference[] getVMsOnNetwork() throws Exception {
|
||||
ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getServiceUtil().getDynamicProperty(_mor, "vm");
|
||||
ManagedObjectReference[] vms = (ManagedObjectReference[])_context.getVimClient().getDynamicProperty(_mor, "vm");
|
||||
return vms;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<PerfMetricId> 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<PerfCounterInfo> queryPerfCounter(int[] counterId) throws Exception {
|
||||
List<Integer> counterArr = new ArrayList<Integer>();
|
||||
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<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<PerfEntityMetricBase> queryPerf(PerfQuerySpec[] specs) throws Exception {
|
||||
return _context.getService().queryPerf(_mor, Arrays.asList(specs));
|
||||
}
|
||||
|
||||
public void removePerfInterval(int samplePeriod) throws Exception {
|
||||
_context.getService().removePerfInterval(_mor, samplePeriod);
|
||||
}
|
||||
|
||||
|
||||
public void updatePerfInterval(PerfInterval interval) throws Exception {
|
||||
_context.getService().updatePerfInterval(_mor, interval);
|
||||
}
|
||||
|
||||
|
||||
public PerfCounterInfo[] getCounterInfo() throws Exception {
|
||||
return (PerfCounterInfo[])_context.getServiceUtil().getDynamicProperty(_mor, "perfCounter");
|
||||
return (PerfCounterInfo[])_context.getVimClient().getDynamicProperty(_mor, "perfCounter");
|
||||
}
|
||||
|
||||
|
||||
public PerfInterval[] getIntervalInfo() throws Exception {
|
||||
return (PerfInterval[])_context.getServiceUtil().getDynamicProperty(_mor, "historicalInterval");
|
||||
return (PerfInterval[])_context.getVimClient().getDynamicProperty(_mor, "historicalInterval");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,509 @@
|
|||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
package com.cloud.hypervisor.vmware.util;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.xml.ws.BindingProvider;
|
||||
|
||||
import com.vmware.vim25.DynamicProperty;
|
||||
import com.vmware.vim25.InvalidCollectorVersionFaultMsg;
|
||||
import com.vmware.vim25.InvalidPropertyFaultMsg;
|
||||
import com.vmware.vim25.LocalizedMethodFault;
|
||||
import com.vmware.vim25.ManagedObjectReference;
|
||||
import com.vmware.vim25.ObjectSpec;
|
||||
import com.vmware.vim25.ObjectUpdate;
|
||||
import com.vmware.vim25.ObjectUpdateKind;
|
||||
import com.vmware.vim25.PropertyChange;
|
||||
import com.vmware.vim25.PropertyChangeOp;
|
||||
import com.vmware.vim25.PropertyFilterSpec;
|
||||
import com.vmware.vim25.PropertyFilterUpdate;
|
||||
import com.vmware.vim25.PropertySpec;
|
||||
import com.vmware.vim25.RuntimeFaultFaultMsg;
|
||||
import com.vmware.vim25.SelectionSpec;
|
||||
import com.vmware.vim25.ServiceContent;
|
||||
import com.vmware.vim25.TaskInfoState;
|
||||
import com.vmware.vim25.TraversalSpec;
|
||||
import com.vmware.vim25.UpdateSet;
|
||||
import com.vmware.vim25.VimPortType;
|
||||
import com.vmware.vim25.VimService;
|
||||
import com.vmware.vim25.ObjectContent;
|
||||
|
||||
/**
|
||||
* A wrapper class to handle Vmware vsphere connection and disconnection.
|
||||
*
|
||||
* @author minc
|
||||
*
|
||||
*/
|
||||
public class VmwareClient {
|
||||
|
||||
private ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
|
||||
private ManagedObjectReference propCollectorRef;
|
||||
private ManagedObjectReference rootRef;
|
||||
private VimService vimService;
|
||||
private VimPortType vimPort;
|
||||
private ServiceContent serviceContent;
|
||||
private final String SVC_INST_NAME = "ServiceInstance";
|
||||
|
||||
private boolean isConnected = false;
|
||||
|
||||
public VmwareClient(String name) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Establishes session with the virtual center server.
|
||||
*
|
||||
* @throws Exception
|
||||
* the exception
|
||||
*/
|
||||
public void connect(String url, String userName, String password) throws Exception {
|
||||
|
||||
HostnameVerifier hv = new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String urlHostName, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv);
|
||||
|
||||
SVC_INST_REF.setType(SVC_INST_NAME);
|
||||
SVC_INST_REF.setValue(SVC_INST_NAME);
|
||||
|
||||
vimService = new VimService();
|
||||
vimPort = vimService.getVimPort();
|
||||
Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
|
||||
|
||||
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
|
||||
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
|
||||
|
||||
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
|
||||
vimPort.login(serviceContent.getSessionManager(), userName, password, null);
|
||||
isConnected = true;
|
||||
|
||||
propCollectorRef = serviceContent.getPropertyCollector();
|
||||
rootRef = serviceContent.getRootFolder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects the user session.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public void disconnect() throws Exception {
|
||||
if (isConnected) {
|
||||
vimPort.logout(serviceContent.getSessionManager());
|
||||
}
|
||||
isConnected = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Service instance
|
||||
*/
|
||||
public VimPortType getService() {
|
||||
return vimPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Service instance content
|
||||
*/
|
||||
public ServiceContent getServiceContent() {
|
||||
return serviceContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Service property collector
|
||||
*/
|
||||
public ManagedObjectReference getPropCol() {
|
||||
return propCollectorRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Root folder
|
||||
*/
|
||||
public ManagedObjectReference getRootFolder() {
|
||||
return rootRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the property value of a managed object.
|
||||
*
|
||||
* @param mor
|
||||
* managed object reference
|
||||
* @param propertyName
|
||||
* property name.
|
||||
* @return property value.
|
||||
* @throws Exception
|
||||
* in case of error.
|
||||
*/
|
||||
public Object getDynamicProperty(ManagedObjectReference mor, String propertyName) throws Exception {
|
||||
List<String> props = new ArrayList<String>();
|
||||
props.add(propertyName);
|
||||
List<ObjectContent> objContent = this.getObjectProperties(mor, props);
|
||||
|
||||
Object propertyValue = null;
|
||||
if (objContent != null && objContent.size() > 0) {
|
||||
List<DynamicProperty> dynamicProperty = objContent.get(0).getPropSet();
|
||||
if (dynamicProperty != null && dynamicProperty.size() > 0) {
|
||||
DynamicProperty dp = dynamicProperty.get(0);
|
||||
propertyValue = dp.getVal();
|
||||
/*
|
||||
* If object is ArrayOfXXX object, then get the XXX[] by
|
||||
* invoking getXXX() on the object.
|
||||
* For Ex:
|
||||
* ArrayOfManagedObjectReference.getManagedObjectReference()
|
||||
* returns ManagedObjectReference[] array.
|
||||
*/
|
||||
Class dpCls = propertyValue.getClass();
|
||||
String dynamicPropertyName = dpCls.getName();
|
||||
if (dynamicPropertyName.startsWith("ArrayOf")) {
|
||||
String methodName = "get"
|
||||
+ dynamicPropertyName
|
||||
.substring(dynamicPropertyName.indexOf("ArrayOf") + "ArrayOf".length(), dynamicPropertyName.length());
|
||||
|
||||
Method getMorMethod = dpCls.getDeclaredMethod(methodName, null);
|
||||
propertyValue = getMorMethod.invoke(propertyValue, (Object[]) null);
|
||||
}
|
||||
}
|
||||
}
|
||||
return propertyValue;
|
||||
}
|
||||
|
||||
private List<ObjectContent> getObjectProperties(ManagedObjectReference mObj, List<String> props) throws Exception {
|
||||
PropertySpec pSpec = new PropertySpec();
|
||||
pSpec.setAll(false);
|
||||
pSpec.setType(mObj.getType());
|
||||
pSpec.getPathSet().addAll(props);
|
||||
|
||||
ObjectSpec oSpec = new ObjectSpec();
|
||||
oSpec.setObj(mObj);
|
||||
oSpec.setSkip(false);
|
||||
PropertyFilterSpec spec = new PropertyFilterSpec();
|
||||
spec.getPropSet().add(pSpec);
|
||||
spec.getObjectSet().add(oSpec);
|
||||
List<PropertyFilterSpec> specArr = new ArrayList<PropertyFilterSpec>();
|
||||
specArr.add(spec);
|
||||
|
||||
return vimPort.retrieveProperties(propCollectorRef, specArr);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method returns a boolean value specifying whether the Task is
|
||||
* succeeded or failed.
|
||||
*
|
||||
* @param task
|
||||
* ManagedObjectReference representing the Task.
|
||||
*
|
||||
* @return boolean value representing the Task result.
|
||||
* @throws InvalidCollectorVersionFaultMsg
|
||||
* @throws RuntimeFaultFaultMsg
|
||||
* @throws InvalidPropertyFaultMsg
|
||||
*/
|
||||
public boolean waitForTask(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg {
|
||||
|
||||
boolean retVal = false;
|
||||
|
||||
// info has a property - state for state of the task
|
||||
Object[] result = waitForValues(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] {
|
||||
TaskInfoState.SUCCESS, TaskInfoState.ERROR } });
|
||||
|
||||
if (result[0].equals(TaskInfoState.SUCCESS)) {
|
||||
retVal = true;
|
||||
}
|
||||
if (result[1] instanceof LocalizedMethodFault) {
|
||||
throw new RuntimeException(((LocalizedMethodFault) result[1]).getLocalizedMessage());
|
||||
}
|
||||
return retVal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Updates for a single object. waits till expected values of
|
||||
* properties to check are reached Destroys the ObjectFilter when done.
|
||||
*
|
||||
* @param objmor
|
||||
* MOR of the Object to wait for</param>
|
||||
* @param filterProps
|
||||
* Properties list to filter
|
||||
* @param endWaitProps
|
||||
* Properties list to check for expected values these be
|
||||
* properties of a property in the filter properties list
|
||||
* @param expectedVals
|
||||
* values for properties to end the wait
|
||||
* @return true indicating expected values were met, and false otherwise
|
||||
* @throws RuntimeFaultFaultMsg
|
||||
* @throws InvalidPropertyFaultMsg
|
||||
* @throws InvalidCollectorVersionFaultMsg
|
||||
*/
|
||||
private Object[] waitForValues(ManagedObjectReference objmor, String[] filterProps, String[] endWaitProps, Object[][] expectedVals)
|
||||
throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg {
|
||||
// version string is initially null
|
||||
String version = "";
|
||||
Object[] endVals = new Object[endWaitProps.length];
|
||||
Object[] filterVals = new Object[filterProps.length];
|
||||
|
||||
PropertyFilterSpec spec = new PropertyFilterSpec();
|
||||
ObjectSpec oSpec = new ObjectSpec();
|
||||
oSpec.setObj(objmor);
|
||||
oSpec.setSkip(Boolean.FALSE);
|
||||
spec.getObjectSet().add(oSpec);
|
||||
|
||||
PropertySpec pSpec = new PropertySpec();
|
||||
pSpec.getPathSet().addAll(Arrays.asList(filterProps));
|
||||
pSpec.setType(objmor.getType());
|
||||
spec.getPropSet().add(pSpec);
|
||||
|
||||
ManagedObjectReference filterSpecRef = vimPort.createFilter(propCollectorRef, spec, true);
|
||||
|
||||
boolean reached = false;
|
||||
|
||||
UpdateSet updateset = null;
|
||||
List<PropertyFilterUpdate> filtupary = null;
|
||||
List<ObjectUpdate> objupary = null;
|
||||
List<PropertyChange> propchgary = null;
|
||||
while (!reached) {
|
||||
updateset = vimPort.waitForUpdates(propCollectorRef, version);
|
||||
if (updateset == null || updateset.getFilterSet() == null) {
|
||||
continue;
|
||||
}
|
||||
version = updateset.getVersion();
|
||||
|
||||
// Make this code more general purpose when PropCol changes later.
|
||||
filtupary = updateset.getFilterSet();
|
||||
|
||||
for (PropertyFilterUpdate filtup : filtupary) {
|
||||
objupary = filtup.getObjectSet();
|
||||
for (ObjectUpdate objup : objupary) {
|
||||
// TODO: Handle all "kind"s of updates.
|
||||
if (objup.getKind() == ObjectUpdateKind.MODIFY || objup.getKind() == ObjectUpdateKind.ENTER
|
||||
|| objup.getKind() == ObjectUpdateKind.LEAVE) {
|
||||
propchgary = objup.getChangeSet();
|
||||
for (PropertyChange propchg : propchgary) {
|
||||
updateValues(endWaitProps, endVals, propchg);
|
||||
updateValues(filterProps, filterVals, propchg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Object expctdval = null;
|
||||
// Check if the expected values have been reached and exit the loop
|
||||
// if done.
|
||||
// Also exit the WaitForUpdates loop if this is the case.
|
||||
for (int chgi = 0; chgi < endVals.length && !reached; chgi++) {
|
||||
for (int vali = 0; vali < expectedVals[chgi].length && !reached; vali++) {
|
||||
expctdval = expectedVals[chgi][vali];
|
||||
|
||||
reached = expctdval.equals(endVals[chgi]) || reached;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Destroy the filter when we are done.
|
||||
vimPort.destroyPropertyFilter(filterSpecRef);
|
||||
return filterVals;
|
||||
}
|
||||
|
||||
private void updateValues(String[] props, Object[] vals, PropertyChange propchg) {
|
||||
for (int findi = 0; findi < props.length; findi++) {
|
||||
if (propchg.getName().lastIndexOf(props[findi]) >= 0) {
|
||||
if (propchg.getOp() == PropertyChangeOp.REMOVE) {
|
||||
vals[findi] = "";
|
||||
} else {
|
||||
vals[findi] = propchg.getVal();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SelectionSpec getSelectionSpec(String name) {
|
||||
SelectionSpec genericSpec = new SelectionSpec();
|
||||
genericSpec.setName(name);
|
||||
return genericSpec;
|
||||
}
|
||||
|
||||
/*
|
||||
* @return An array of SelectionSpec covering VM, Host, Resource pool,
|
||||
* Cluster Compute Resource and Datastore.
|
||||
*/
|
||||
private List<SelectionSpec> buildFullTraversal() {
|
||||
// Terminal traversal specs
|
||||
|
||||
// RP -> VM
|
||||
TraversalSpec rpToVm = new TraversalSpec();
|
||||
rpToVm.setName("rpToVm");
|
||||
rpToVm.setType("ResourcePool");
|
||||
rpToVm.setPath("vm");
|
||||
rpToVm.setSkip(Boolean.FALSE);
|
||||
|
||||
// vApp -> VM
|
||||
TraversalSpec vAppToVM = new TraversalSpec();
|
||||
vAppToVM.setName("vAppToVM");
|
||||
vAppToVM.setType("VirtualApp");
|
||||
vAppToVM.setPath("vm");
|
||||
|
||||
// HostSystem -> VM
|
||||
TraversalSpec hToVm = new TraversalSpec();
|
||||
hToVm.setType("HostSystem");
|
||||
hToVm.setPath("vm");
|
||||
hToVm.setName("hToVm");
|
||||
hToVm.getSelectSet().add(getSelectionSpec("VisitFolders"));
|
||||
hToVm.setSkip(Boolean.FALSE);
|
||||
|
||||
// DC -> DS
|
||||
TraversalSpec dcToDs = new TraversalSpec();
|
||||
dcToDs.setType("Datacenter");
|
||||
dcToDs.setPath("datastore");
|
||||
dcToDs.setName("dcToDs");
|
||||
dcToDs.setSkip(Boolean.FALSE);
|
||||
|
||||
// Recurse through all ResourcePools
|
||||
TraversalSpec rpToRp = new TraversalSpec();
|
||||
rpToRp.setType("ResourcePool");
|
||||
rpToRp.setPath("resourcePool");
|
||||
rpToRp.setSkip(Boolean.FALSE);
|
||||
rpToRp.setName("rpToRp");
|
||||
rpToRp.getSelectSet().add(getSelectionSpec("rpToRp"));
|
||||
|
||||
TraversalSpec crToRp = new TraversalSpec();
|
||||
crToRp.setType("ComputeResource");
|
||||
crToRp.setPath("resourcePool");
|
||||
crToRp.setSkip(Boolean.FALSE);
|
||||
crToRp.setName("crToRp");
|
||||
crToRp.getSelectSet().add(getSelectionSpec("rpToRp"));
|
||||
|
||||
TraversalSpec crToH = new TraversalSpec();
|
||||
crToH.setSkip(Boolean.FALSE);
|
||||
crToH.setType("ComputeResource");
|
||||
crToH.setPath("host");
|
||||
crToH.setName("crToH");
|
||||
|
||||
TraversalSpec dcToHf = new TraversalSpec();
|
||||
dcToHf.setSkip(Boolean.FALSE);
|
||||
dcToHf.setType("Datacenter");
|
||||
dcToHf.setPath("hostFolder");
|
||||
dcToHf.setName("dcToHf");
|
||||
dcToHf.getSelectSet().add(getSelectionSpec("VisitFolders"));
|
||||
|
||||
TraversalSpec vAppToRp = new TraversalSpec();
|
||||
vAppToRp.setName("vAppToRp");
|
||||
vAppToRp.setType("VirtualApp");
|
||||
vAppToRp.setPath("resourcePool");
|
||||
vAppToRp.getSelectSet().add(getSelectionSpec("rpToRp"));
|
||||
|
||||
TraversalSpec dcToVmf = new TraversalSpec();
|
||||
dcToVmf.setType("Datacenter");
|
||||
dcToVmf.setSkip(Boolean.FALSE);
|
||||
dcToVmf.setPath("vmFolder");
|
||||
dcToVmf.setName("dcToVmf");
|
||||
dcToVmf.getSelectSet().add(getSelectionSpec("VisitFolders"));
|
||||
|
||||
// For Folder -> Folder recursion
|
||||
TraversalSpec visitFolders = new TraversalSpec();
|
||||
visitFolders.setType("Folder");
|
||||
visitFolders.setPath("childEntity");
|
||||
visitFolders.setSkip(Boolean.FALSE);
|
||||
visitFolders.setName("VisitFolders");
|
||||
List<SelectionSpec> sspecarrvf = new ArrayList<SelectionSpec>();
|
||||
sspecarrvf.add(getSelectionSpec("crToRp"));
|
||||
sspecarrvf.add(getSelectionSpec("crToH"));
|
||||
sspecarrvf.add(getSelectionSpec("dcToVmf"));
|
||||
sspecarrvf.add(getSelectionSpec("dcToHf"));
|
||||
sspecarrvf.add(getSelectionSpec("vAppToRp"));
|
||||
sspecarrvf.add(getSelectionSpec("vAppToVM"));
|
||||
sspecarrvf.add(getSelectionSpec("dcToDs"));
|
||||
sspecarrvf.add(getSelectionSpec("hToVm"));
|
||||
sspecarrvf.add(getSelectionSpec("rpToVm"));
|
||||
sspecarrvf.add(getSelectionSpec("VisitFolders"));
|
||||
|
||||
visitFolders.getSelectSet().addAll(sspecarrvf);
|
||||
|
||||
List<SelectionSpec> resultspec = new ArrayList<SelectionSpec>();
|
||||
resultspec.add(visitFolders);
|
||||
resultspec.add(crToRp);
|
||||
resultspec.add(crToH);
|
||||
resultspec.add(dcToVmf);
|
||||
resultspec.add(dcToHf);
|
||||
resultspec.add(vAppToRp);
|
||||
resultspec.add(vAppToVM);
|
||||
resultspec.add(dcToDs);
|
||||
resultspec.add(hToVm);
|
||||
resultspec.add(rpToVm);
|
||||
resultspec.add(rpToRp);
|
||||
|
||||
return resultspec;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the ManagedObjectReference for an item under the
|
||||
* specified root folder that has the type and name specified.
|
||||
*
|
||||
* @param root a root folder if available, or null for default
|
||||
* @param type type of the managed object
|
||||
* @param name name to match
|
||||
*
|
||||
* @return First ManagedObjectReference of the type / name pair found
|
||||
*/
|
||||
public ManagedObjectReference getDecendentMoRef(ManagedObjectReference root, String type, String name) throws Exception {
|
||||
if (name == null || name.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create PropertySpecs
|
||||
PropertySpec pSpec = new PropertySpec();
|
||||
pSpec.setType(type);
|
||||
pSpec.setAll(false);
|
||||
pSpec.getPathSet().add(name);
|
||||
|
||||
ObjectSpec oSpec = new ObjectSpec();
|
||||
oSpec.setObj(root);
|
||||
oSpec.setSkip(false);
|
||||
oSpec.getSelectSet().addAll(buildFullTraversal());
|
||||
|
||||
PropertyFilterSpec spec = new PropertyFilterSpec();
|
||||
spec.getPropSet().add(pSpec);
|
||||
spec.getObjectSet().add(oSpec);
|
||||
List<PropertyFilterSpec> specArr = new ArrayList<PropertyFilterSpec>();
|
||||
specArr.add(spec);
|
||||
|
||||
List<ObjectContent> ocary = vimPort.retrieveProperties(propCollectorRef, specArr);
|
||||
|
||||
if (ocary == null || ocary.size() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (ObjectContent oc : ocary) {
|
||||
ManagedObjectReference mor = oc.getObj();
|
||||
List<DynamicProperty> propary = oc.getPropSet();
|
||||
if (type == null || type.equals(mor.getType())) {
|
||||
if (propary.size() > 0) {
|
||||
String propval = (String) propary.get(0).getVal();
|
||||
if (propval != null && name.equals(propval))
|
||||
return mor;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -26,7 +26,6 @@ import java.io.FileOutputStream;
|
|||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ConnectException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
|
|
@ -44,15 +43,11 @@ import org.apache.log4j.Logger;
|
|||
import com.cloud.hypervisor.vmware.mo.DatacenterMO;
|
||||
import com.cloud.hypervisor.vmware.mo.DatastoreFile;
|
||||
import com.cloud.utils.ActionDelegate;
|
||||
import com.vmware.apputils.version.ExtendedAppUtil;
|
||||
import com.vmware.apputils.vim25.ServiceConnection;
|
||||
import com.vmware.apputils.vim25.ServiceUtil;
|
||||
import com.vmware.vim25.ManagedObjectReference;
|
||||
import com.vmware.vim25.ObjectContent;
|
||||
import com.vmware.vim25.ObjectSpec;
|
||||
import com.vmware.vim25.PropertyFilterSpec;
|
||||
import com.vmware.vim25.PropertySpec;
|
||||
import com.vmware.vim25.SelectionSpec;
|
||||
import com.vmware.vim25.ServiceContent;
|
||||
import com.vmware.vim25.TaskInfo;
|
||||
import com.vmware.vim25.TraversalSpec;
|
||||
|
|
@ -63,30 +58,30 @@ public class VmwareContext {
|
|||
|
||||
private static int MAX_CONNECT_RETRY = 5;
|
||||
private static int CONNECT_RETRY_INTERVAL = 1000;
|
||||
|
||||
private ExtendedAppUtil _appUtil;
|
||||
|
||||
private VmwareClient _vimClient;
|
||||
private String _serverAddress;
|
||||
|
||||
|
||||
private Map<String, Object> _stockMap = new HashMap<String, Object>();
|
||||
private int _CHUNKSIZE = 1*1024*1024; // 1M
|
||||
|
||||
|
||||
static {
|
||||
try {
|
||||
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
|
||||
javax.net.ssl.TrustManager tm = new TrustAllManager();
|
||||
trustAllCerts[0] = tm;
|
||||
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
|
||||
sc.init(null, trustAllCerts, null);
|
||||
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
|
||||
javax.net.ssl.TrustManager tm = new TrustAllManager();
|
||||
trustAllCerts[0] = tm;
|
||||
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
|
||||
sc.init(null, trustAllCerts, null);
|
||||
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
|
||||
} catch (Exception e) {
|
||||
s_logger.error("Unexpected exception ", e);
|
||||
}
|
||||
}
|
||||
|
||||
public VmwareContext(ExtendedAppUtil appUtil, String address) {
|
||||
assert(appUtil != null) : "Invalid parameter in constructing VmwareContext object";
|
||||
|
||||
_appUtil = appUtil;
|
||||
|
||||
public VmwareContext(VmwareClient client, String address) {
|
||||
assert(client != null) : "Invalid parameter in constructing VmwareContext object";
|
||||
|
||||
_vimClient = client;
|
||||
_serverAddress = address;
|
||||
}
|
||||
|
||||
|
|
@ -95,132 +90,136 @@ public class VmwareContext {
|
|||
_stockMap.put(name, obj);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void uregisterStockObject(String name) {
|
||||
synchronized(_stockMap) {
|
||||
_stockMap.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getStockObject(String name) {
|
||||
synchronized(_stockMap) {
|
||||
return (T)_stockMap.get(name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public String getServerAddress() {
|
||||
return _serverAddress;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
public ServiceConnection getServiceConnection() {
|
||||
return _appUtil.getServiceConnection3();
|
||||
return _vimClient.getServiceConnection3();
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
public VimPortType getService() {
|
||||
return getServiceConnection().getService();
|
||||
return _vimClient.getService();
|
||||
}
|
||||
|
||||
|
||||
public ServiceContent getServiceContent() {
|
||||
return getServiceConnection().getServiceContent();
|
||||
return _vimClient.getServiceContent();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
public ServiceUtil getServiceUtil() {
|
||||
return _appUtil.getServiceUtil3();
|
||||
return _vimClient.getServiceUtil3();
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
public ManagedObjectReference getPropertyCollector(){
|
||||
return _vimClient.getPropCol();
|
||||
}
|
||||
|
||||
public ManagedObjectReference getRootFolder() {
|
||||
return getServiceContent().getRootFolder();
|
||||
return _vimClient.getRootFolder();
|
||||
}
|
||||
|
||||
|
||||
public VmwareClient getVimClient(){
|
||||
return _vimClient;
|
||||
}
|
||||
|
||||
|
||||
public ManagedObjectReference getHostMorByPath(String inventoryPath) throws Exception {
|
||||
assert(inventoryPath != null);
|
||||
|
||||
|
||||
String[] tokens;
|
||||
if(inventoryPath.startsWith("/"))
|
||||
tokens = inventoryPath.substring(1).split("/");
|
||||
else
|
||||
tokens = inventoryPath.split("/");
|
||||
|
||||
|
||||
ManagedObjectReference mor = getRootFolder();
|
||||
for(int i=0; i < tokens.length;i++) {
|
||||
String token = tokens[i];
|
||||
ObjectContent[] ocs;
|
||||
List<ObjectContent> ocs;
|
||||
PropertySpec pSpec = null;
|
||||
ObjectSpec oSpec = null;
|
||||
if(mor.getType().equalsIgnoreCase("Datacenter")) {
|
||||
PropertySpec pSpec = new PropertySpec();
|
||||
pSpec = new PropertySpec();
|
||||
pSpec.setAll(false);
|
||||
pSpec.setType("ManagedEntity");
|
||||
pSpec.setPathSet(new String[] { "name" });
|
||||
|
||||
pSpec.getPathSet().add("name");
|
||||
|
||||
TraversalSpec dcHostFolderTraversal = new TraversalSpec();
|
||||
dcHostFolderTraversal.setType("Datacenter");
|
||||
dcHostFolderTraversal.setPath("hostFolder");
|
||||
dcHostFolderTraversal.setName("dcHostFolderTraversal");
|
||||
|
||||
ObjectSpec oSpec = new ObjectSpec();
|
||||
oSpec = new ObjectSpec();
|
||||
oSpec.setObj(mor);
|
||||
oSpec.setSkip(Boolean.TRUE);
|
||||
oSpec.setSelectSet(new SelectionSpec[] { dcHostFolderTraversal });
|
||||
oSpec.getSelectSet().add(dcHostFolderTraversal);
|
||||
|
||||
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
|
||||
pfSpec.setPropSet(new PropertySpec[] { pSpec });
|
||||
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
|
||||
ocs = getService().retrieveProperties(
|
||||
getServiceContent().getPropertyCollector(),
|
||||
new PropertyFilterSpec[] { pfSpec });
|
||||
|
||||
} else if(mor.getType().equalsIgnoreCase("Folder")) {
|
||||
PropertySpec pSpec = new PropertySpec();
|
||||
pSpec = new PropertySpec();
|
||||
pSpec.setAll(false);
|
||||
pSpec.setType("ManagedEntity");
|
||||
pSpec.setPathSet(new String[] { "name" });
|
||||
|
||||
pSpec.getPathSet().add("name");
|
||||
|
||||
TraversalSpec folderChildrenTraversal = new TraversalSpec();
|
||||
folderChildrenTraversal.setType("Folder");
|
||||
folderChildrenTraversal.setPath("childEntity");
|
||||
folderChildrenTraversal.setName("folderChildrenTraversal");
|
||||
|
||||
ObjectSpec oSpec = new ObjectSpec();
|
||||
oSpec = new ObjectSpec();
|
||||
oSpec.setObj(mor);
|
||||
oSpec.setSkip(Boolean.TRUE);
|
||||
oSpec.setSelectSet(new SelectionSpec[] { folderChildrenTraversal });
|
||||
oSpec.getSelectSet().add(folderChildrenTraversal);
|
||||
|
||||
|
||||
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
|
||||
pfSpec.setPropSet(new PropertySpec[] { pSpec });
|
||||
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
|
||||
|
||||
ocs = getService().retrieveProperties(
|
||||
getServiceContent().getPropertyCollector(),
|
||||
new PropertyFilterSpec[] { pfSpec });
|
||||
} else if(mor.getType().equalsIgnoreCase("ClusterComputeResource")) {
|
||||
PropertySpec pSpec = new PropertySpec();
|
||||
pSpec = new PropertySpec();
|
||||
pSpec.setType("ManagedEntity");
|
||||
pSpec.setPathSet(new String[] { "name" });
|
||||
|
||||
pSpec.getPathSet().add("name");
|
||||
|
||||
TraversalSpec clusterHostTraversal = new TraversalSpec();
|
||||
clusterHostTraversal.setType("ClusterComputeResource");
|
||||
clusterHostTraversal.setPath("host");
|
||||
clusterHostTraversal.setName("folderChildrenTraversal");
|
||||
|
||||
ObjectSpec oSpec = new ObjectSpec();
|
||||
oSpec = new ObjectSpec();
|
||||
oSpec.setObj(mor);
|
||||
oSpec.setSkip(Boolean.TRUE);
|
||||
oSpec.setSelectSet(new SelectionSpec[] { clusterHostTraversal });
|
||||
oSpec.getSelectSet().add(clusterHostTraversal);
|
||||
|
||||
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
|
||||
pfSpec.setPropSet(new PropertySpec[] { pSpec });
|
||||
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
|
||||
|
||||
ocs = getService().retrieveProperties(
|
||||
getServiceContent().getPropertyCollector(),
|
||||
new PropertyFilterSpec[] { pfSpec });
|
||||
} else {
|
||||
s_logger.error("Invalid inventory path, path element can only be datacenter and folder");
|
||||
return null;
|
||||
}
|
||||
|
||||
if(ocs != null && ocs.length > 0) {
|
||||
|
||||
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
|
||||
pfSpec.getPropSet().add(pSpec);
|
||||
pfSpec.getObjectSet().add(oSpec);
|
||||
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
|
||||
pfSpecArr.add(pfSpec);
|
||||
ocs = getService().retrieveProperties(getPropertyCollector(), pfSpecArr);
|
||||
|
||||
if(ocs != null && ocs.size() > 0) {
|
||||
boolean found = false;
|
||||
for(ObjectContent oc : ocs) {
|
||||
String name = oc.getPropSet()[0].getVal().toString();
|
||||
String name = oc.getPropSet().get(0).getVal().toString();
|
||||
if(name.equalsIgnoreCase(token) || name.equalsIgnoreCase("host")) {
|
||||
mor = oc.getObj();
|
||||
found = true;
|
||||
|
|
@ -244,44 +243,44 @@ public class VmwareContext {
|
|||
// path in format of <datacenter name>/<datastore name>
|
||||
public ManagedObjectReference getDatastoreMorByPath(String inventoryPath) throws Exception {
|
||||
assert(inventoryPath != null);
|
||||
|
||||
|
||||
String[] tokens;
|
||||
if(inventoryPath.startsWith("/"))
|
||||
tokens = inventoryPath.substring(1).split("/");
|
||||
else
|
||||
tokens = inventoryPath.split("/");
|
||||
|
||||
|
||||
if(tokens == null || tokens.length != 2) {
|
||||
s_logger.error("Invalid datastore inventory path. path: " + inventoryPath);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
DatacenterMO dcMo = new DatacenterMO(this, tokens[0]);
|
||||
if(dcMo.getMor() == null) {
|
||||
s_logger.error("Unable to locate the datacenter specified in path: " + inventoryPath);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return dcMo.findDatastore(tokens[1]);
|
||||
}
|
||||
|
||||
|
||||
public void waitForTaskProgressDone(ManagedObjectReference morTask) throws Exception {
|
||||
while(true) {
|
||||
TaskInfo tinfo = (TaskInfo)getServiceUtil().getDynamicProperty(morTask, "info");
|
||||
TaskInfo tinfo = (TaskInfo)_vimClient.getDynamicProperty(morTask, "info");
|
||||
Integer progress = tinfo.getProgress();
|
||||
if(progress == null)
|
||||
break;
|
||||
|
||||
|
||||
if(progress.intValue() >= 100)
|
||||
break;
|
||||
|
||||
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void getFile(String urlString, String localFileFullName) throws Exception {
|
||||
HttpURLConnection conn = getHTTPConnection(urlString);
|
||||
|
||||
|
||||
InputStream in = conn.getInputStream();
|
||||
OutputStream out = new FileOutputStream(new File(localFileFullName));
|
||||
byte[] buf = new byte[_CHUNKSIZE];
|
||||
|
|
@ -290,19 +289,19 @@ public class VmwareContext {
|
|||
out.write(buf, 0, len);
|
||||
}
|
||||
in.close();
|
||||
out.close();
|
||||
out.close();
|
||||
}
|
||||
|
||||
|
||||
public void uploadFile(String urlString, String localFileFullName) throws Exception {
|
||||
uploadFile(urlString, new File(localFileFullName));
|
||||
}
|
||||
|
||||
|
||||
public void uploadFile(String urlString, File localFile) throws Exception {
|
||||
HttpURLConnection conn = getHTTPConnection(urlString, "PUT");
|
||||
OutputStream out = null;
|
||||
InputStream in = null;
|
||||
BufferedReader br = null;
|
||||
|
||||
|
||||
try {
|
||||
out = conn.getOutputStream();
|
||||
in = new FileInputStream(localFile);
|
||||
|
|
@ -312,7 +311,7 @@ public class VmwareContext {
|
|||
out.write(buf, 0, len);
|
||||
}
|
||||
out.flush();
|
||||
|
||||
|
||||
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
|
|
@ -322,41 +321,41 @@ public class VmwareContext {
|
|||
} finally {
|
||||
if(in != null)
|
||||
in.close();
|
||||
|
||||
|
||||
if(out != null)
|
||||
out.close();
|
||||
|
||||
|
||||
if(br != null)
|
||||
br.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadVmdkFile(String httpMethod, String urlString, String localFileName,
|
||||
|
||||
public void uploadVmdkFile(String httpMethod, String urlString, String localFileName,
|
||||
long totalBytesUpdated, ActionDelegate progressUpdater) throws Exception {
|
||||
|
||||
|
||||
HttpURLConnection conn = getRawHTTPConnection(urlString);
|
||||
|
||||
|
||||
conn.setDoOutput(true);
|
||||
conn.setUseCaches(false);
|
||||
|
||||
conn.setChunkedStreamingMode(_CHUNKSIZE);
|
||||
conn.setRequestMethod(httpMethod);
|
||||
conn.setRequestProperty("Connection", "Keep-Alive");
|
||||
conn.setRequestProperty("Content-Type", "application/x-vnd.vmware-streamVmdk");
|
||||
|
||||
conn.setChunkedStreamingMode(_CHUNKSIZE);
|
||||
conn.setRequestMethod(httpMethod);
|
||||
conn.setRequestProperty("Connection", "Keep-Alive");
|
||||
conn.setRequestProperty("Content-Type", "application/x-vnd.vmware-streamVmdk");
|
||||
conn.setRequestProperty("Content-Length", Long.toString(new File(localFileName).length()));
|
||||
connectWithRetry(conn);
|
||||
|
||||
|
||||
BufferedOutputStream bos = null;
|
||||
BufferedInputStream is = null;
|
||||
try {
|
||||
bos = new BufferedOutputStream(conn.getOutputStream());
|
||||
is = new BufferedInputStream(new FileInputStream(localFileName));
|
||||
int bufferSize = _CHUNKSIZE;
|
||||
byte[] buffer = new byte[bufferSize];
|
||||
while (true) {
|
||||
int bytesRead = is.read(buffer, 0, bufferSize);
|
||||
if (bytesRead == -1) {
|
||||
break;
|
||||
bos = new BufferedOutputStream(conn.getOutputStream());
|
||||
is = new BufferedInputStream(new FileInputStream(localFileName));
|
||||
int bufferSize = _CHUNKSIZE;
|
||||
byte[] buffer = new byte[bufferSize];
|
||||
while (true) {
|
||||
int bytesRead = is.read(buffer, 0, bufferSize);
|
||||
if (bytesRead == -1) {
|
||||
break;
|
||||
}
|
||||
bos.write(buffer, 0, bytesRead);
|
||||
totalBytesUpdated += bytesRead;
|
||||
|
|
@ -370,54 +369,54 @@ public class VmwareContext {
|
|||
is.close();
|
||||
if(bos != null)
|
||||
bos.close();
|
||||
|
||||
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
public long downloadVmdkFile(String urlString, String localFileName,
|
||||
|
||||
public long downloadVmdkFile(String urlString, String localFileName,
|
||||
long totalBytesDownloaded, ActionDelegate progressUpdater) throws Exception {
|
||||
HttpURLConnection conn = getRawHTTPConnection(urlString);
|
||||
|
||||
|
||||
String cookieString = getServiceCookie();
|
||||
conn.setRequestProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE, cookieString);
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoOutput(true);
|
||||
conn.setAllowUserInteraction(true);
|
||||
connectWithRetry(conn);
|
||||
|
||||
long bytesWritten = 0;
|
||||
InputStream in = null;
|
||||
OutputStream out = null;
|
||||
long bytesWritten = 0;
|
||||
InputStream in = null;
|
||||
OutputStream out = null;
|
||||
try {
|
||||
in = conn.getInputStream();
|
||||
out = new FileOutputStream(new File(localFileName));
|
||||
|
||||
byte[] buf = new byte[_CHUNKSIZE];
|
||||
int len = 0;
|
||||
while ((len = in.read(buf)) > 0) {
|
||||
out.write(buf, 0, len);
|
||||
in = conn.getInputStream();
|
||||
out = new FileOutputStream(new File(localFileName));
|
||||
|
||||
byte[] buf = new byte[_CHUNKSIZE];
|
||||
int len = 0;
|
||||
while ((len = in.read(buf)) > 0) {
|
||||
out.write(buf, 0, len);
|
||||
bytesWritten += len;
|
||||
totalBytesDownloaded += len;
|
||||
|
||||
|
||||
if(progressUpdater != null)
|
||||
progressUpdater.action(new Long(totalBytesDownloaded));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if(in != null)
|
||||
in.close();
|
||||
if(out != null)
|
||||
out.close();
|
||||
|
||||
|
||||
conn.disconnect();
|
||||
}
|
||||
return bytesWritten;
|
||||
return bytesWritten;
|
||||
}
|
||||
|
||||
|
||||
public byte[] getResourceContent(String urlString) throws Exception {
|
||||
HttpURLConnection conn = getHTTPConnection(urlString);
|
||||
InputStream in = conn.getInputStream();
|
||||
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
byte[] buf = new byte[_CHUNKSIZE];
|
||||
int len = 0;
|
||||
|
|
@ -425,10 +424,10 @@ public class VmwareContext {
|
|||
out.write(buf, 0, len);
|
||||
}
|
||||
in.close();
|
||||
out.close();
|
||||
out.close();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
public void uploadResourceContent(String urlString, byte[] content) throws Exception {
|
||||
// vSphere does not support POST
|
||||
HttpURLConnection conn = getHTTPConnection(urlString, "PUT");
|
||||
|
|
@ -436,7 +435,7 @@ public class VmwareContext {
|
|||
OutputStream out = conn.getOutputStream();
|
||||
out.write(content);
|
||||
out.flush();
|
||||
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
|
|
@ -446,15 +445,15 @@ public class VmwareContext {
|
|||
out.close();
|
||||
in.close();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Sample content returned by query a datastore directory
|
||||
*
|
||||
*
|
||||
* Url for the query
|
||||
* https://vsphere-1.lab.vmops.com/folder/Fedora-clone-test?dcPath=cupertino&dsName=NFS+datastore
|
||||
*
|
||||
* Returned conent from vSphere
|
||||
*
|
||||
*
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
|
||||
<html>
|
||||
<head>
|
||||
|
|
@ -485,7 +484,7 @@ public class VmwareContext {
|
|||
</table>
|
||||
</body>
|
||||
</html>
|
||||
*/
|
||||
*/
|
||||
public String[] listDatastoreDirContent(String urlString) throws Exception {
|
||||
List<String> fileList = new ArrayList<String>();
|
||||
String content = new String(getResourceContent(urlString));
|
||||
|
|
@ -497,7 +496,7 @@ public class VmwareContext {
|
|||
int beginPos = content.lastIndexOf('>', parsePos -1);
|
||||
if(beginPos < 0)
|
||||
beginPos = 0;
|
||||
|
||||
|
||||
fileList.add((content.substring(beginPos + 1, parsePos)));
|
||||
parsePos += marker.length();
|
||||
} else {
|
||||
|
|
@ -511,11 +510,11 @@ public class VmwareContext {
|
|||
DatastoreFile dsFile = new DatastoreFile(fullPath);
|
||||
return composeDatastoreBrowseUrl(dcName, dsFile.getDatastoreName(), dsFile.getRelativePath());
|
||||
}
|
||||
|
||||
|
||||
public String composeDatastoreBrowseUrl(String dcName, String datastoreName, String relativePath) {
|
||||
assert(relativePath != null);
|
||||
assert(datastoreName != null);
|
||||
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("https://");
|
||||
sb.append(_serverAddress);
|
||||
|
|
@ -525,23 +524,24 @@ public class VmwareContext {
|
|||
sb.append(URLEncoder.encode(datastoreName));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
public HttpURLConnection getHTTPConnection(String urlString) throws Exception {
|
||||
return getHTTPConnection(urlString, "GET");
|
||||
}
|
||||
|
||||
|
||||
public HttpURLConnection getHTTPConnection(String urlString, String httpMethod) throws Exception {
|
||||
String cookieString = getServiceCookie();
|
||||
HostnameVerifier hv = new HostnameVerifier() {
|
||||
public boolean verify(String urlHostName, SSLSession session) {
|
||||
@Override
|
||||
public boolean verify(String urlHostName, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv);
|
||||
URL url = new URL(urlString);
|
||||
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv);
|
||||
URL url = new URL(urlString);
|
||||
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
|
||||
|
||||
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
conn.setAllowUserInteraction(true);
|
||||
|
|
@ -550,16 +550,17 @@ public class VmwareContext {
|
|||
connectWithRetry(conn);
|
||||
return conn;
|
||||
}
|
||||
|
||||
|
||||
public HttpURLConnection getRawHTTPConnection(String urlString) throws Exception {
|
||||
HostnameVerifier hv = new HostnameVerifier() {
|
||||
public boolean verify(String urlHostName, SSLSession session) {
|
||||
@Override
|
||||
public boolean verify(String urlHostName, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv);
|
||||
URL url = new URL(urlString);
|
||||
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(hv);
|
||||
URL url = new URL(urlString);
|
||||
return (HttpURLConnection)url.openConnection();
|
||||
}
|
||||
|
||||
|
|
@ -571,7 +572,7 @@ public class VmwareContext {
|
|||
String cookieString = (String)msgContext.getProperty(org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE);
|
||||
return cookieString;
|
||||
}
|
||||
|
||||
|
||||
private static void connectWithRetry(HttpURLConnection conn) throws Exception {
|
||||
boolean connected = false;
|
||||
for(int i = 0; i < MAX_CONNECT_RETRY && !connected; i++) {
|
||||
|
|
@ -581,45 +582,48 @@ public class VmwareContext {
|
|||
s_logger.info("Connected, conn: " + conn.toString() + ", retry: " + i);
|
||||
} catch (Exception e) {
|
||||
s_logger.warn("Unable to connect, conn: " + conn.toString() + ", message: " + e.toString() + ", retry: " + i);
|
||||
|
||||
|
||||
try {
|
||||
Thread.sleep(CONNECT_RETRY_INTERVAL);
|
||||
} catch(InterruptedException ex) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(!connected)
|
||||
throw new Exception("Unable to connect to " + conn.toString());
|
||||
}
|
||||
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
_appUtil.disConnect();
|
||||
_vimClient.disconnect();
|
||||
} catch(Exception e) {
|
||||
s_logger.warn("Unexpected exception: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
@Override
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
|
||||
throws java.security.cert.CertificateException {
|
||||
return;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
|
||||
throws java.security.cert.CertificateException {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue