use of com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost in project cloudstack by apache.
the class VmwareStorageManagerImpl method execute.
@Override
public Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd) {
String secondaryStoragePoolURL = cmd.getSecondaryStorageUrl();
String volumePath = cmd.getVolumePath();
Long accountId = cmd.getAccountId();
Long templateId = cmd.getTemplateId();
String details = null;
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()) {
s_logger.debug("Unable to find the owner VM for CreatePrivateTemplateFromVolumeCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter");
}
vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName());
if (vmMo == null) {
String msg = "Unable to find the owner VM for volume operation. vm: " + cmd.getVmName();
s_logger.error(msg);
throw new Exception(msg);
}
}
Ternary<String, Long, Long> result = createTemplateFromVolume(vmMo, accountId, templateId, cmd.getUniqueName(), secondaryStoragePoolURL, volumePath, hostService.getWorkerName(context, cmd, 0, null), cmd.getNfsVersion());
return new CreatePrivateTemplateAnswer(cmd, true, null, result.first(), result.third(), result.second(), cmd.getUniqueName(), ImageFormat.OVA);
} catch (Throwable e) {
return new CreatePrivateTemplateAnswer(cmd, false, hostService.createLogMessageException(e, cmd));
}
}
use of com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost in project cloudstack by apache.
the class VmwareStorageProcessor method deleteVolume.
@Override
public Answer deleteVolume(DeleteCommand 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();
DatacenterMO dcMo = new DatacenterMO(context, morDc);
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
vmMo = dcMo.findVm(vmName);
}
List<Map<String, String>> dynamicTargetsToRemove = null;
boolean deployAsIs = vol.isDeployAsIs();
if (vmMo != null) {
if (s_logger.isInfoEnabled()) {
if (deployAsIs) {
s_logger.info("Destroying root volume " + vol.getPath() + " of deploy-as-is VM " + vmName);
} else {
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> managedDatastoreNames = getManagedDatastoreNamesFromVirtualDisks(virtualDisks);
// Preserve other disks of the VM
List<String> detachedDisks = vmMo.detachAllDisksExcept(vol.getPath(), diskInfo != null ? diskInfo.getDiskDeviceBusName() : null);
VmwareStorageLayoutHelper.moveVolumeToRootFolder(new DatacenterMO(context, morDc), detachedDisks);
// vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class });
if (isManaged) {
vmMo.unregisterVm();
} else {
vmMo.destroy();
}
// this.hostService.handleDatastoreAndVmdkDetach(iScsiName, storageHost, storagePort);
if (managedDatastoreNames != null && !managedDatastoreNames.isEmpty()) {
removeManagedTargetsFromCluster(managedDatastoreNames);
}
for (NetworkDetails netDetails : networks) {
if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) {
if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) {
resource.cleanupNetwork(dcMo, netDetails);
}
}
}
} else if (deployAsIs) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroying root volume " + vol.getPath() + " of already removed deploy-as-is VM " + vmName);
}
// The disks of the deploy-as-is VM have been detached from the VM and moved to root folder
String deployAsIsRootDiskPath = dsMo.searchFileInSubFolders(vol.getPath() + VmwareResource.VMDK_EXTENSION, true, null);
if (StringUtils.isNotBlank(deployAsIsRootDiskPath)) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Removing disk " + deployAsIsRootDiskPath);
}
dsMo.deleteFile(deployAsIsRootDiskPath, morDc, true);
String deltaFilePath = dsMo.searchFileInSubFolders(vol.getPath() + "-delta" + VmwareResource.VMDK_EXTENSION, true, null);
if (StringUtils.isNotBlank(deltaFilePath)) {
dsMo.deleteFile(deltaFilePath, morDc, true);
}
}
}
return new Answer(cmd, true, "");
}
if (s_logger.isInfoEnabled()) {
s_logger.info("Destroy root volume directly from datastore");
}
}
if (!isManaged) {
VmwareStorageLayoutHelper.deleteVolumeVmdkFiles(dsMo, vol.getPath(), new DatacenterMO(context, morDc), VmwareManager.s_vmwareSearchExcludeFolder.value());
}
return new Answer(cmd, true, "Success");
} catch (Throwable e) {
return new Answer(cmd, false, hostService.createLogMessageException(e, cmd));
}
}
use of com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost in project cloudstack by apache.
the class VmwareStorageProcessor method createVmdk.
private void createVmdk(Command cmd, DatastoreMO dsMo, String vmdkDatastorePath, Long volumeSize) throws Exception {
VmwareContext context = hostService.getServiceContext(null);
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
String dummyVmName = hostService.getWorkerName(context, cmd, 0, dsMo);
VirtualMachineMO vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, dummyVmName, null);
if (vmMo == null) {
throw new Exception("Unable to create a dummy VM for volume creation");
}
Long volumeSizeToUse = volumeSize < dsMo.getDatastoreSummary().getFreeSpace() ? volumeSize : dsMo.getDatastoreSummary().getFreeSpace();
vmMo.createDisk(vmdkDatastorePath, getMBsFromBytes(volumeSizeToUse), dsMo.getMor(), vmMo.getScsiDeviceControllerKey(), null);
vmMo.detachDisk(vmdkDatastorePath, false);
vmMo.destroy();
}
use of com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost in project cloudstack by apache.
the class VmwareStorageProcessor method attachIso.
private Answer attachIso(DiskTO disk, boolean isAttach, String vmName, boolean force) {
try {
VmwareContext context = hostService.getServiceContext(null);
VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
if (vmMo == null) {
String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + vmName;
s_logger.error(msg);
throw new Exception(msg);
}
TemplateObjectTO iso = (TemplateObjectTO) disk.getData();
NfsTO nfsImageStore = (NfsTO) iso.getDataStore();
String storeUrl = null;
if (nfsImageStore != null) {
storeUrl = nfsImageStore.getUrl();
}
if (storeUrl == null) {
if (!iso.getName().equalsIgnoreCase(TemplateManager.VMWARE_TOOLS_ISO)) {
String msg = "ISO store root url is not found in AttachIsoCommand";
s_logger.error(msg);
throw new Exception(msg);
} else {
if (isAttach) {
vmMo.mountToolsInstaller();
} else {
try {
if (!vmMo.unmountToolsInstaller()) {
return new AttachAnswer("Failed to unmount vmware-tools installer ISO as the corresponding CDROM device is locked by VM. Please unmount the CDROM device inside the VM and ret-try.");
}
} catch (Throwable e) {
vmMo.detachIso(null, force);
}
}
return new AttachAnswer(disk);
}
}
ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl);
String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath();
if (!isoPath.startsWith(storeUrl)) {
assert (false);
String msg = "ISO path does not start with the secondary storage root";
s_logger.error(msg);
throw new Exception(msg);
}
int isoNameStartPos = isoPath.lastIndexOf('/');
String isoFileName = isoPath.substring(isoNameStartPos + 1);
String isoStorePathFromRoot = isoPath.substring(storeUrl.length() + 1, isoNameStartPos);
// TODO, check if iso is already attached, or if there is a previous
// attachment
DatastoreMO secondaryDsMo = new DatastoreMO(context, morSecondaryDs);
String storeName = secondaryDsMo.getName();
String isoDatastorePath = String.format("[%s] %s/%s", storeName, isoStorePathFromRoot, isoFileName);
if (isAttach) {
vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false, force);
} else {
vmMo.detachIso(isoDatastorePath, force);
}
return new AttachAnswer(disk);
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
hostService.invalidateServiceContext(null);
}
String message = String.format("AttachIsoCommand(%s) failed due to: [%s]. Also check if your guest os is a supported version", isAttach ? "attach" : "detach", VmwareHelper.getExceptionMessage(e));
s_logger.error(message, e);
return new AttachAnswer(message);
}
}
use of com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost 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));
}
}
Aggregations