use of com.cloud.hypervisor.vmware.mo.ClusterMO in project cloudstack by apache.
the class VmwareResource method prepareNetworkElementCommand.
private ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) {
VmwareContext context = getServiceContext();
try {
VmwareHypervisorHost hyperHost = getHyperHost(context);
IpAddressTO[] ips = cmd.getIpAddresses();
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String controlIp = VmwareResource.getRouterSshControlIp(cmd);
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName);
// the check and will try to find it within cluster
if (vmMo == null) {
if (hyperHost instanceof HostMO) {
ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO) hyperHost).getParentMor());
vmMo = clusterMo.findVmOnHyperHost(routerName);
}
}
if (vmMo == null) {
String msg = "Router " + routerName + " no longer exists to execute IPAssoc command";
s_logger.error(msg);
throw new Exception(msg);
}
for (IpAddressTO ip : ips) {
/**
* TODO support other networks
*/
URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri());
if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) {
throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + ip.getBroadcastUri());
}
String vlanId = BroadcastDomainType.getValue(broadcastUri);
String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId);
Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first());
}
boolean addVif = false;
if (ip.isAdd() && publicNicInfo.first().intValue() == -1) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Plug new NIC to associate" + controlIp + " to " + ip.getPublicIp());
}
addVif = true;
}
if (addVif) {
plugPublicNic(vmMo, vlanId, ip.getVifMacAddress());
publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName);
if (publicNicInfo.first().intValue() >= 0) {
networkUsage(controlIp, "addVif", "eth" + publicNicInfo.first());
}
}
if (publicNicInfo.first().intValue() < 0) {
String msg = "Failed to find DomR VIF to associate/disassociate IP with.";
s_logger.error(msg);
throw new InternalErrorException(msg);
}
ip.setNicDevId(publicNicInfo.first().intValue());
ip.setNewNic(addVif);
}
} catch (Throwable e) {
s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e);
return new ExecutionResult(false, e.toString());
}
return new ExecutionResult(true, null);
}
use of com.cloud.hypervisor.vmware.mo.ClusterMO in project cloudstack by apache.
the class VmwareResource method execute.
private PlugNicAnswer execute(PlugNicCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource PlugNicCommand " + _gson.toJson(cmd));
}
getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
VmwareContext context = getServiceContext();
try {
VmwareHypervisorHost hyperHost = getHyperHost(context);
String vmName = cmd.getVmName();
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
if (vmMo == null) {
if (hyperHost instanceof HostMO) {
ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO) hyperHost).getParentMor());
vmMo = clusterMo.findVmOnHyperHost(vmName);
}
}
if (vmMo == null) {
String msg = "Router " + vmName + " no longer exists to execute PlugNic command";
s_logger.error(msg);
throw new Exception(msg);
}
/*
if(!isVMWareToolsInstalled(vmMo)){
String errMsg = "vmware tools is not installed or not running, cannot add nic to vm " + vmName;
s_logger.debug(errMsg);
return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + errMsg);
}
*/
// Fallback to E1000 if no specific nicAdapter is passed
VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.E1000;
Map<String, String> details = cmd.getDetails();
if (details != null) {
nicDeviceType = VirtualEthernetCardType.valueOf((String) details.get("nicAdapter"));
}
// find a usable device number in VMware environment
VirtualDevice[] nicDevices = vmMo.getNicDevices();
int deviceNumber = -1;
for (VirtualDevice device : nicDevices) {
if (device.getUnitNumber() > deviceNumber)
deviceNumber = device.getUnitNumber();
}
deviceNumber++;
NicTO nicTo = cmd.getNic();
VirtualDevice nic;
Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, false, cmd.getVMType());
String dvSwitchUuid = null;
if (VmwareHelper.isDvPortGroup(networkInfo.first())) {
ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);
ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first());
dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor);
s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid);
nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true);
} else {
s_logger.info("Preparing NIC device on network " + networkInfo.second());
nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true);
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
//VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(nic);
deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
setNuageVspVrIpInExtraConfig(vmConfigSpec.getExtraConfig(), nicTo, dvSwitchUuid);
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure devices when running PlugNicCommand");
}
return new PlugNicAnswer(cmd, true, "success");
} catch (Exception e) {
s_logger.error("Unexpected exception: ", e);
return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + e.toString());
}
}
use of com.cloud.hypervisor.vmware.mo.ClusterMO in project cloudstack by apache.
the class VmwareStorageProcessor method getVmfsDatastore.
private ManagedObjectReference getVmfsDatastore(VmwareContext context, VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, String iqn, String chapName, String chapSecret, String mutualChapName, String mutualChapSecret) throws Exception {
ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
ClusterMO cluster = new ClusterMO(context, morCluster);
List<Pair<ManagedObjectReference, String>> lstHosts = cluster.getClusterHosts();
HostInternetScsiHbaStaticTarget target = new HostInternetScsiHbaStaticTarget();
target.setAddress(storageIpAddress);
target.setPort(storagePortNumber);
target.setIScsiName(iqn);
if (StringUtils.isNotBlank(chapName) && StringUtils.isNotBlank(chapSecret)) {
HostInternetScsiHbaAuthenticationProperties auth = new HostInternetScsiHbaAuthenticationProperties();
String strAuthType = "chapRequired";
auth.setChapAuthEnabled(true);
auth.setChapInherited(false);
auth.setChapAuthenticationType(strAuthType);
auth.setChapName(chapName);
auth.setChapSecret(chapSecret);
if (StringUtils.isNotBlank(mutualChapName) && StringUtils.isNotBlank(mutualChapSecret)) {
auth.setMutualChapInherited(false);
auth.setMutualChapAuthenticationType(strAuthType);
auth.setMutualChapName(mutualChapName);
auth.setMutualChapSecret(mutualChapSecret);
}
target.setAuthenticationProperties(auth);
}
final List<HostInternetScsiHbaStaticTarget> lstTargets = new ArrayList<HostInternetScsiHbaStaticTarget>();
lstTargets.add(target);
addRemoveInternetScsiTargetsToAllHosts(context, true, lstTargets, lstHosts);
rescanAllHosts(context, lstHosts);
HostMO host = new HostMO(context, lstHosts.get(0).first());
HostDatastoreSystemMO hostDatastoreSystem = host.getHostDatastoreSystemMO();
ManagedObjectReference morDs = hostDatastoreSystem.findDatastoreByName(datastoreName);
if (morDs != null) {
return morDs;
}
rescanAllHosts(context, lstHosts);
HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO();
List<HostScsiDisk> lstHostScsiDisks = hostDatastoreSystem.queryAvailableDisksForVmfs();
HostScsiDisk hostScsiDisk = getHostScsiDisk(hostStorageSystem.getStorageDeviceInfo().getScsiTopology(), lstHostScsiDisks, iqn);
if (hostScsiDisk == null) {
// check to see if the datastore actually does exist already
morDs = hostDatastoreSystem.findDatastoreByName(datastoreName);
if (morDs != null) {
return morDs;
}
throw new Exception("A relevant SCSI disk could not be located to use to create a datastore.");
}
morDs = hostDatastoreSystem.createVmfsDatastore(datastoreName, hostScsiDisk);
if (morDs != null) {
rescanAllHosts(context, lstHosts);
return morDs;
}
throw new Exception("Unable to create a datastore");
}
use of com.cloud.hypervisor.vmware.mo.ClusterMO in project cloudstack by apache.
the class VmwareStorageProcessor method cloneVolumeFromBaseTemplate.
@Override
public Answer cloneVolumeFromBaseTemplate(CopyCommand cmd) {
DataTO srcData = cmd.getSrcTO();
TemplateObjectTO template = (TemplateObjectTO) srcData;
DataTO destData = cmd.getDestTO();
VolumeObjectTO volume = (VolumeObjectTO) destData;
DataStoreTO primaryStore = volume.getDataStore();
DataStoreTO srcStore = template.getDataStore();
try {
VmwareContext context = hostService.getServiceContext(null);
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
VirtualMachineMO vmMo = null;
ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
if (morDatastore == null) {
throw new Exception("Unable to find datastore in vSphere");
}
DatastoreMO dsMo = new DatastoreMO(context, morDatastore);
String vmdkName = volume.getName();
String vmdkFileBaseName = null;
if (srcStore == null) {
// create a root volume for blank VM (created from ISO)
String dummyVmName = hostService.getWorkerName(context, cmd, 0);
try {
vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, dummyVmName);
if (vmMo == null) {
throw new Exception("Unable to create a dummy VM for volume creation");
}
vmdkFileBaseName = vmMo.getVmdkFileBaseNames().get(0);
// we only use the first file in the pair, linked or not will not matter
String[] vmdkFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, null, vmdkFileBaseName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, true);
String volumeDatastorePath = vmdkFilePair[0];
synchronized (this) {
s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath);
VmwareStorageLayoutHelper.deleteVolumeVmdkFiles(dsMo, vmdkName, dcMo);
vmMo.createDisk(volumeDatastorePath, (int) (volume.getSize() / (1024L * 1024L)), morDatastore, -1);
vmMo.detachDisk(volumeDatastorePath, false);
}
} finally {
s_logger.info("Destroy dummy VM after volume creation");
if (vmMo != null) {
s_logger.warn("Unable to destroy a null VM ManagedObjectReference");
vmMo.detachAllDisks();
vmMo.destroy();
}
}
} else {
String templatePath = template.getPath();
VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templatePath), true);
if (vmTemplate == null) {
s_logger.warn("Template host in vSphere is not in connected state, request template reload");
return new CopyCmdAnswer("Template host in vSphere is not in connected state, request template reload");
}
ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool();
ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
if (!_fullCloneFlag) {
createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool);
} else {
createVMFullClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool);
}
vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName);
assert (vmMo != null);
// TO-DO: Support for base template containing multiple disks
vmdkFileBaseName = vmMo.getVmdkFileBaseNames().get(0);
s_logger.info("Move volume out of volume-wrapper VM ");
String[] vmwareLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkFileBaseName, VmwareStorageLayoutType.VMWARE, !_fullCloneFlag);
String[] legacyCloudStackLayoutFilePair = VmwareStorageLayoutHelper.getVmdkFilePairDatastorePath(dsMo, vmdkName, vmdkFileBaseName, VmwareStorageLayoutType.CLOUDSTACK_LEGACY, !_fullCloneFlag);
dsMo.moveDatastoreFile(vmwareLayoutFilePair[0], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[0], dcMo.getMor(), true);
dsMo.moveDatastoreFile(vmwareLayoutFilePair[1], dcMo.getMor(), dsMo.getMor(), legacyCloudStackLayoutFilePair[1], dcMo.getMor(), true);
s_logger.info("detach disks from volume-wrapper VM " + vmdkName);
vmMo.detachAllDisks();
s_logger.info("destroy volume-wrapper VM " + vmdkName);
vmMo.destroy();
String srcFile = dsMo.getDatastorePath(vmdkName, true);
dsMo.deleteFile(srcFile, dcMo.getMor(), true);
}
// restoreVM - move the new ROOT disk into corresponding VM folder
VirtualMachineMO restoreVmMo = dcMo.findVm(volume.getVmName());
if (restoreVmMo != null) {
// VM folder name in datastore will be VM's name in vCenter.
String vmNameInVcenter = restoreVmMo.getName();
if (dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmNameInVcenter)) {
VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmNameInVcenter, dsMo, vmdkFileBaseName);
}
}
VolumeObjectTO newVol = new VolumeObjectTO();
newVol.setPath(vmdkFileBaseName);
newVol.setSize(volume.getSize());
return new CopyCmdAnswer(newVol);
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
hostService.invalidateServiceContext(null);
}
String msg = "clone volume from base image failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg, e);
return new CopyCmdAnswer(e.toString());
}
}
use of com.cloud.hypervisor.vmware.mo.ClusterMO in project cloudstack by apache.
the class VmwareStorageProcessor method deleteVolume.
@Override
public Answer deleteVolume(DeleteCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource DeleteCommand: " + _gson.toJson(cmd));
}
try {
VmwareContext context = hostService.getServiceContext(null);
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
VolumeObjectTO vol = (VolumeObjectTO) cmd.getData();
DataStoreTO store = vol.getDataStore();
PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) store;
Map<String, String> details = primaryDataStoreTO.getDetails();
boolean isManaged = false;
String managedDatastoreName = null;
if (details != null) {
isManaged = Boolean.parseBoolean(details.get(PrimaryDataStoreTO.MANAGED));
if (isManaged) {
managedDatastoreName = getManagedDatastoreNameFromPath(vol.getPath());
}
}
ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? managedDatastoreName : store.getUuid());
if (morDs == null) {
String msg = "Unable to find datastore based on volume mount point " + store.getUuid();
s_logger.error(msg);
throw new Exception(msg);
}
DatastoreMO dsMo = new DatastoreMO(context, morDs);
ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
ClusterMO clusterMo = new ClusterMO(context, morCluster);
if (vol.getVolumeType() == Volume.Type.ROOT) {
String vmName = vol.getVmName();
if (vmName != null) {
VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName);
if (vmMo == null) {
// Volume might be on a zone-wide storage pool, look for VM in datacenter
DatacenterMO dcMo = new DatacenterMO(context, morDc);
vmMo = dcMo.findVm(vmName);
}
if (vmMo != null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy root volume and VM itself. vmName " + vmName);
}
VirtualMachineDiskInfo diskInfo = null;
if (vol.getChainInfo() != null)
diskInfo = _gson.fromJson(vol.getChainInfo(), VirtualMachineDiskInfo.class);
HostMO hostMo = vmMo.getRunningHost();
List<NetworkDetails> networks = vmMo.getNetworksWithDetails();
// tear down all devices first before we destroy the VM to avoid accidently delete disk backing files
if (VmwareResource.getVmState(vmMo) != PowerState.PowerOff) {
vmMo.safePowerOff(_shutdownWaitMs);
}
// call this before calling detachAllDisksExcept
// when expunging a VM, we need to see if any of its disks are serviced by managed storage
// if there is one or more disk serviced by managed storage, remove the iSCSI connection(s)
// don't remove the iSCSI connection(s) until the supported disk(s) is/are removed from the VM
// (removeManagedTargetsFromCluster should be called after detachAllDisksExcept and vm.destroy)
List<VirtualDisk> virtualDisks = vmMo.getVirtualDisks();
List<String> managedIqns = getManagedIqnsFromVirtualDisks(virtualDisks);
List<String> detachedDisks = vmMo.detachAllDisksExcept(vol.getPath(), diskInfo != null ? diskInfo.getDiskDeviceBusName() : null);
VmwareStorageLayoutHelper.moveVolumeToRootFolder(new DatacenterMO(context, morDc), detachedDisks);
if (isManaged) {
vmMo.unregisterVm();
} else {
vmMo.destroy();
}
// this.hostService.handleDatastoreAndVmdkDetach(iScsiName, storageHost, storagePort);
if (managedIqns != null && !managedIqns.isEmpty()) {
removeManagedTargetsFromCluster(managedIqns);
}
for (NetworkDetails netDetails : networks) {
if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) {
if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) {
resource.cleanupNetwork(hostMo, netDetails);
}
}
}
}
/*
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk");
}
VmwareStorageLayoutHelper.deleteVolumeVmdkFiles(dsMo, vol.getPath(), new DatacenterMO(context, morDc));
*/
return new Answer(cmd, true, "Success");
}
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy root volume directly from datastore");
}
}
VmwareStorageLayoutHelper.deleteVolumeVmdkFiles(dsMo, vol.getPath(), new DatacenterMO(context, morDc));
return new Answer(cmd, true, "Success");
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
hostService.invalidateServiceContext(null);
}
String msg = "delete volume failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg, e);
return new Answer(cmd, false, msg);
}
}
Aggregations