use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareStorageProcessor method backupSnapshot.
@Override
public Answer backupSnapshot(CopyCommand cmd) {
SnapshotObjectTO srcSnapshot = (SnapshotObjectTO) cmd.getSrcTO();
DataStoreTO primaryStore = srcSnapshot.getDataStore();
SnapshotObjectTO destSnapshot = (SnapshotObjectTO) cmd.getDestTO();
DataStoreTO destStore = destSnapshot.getDataStore();
if (!(destStore instanceof NfsTO)) {
return new CopyCmdAnswer("unsupported protocol");
}
NfsTO destNfsStore = (NfsTO) destStore;
String secondaryStorageUrl = destNfsStore.getUrl();
String snapshotUuid = srcSnapshot.getPath();
String prevSnapshotUuid = srcSnapshot.getParentSnapshotPath();
String prevBackupUuid = destSnapshot.getParentSnapshotPath();
VirtualMachineMO workerVm = null;
String workerVMName = null;
String volumePath = srcSnapshot.getVolume().getPath();
ManagedObjectReference morDs;
DatastoreMO dsMo;
// By default assume failure
String details;
boolean success;
String snapshotBackupUuid;
boolean hasOwnerVm = false;
Ternary<String, String, String[]> backupResult = null;
VmwareContext context = hostService.getServiceContext(cmd);
VirtualMachineMO vmMo = null;
String vmName = srcSnapshot.getVmName();
try {
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
CopyCmdAnswer answer = null;
try {
if (vmName != null) {
vmMo = hyperHost.findVmOnHyperHost(vmName);
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(vmName);
}
}
if (vmMo == null) {
dsMo = new DatastoreMO(hyperHost.getContext(), morDs);
workerVMName = hostService.getWorkerName(context, cmd, 0, dsMo);
vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, workerVMName, null);
if (vmMo == null) {
throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName);
}
workerVm = vmMo;
// attach volume to worker VM
String datastoreVolumePath = VmwareStorageLayoutHelper.getLegacyDatastorePathFromVmdkFileName(dsMo, volumePath + ".vmdk");
vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs);
} else {
s_logger.info("Using owner VM " + vmName + " for snapshot operation");
hasOwnerVm = true;
}
s_logger.debug(String.format("Executing backup snapshot with UUID [%s] to secondary storage.", snapshotUuid));
backupResult = backupSnapshotToSecondaryStorage(context, vmMo, hyperHost, destSnapshot.getPath(), srcSnapshot.getVolume().getPath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid, hostService.getWorkerName(context, cmd, 1, null), _nfsVersion);
snapshotBackupUuid = backupResult.first();
success = (snapshotBackupUuid != null);
if (!success) {
details = "Failed to backUp the snapshot with uuid: " + snapshotUuid + " to secondary storage.";
answer = new CopyCmdAnswer(details);
} else {
details = "Successfully backedUp the snapshot with Uuid: " + snapshotUuid + " to secondary storage.";
// Get snapshot physical size
long physicalSize = 0;
String secondaryMountPoint = mountService.getMountPoint(secondaryStorageUrl, _nfsVersion);
String snapshotDir = destSnapshot.getPath() + "/" + snapshotBackupUuid;
File[] files = new File(secondaryMountPoint + "/" + snapshotDir).listFiles();
if (files != null) {
for (File file : files) {
String fileName = file.getName();
if (fileName.toLowerCase().startsWith(snapshotBackupUuid) && fileName.toLowerCase().endsWith(".vmdk")) {
physicalSize = new File(secondaryMountPoint + "/" + snapshotDir + "/" + fileName).length();
break;
}
}
}
SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
newSnapshot.setPath(snapshotDir + "/" + snapshotBackupUuid);
newSnapshot.setPhysicalSize(physicalSize);
answer = new CopyCmdAnswer(newSnapshot);
}
} finally {
if (vmMo != null) {
ManagedObjectReference snapshotMor = vmMo.getSnapshotMor(snapshotUuid);
if (snapshotMor != null) {
vmMo.removeSnapshot(snapshotUuid, false);
// in the middle
if (backupResult != null && hasOwnerVm) {
s_logger.info("Check if we have disk consolidation after snapshot operation");
boolean chainConsolidated = false;
for (String vmdkDsFilePath : backupResult.third()) {
s_logger.info("Validate disk chain file:" + vmdkDsFilePath);
if (vmMo.getDiskDevice(vmdkDsFilePath) == null) {
s_logger.info("" + vmdkDsFilePath + " no longer exists, consolidation detected");
chainConsolidated = true;
break;
} else {
s_logger.info("" + vmdkDsFilePath + " is found still in chain");
}
}
if (chainConsolidated) {
String topVmdkFilePath = null;
try {
topVmdkFilePath = vmMo.getDiskCurrentTopBackingFileInChain(backupResult.second());
} catch (Exception e) {
s_logger.error("Unexpected exception", e);
}
s_logger.info("Disk has been consolidated, top VMDK is now: " + topVmdkFilePath);
if (topVmdkFilePath != null) {
DatastoreFile file = new DatastoreFile(topVmdkFilePath);
SnapshotObjectTO snapshotInfo = (SnapshotObjectTO) answer.getNewData();
VolumeObjectTO vol = new VolumeObjectTO();
vol.setUuid(srcSnapshot.getVolume().getUuid());
vol.setPath(file.getFileBaseName());
snapshotInfo.setVolume(vol);
} else {
s_logger.error("Disk has been consolidated, but top VMDK is not found ?!");
}
}
}
} else {
s_logger.info("No snapshots created to be deleted!");
}
}
try {
if (workerVm != null) {
workerVm.detachAllDisksAndDestroy();
}
} catch (Throwable e) {
s_logger.warn(String.format("Failed to destroy worker VM [%s] due to: [%s]", workerVMName, e.getMessage()), e);
}
}
return answer;
} catch (Throwable e) {
return new CopyCmdAnswer(hostService.createLogMessageException(e, cmd));
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareStorageProcessor method attachVolume.
private Answer attachVolume(Command cmd, DiskTO disk, boolean isAttach, boolean isManaged, String vmName, String iScsiName, String storageHost, int storagePort, Map<String, String> controllerInfo) {
VolumeObjectTO volumeTO = (VolumeObjectTO) disk.getData();
DataStoreTO primaryStore = volumeTO.getDataStore();
String volumePath = volumeTO.getPath();
String storagePolicyId = volumeTO.getvSphereStoragePolicyId();
String vmdkPath = isManaged ? resource.getVmdkPath(volumePath) : null;
try {
VmwareContext context = hostService.getServiceContext(null);
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
if (vmMo == null) {
vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
if (vmMo == null) {
String msg = "Unable to find the VM to execute AttachCommand, vmName: " + vmName;
s_logger.error(msg);
throw new Exception(msg);
}
}
vmName = vmMo.getName();
ManagedObjectReference morDs;
String diskUuid = volumeTO.getUuid().replace("-", "");
if (isAttach && isManaged) {
Map<String, String> details = disk.getDetails();
morDs = prepareManagedStorage(context, hyperHost, diskUuid, iScsiName, storageHost, storagePort, vmdkPath, details.get(DiskTO.CHAP_INITIATOR_USERNAME), details.get(DiskTO.CHAP_INITIATOR_SECRET), details.get(DiskTO.CHAP_TARGET_USERNAME), details.get(DiskTO.CHAP_TARGET_SECRET), volumeTO.getSize(), cmd);
} else {
if (storagePort == DEFAULT_NFS_PORT) {
morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(diskUuid) : primaryStore.getUuid());
} else {
morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid());
}
}
if (morDs == null) {
String msg = "Unable to find the mounted datastore to execute AttachCommand, vmName: " + vmName;
s_logger.error(msg);
throw new Exception(msg);
}
DatastoreMO dsMo = new DatastoreMO(context, morDs);
String datastoreVolumePath;
boolean datastoreChangeObserved = false;
boolean volumePathChangeObserved = false;
String chainInfo = null;
if (isAttach) {
if (isManaged) {
datastoreVolumePath = dsMo.getDatastorePath((vmdkPath != null ? vmdkPath : dsMo.getName()) + ".vmdk");
} else {
if (dsMo.getDatastoreType().equalsIgnoreCase("VVOL")) {
datastoreVolumePath = VmwareStorageLayoutHelper.getLegacyDatastorePathFromVmdkFileName(dsMo, volumePath + ".vmdk");
if (!dsMo.fileExists(datastoreVolumePath)) {
datastoreVolumePath = VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(dsMo, vmName, volumePath + ".vmdk");
}
if (!dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmName) || !dsMo.fileExists(datastoreVolumePath)) {
datastoreVolumePath = VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(dsMo, volumePath, volumePath + ".vmdk");
}
if (!dsMo.folderExists(String.format("[%s]", dsMo.getName()), volumePath) || !dsMo.fileExists(datastoreVolumePath)) {
datastoreVolumePath = dsMo.searchFileInSubFolders(volumePath + ".vmdk", true, null);
}
} else {
datastoreVolumePath = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dsMo.getOwnerDatacenter().first(), vmName, dsMo, volumePath, VmwareManager.s_vmwareSearchExcludeFolder.value());
}
}
} else {
if (isManaged) {
datastoreVolumePath = dsMo.getDatastorePath((vmdkPath != null ? vmdkPath : dsMo.getName()) + ".vmdk");
} else {
String datastoreUUID = primaryStore.getUuid();
if (disk.getDetails().get(DiskTO.PROTOCOL_TYPE) != null && disk.getDetails().get(DiskTO.PROTOCOL_TYPE).equalsIgnoreCase("DatastoreCluster")) {
VirtualMachineDiskInfo matchingExistingDisk = getMatchingExistingDisk(hyperHost, context, vmMo, disk);
VirtualMachineDiskInfoBuilder diskInfoBuilder = vmMo.getDiskInfoBuilder();
if (diskInfoBuilder != null && matchingExistingDisk != null) {
String[] diskChain = matchingExistingDisk.getDiskChain();
assert (diskChain.length > 0);
DatastoreFile file = new DatastoreFile(diskChain[0]);
if (!file.getFileBaseName().equalsIgnoreCase(volumePath)) {
if (s_logger.isInfoEnabled())
s_logger.info("Detected disk-chain top file change on volume: " + volumeTO.getId() + " " + volumePath + " -> " + file.getFileBaseName());
volumePathChangeObserved = true;
volumePath = file.getFileBaseName();
volumeTO.setPath(volumePath);
chainInfo = _gson.toJson(matchingExistingDisk);
}
DatastoreMO diskDatastoreMofromVM = getDiskDatastoreMofromVM(hyperHost, context, vmMo, disk, diskInfoBuilder);
if (diskDatastoreMofromVM != null) {
String actualPoolUuid = diskDatastoreMofromVM.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID);
if (!actualPoolUuid.equalsIgnoreCase(primaryStore.getUuid())) {
s_logger.warn(String.format("Volume %s found to be in a different storage pool %s", volumePath, actualPoolUuid));
datastoreChangeObserved = true;
datastoreUUID = actualPoolUuid;
chainInfo = _gson.toJson(matchingExistingDisk);
}
}
}
}
if (storagePort == DEFAULT_NFS_PORT) {
morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(diskUuid) : datastoreUUID);
} else {
morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, isManaged ? VmwareResource.getDatastoreName(iScsiName) : datastoreUUID);
}
dsMo = new DatastoreMO(context, morDs);
datastoreVolumePath = VmwareStorageLayoutHelper.getLegacyDatastorePathFromVmdkFileName(dsMo, volumePath + ".vmdk");
if (!dsMo.fileExists(datastoreVolumePath)) {
datastoreVolumePath = VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(dsMo, vmName, volumePath + ".vmdk");
}
if (!dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmName) || !dsMo.fileExists(datastoreVolumePath)) {
datastoreVolumePath = VmwareStorageLayoutHelper.getVmwareDatastorePathFromVmdkFileName(dsMo, volumePath, volumePath + ".vmdk");
}
if (!dsMo.folderExists(String.format("[%s]", dsMo.getName()), volumePath) || !dsMo.fileExists(datastoreVolumePath)) {
datastoreVolumePath = dsMo.searchFileInSubFolders(volumePath + ".vmdk", true, null);
}
}
}
disk.setPath(datastoreVolumePath);
AttachAnswer answer = new AttachAnswer(disk);
if (isAttach) {
String diskController = getLegacyVmDataDiskController();
if (controllerInfo != null && StringUtils.isNotEmpty(controllerInfo.get(VmDetailConstants.DATA_DISK_CONTROLLER))) {
diskController = controllerInfo.get(VmDetailConstants.DATA_DISK_CONTROLLER);
}
if (DiskControllerType.getType(diskController) == DiskControllerType.osdefault) {
diskController = vmMo.getRecommendedDiskController(null);
}
vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs, diskController, storagePolicyId);
VirtualMachineDiskInfoBuilder diskInfoBuilder = vmMo.getDiskInfoBuilder();
VirtualMachineDiskInfo diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(volumePath, dsMo.getName());
chainInfo = _gson.toJson(diskInfo);
if (isManaged) {
expandVirtualDisk(vmMo, datastoreVolumePath, volumeTO.getSize());
}
} else {
vmMo.removeAllSnapshots();
vmMo.detachDisk(datastoreVolumePath, false);
if (isManaged) {
handleDatastoreAndVmdkDetachManaged(cmd, diskUuid, iScsiName, storageHost, storagePort);
} else {
if (!dsMo.getDatastoreType().equalsIgnoreCase("VVOL")) {
VmwareStorageLayoutHelper.syncVolumeToRootFolder(dsMo.getOwnerDatacenter().first(), dsMo, volumePath, vmName, VmwareManager.s_vmwareSearchExcludeFolder.value());
}
}
if (datastoreChangeObserved) {
answer.setContextParam("datastoreName", dsMo.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID));
}
if (volumePathChangeObserved) {
answer.setContextParam("volumePath", volumePath);
}
}
if (chainInfo != null && !chainInfo.isEmpty())
answer.setContextParam("chainInfo", chainInfo);
return answer;
} catch (Throwable e) {
String msg = String.format("Failed to %s volume!", isAttach ? "attach" : "detach");
s_logger.error(msg, e);
hostService.createLogMessageException(e, cmd);
// Sending empty error message - too many duplicate errors in UI
return new AttachAnswer("");
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareStorageProcessor method cleanUpDatastore.
/**
* 1) Possibly expand the datastore.
* 2) Possibly consolidate all relevant VMDK files into one VMDK file.
* 3) Possibly move the VMDK file to the root folder (may already be there).
* 4) If the VMDK file wasn't already in the root folder, then delete the folder the VMDK file was in.
* 5) Possibly rename the VMDK file (this will lead to there being a delta file with the new name and the
* original file with the original name).
*
* Note: If the underlying VMDK file was for a root disk, the 'vmdk' parameter's value might look, for example,
* like "i-2-32-VM/ROOT-32.vmdk".
*
* Note: If the underlying VMDK file was for a data disk, the 'vmdk' parameter's value might look, for example,
* like "-iqn.2010-01.com.solidfire:4nhe.data-32.79-0.vmdk".
*
* Returns the (potentially new) name of the VMDK file.
*/
private String cleanUpDatastore(Command cmd, HostDatastoreSystemMO hostDatastoreSystem, DatastoreMO dsMo, Map<String, String> details) throws Exception {
s_logger.debug(String.format("Executing clean up in DataStore: [%s].", dsMo.getName()));
boolean expandDatastore = Boolean.parseBoolean(details.get(DiskTO.EXPAND_DATASTORE));
// reserve value in use is set to the minimum for the cloned volume), but that's fine.
if (expandDatastore) {
expandDatastore(hostDatastoreSystem, dsMo);
}
String vmdk = details.get(DiskTO.VMDK);
String fullVmdkPath = new DatastoreFile(dsMo.getName(), vmdk).getPath();
VmwareContext context = hostService.getServiceContext(null);
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
String vmName = getVmName(vmdk);
// If vmName is not null, then move all VMDK files out of this folder to the root folder and then delete the folder named vmName.
if (vmName != null) {
String workerVmName = hostService.getWorkerName(context, cmd, 0, dsMo);
VirtualMachineMO vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, workerVmName, null);
if (vmMo == null) {
throw new Exception("Unable to create a worker VM for volume creation");
}
vmMo.attachDisk(new String[] { fullVmdkPath }, dsMo.getMor());
List<String> backingFiles = new ArrayList<>(1);
List<VirtualDisk> virtualDisks = vmMo.getVirtualDisks();
VirtualDisk virtualDisk = virtualDisks.get(0);
VirtualDeviceBackingInfo virtualDeviceBackingInfo = virtualDisk.getBacking();
while (virtualDeviceBackingInfo instanceof VirtualDiskFlatVer2BackingInfo) {
VirtualDiskFlatVer2BackingInfo backingInfo = (VirtualDiskFlatVer2BackingInfo) virtualDeviceBackingInfo;
backingFiles.add(backingInfo.getFileName());
virtualDeviceBackingInfo = backingInfo.getParent();
}
vmMo.detachAllDisksAndDestroy();
VmwareStorageLayoutHelper.moveVolumeToRootFolder(dcMo, backingFiles);
vmdk = new DatastoreFile(vmdk).getFileName();
// Delete the folder the VMDK file was in.
DatastoreFile folderToDelete = new DatastoreFile(dsMo.getName(), vmName);
dsMo.deleteFolder(folderToDelete.getPath(), dcMo.getMor());
}
return vmdk;
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected Answer execute(CheckVirtualMachineCommand cmd) {
final String vmName = cmd.getVmName();
PowerState powerState = PowerState.PowerUnknown;
Integer vncPort = null;
VmwareContext context = getServiceContext();
VmwareHypervisorHost hyperHost = getHyperHost(context);
try {
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
if (vmMo != null) {
powerState = getVmPowerState(vmMo);
return new CheckVirtualMachineAnswer(cmd, powerState, vncPort);
} else {
s_logger.warn("Can not find vm " + vmName + " to execute CheckVirtualMachineCommand");
return new CheckVirtualMachineAnswer(cmd, powerState, vncPort);
}
} catch (Throwable e) {
createLogMessageException(e, cmd);
return new CheckVirtualMachineAnswer(cmd, powerState, vncPort);
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected ScaleVmAnswer execute(ScaleVmCommand cmd) {
VmwareContext context = getServiceContext();
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
try {
VmwareHypervisorHost hyperHost = getHyperHost(context);
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
int ramMb = getReservedMemoryMb(vmSpec);
long hotaddIncrementSizeInMb;
long hotaddMemoryLimitInMb;
long requestedMaxMemoryInMb = vmSpec.getMaxRam() / (1024 * 1024);
// Check if VM is really running on hypervisor host
if (getVmPowerState(vmMo) != PowerState.PowerOn) {
throw new CloudRuntimeException("Found that the VM " + vmMo.getVmName() + " is not running. Unable to scale-up this VM");
}
// Check max hot add limit
hotaddIncrementSizeInMb = vmMo.getHotAddMemoryIncrementSizeInMb();
hotaddMemoryLimitInMb = vmMo.getHotAddMemoryLimitInMb();
if (requestedMaxMemoryInMb > hotaddMemoryLimitInMb) {
throw new CloudRuntimeException("Memory of VM " + vmMo.getVmName() + " cannot be scaled to " + requestedMaxMemoryInMb + "MB." + " Requested memory limit is beyond the hotadd memory limit for this VM at the moment is " + hotaddMemoryLimitInMb + "MB.");
}
// Check increment is multiple of increment size
long reminder = hotaddIncrementSizeInMb > 0 ? requestedMaxMemoryInMb % hotaddIncrementSizeInMb : 0;
if (reminder != 0) {
requestedMaxMemoryInMb = requestedMaxMemoryInMb + hotaddIncrementSizeInMb - reminder;
}
// Check if license supports the feature
VmwareHelper.isFeatureLicensed(hyperHost, FeatureKeyConstants.HOTPLUG);
VmwareHelper.setVmScaleUpConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), getReservedCpuMHZ(vmSpec), (int) requestedMaxMemoryInMb, ramMb, vmSpec.getLimitCpuUse());
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Unable to execute ScaleVmCommand");
}
} catch (Exception e) {
s_logger.error(String.format("ScaleVmCommand failed due to: [%s].", VmwareHelper.getExceptionMessage(e)), e);
return new ScaleVmAnswer(cmd, false, String.format("Unable to execute ScaleVmCommand due to: [%s].", e.toString()));
}
return new ScaleVmAnswer(cmd, true, null);
}
Aggregations