use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO 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();
String searchExcludedFolders = cmd.getContextParam("searchexludefolders");
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 vmName = volume.getVmName();
String vmdkFileBaseName = null;
if (template.isDeployAsIs() && volume.getVolumeType() == Volume.Type.ROOT) {
VirtualMachineMO existingVm = dcMo.findVm(vmName);
if (volume.getDeviceId().equals(0L)) {
if (existingVm != null) {
s_logger.info(String.format("Found existing VM wth name [%s] before cloning from template, destroying it", vmName));
existingVm.detachAllDisksAndDestroy();
}
s_logger.info("ROOT Volume from deploy-as-is template, cloning template");
cloneVMFromTemplate(hyperHost, template.getPath(), vmName, primaryStore.getUuid());
} else {
s_logger.info("ROOT Volume from deploy-as-is template, volume already created at this point");
}
} else {
if (srcStore == null) {
// create a root volume for blank VM (created from ISO)
String dummyVmName = hostService.getWorkerName(context, cmd, 0, dsMo);
try {
vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, dummyVmName, null);
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, searchExcludedFolders);
vmMo.createDisk(volumeDatastorePath, (long) (volume.getSize() / (1024L * 1024L)), morDatastore, -1, null);
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.detachAllDisksAndDestroy();
}
}
} 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");
}
if (dsMo.getDatastoreType().equalsIgnoreCase("VVOL")) {
vmdkFileBaseName = cloneVMforVvols(context, hyperHost, template, vmTemplate, volume, dcMo, dsMo);
} else {
vmdkFileBaseName = createVMAndFolderWithVMName(context, hyperHost, template, vmTemplate, volume, dcMo, dsMo, searchExcludedFolders);
}
}
// restoreVM - move the new ROOT disk into corresponding VM folder
VirtualMachineMO restoreVmMo = dcMo.findVm(volume.getVmName());
if (restoreVmMo != null) {
if (!dsMo.getDatastoreType().equalsIgnoreCase("VVOL")) {
// 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, searchExcludedFolders);
}
}
}
}
VolumeObjectTO newVol = new VolumeObjectTO();
newVol.setPath(vmdkFileBaseName);
if (template.isDeployAsIs()) {
newVol.setSize(volume.getSize());
} else if (template.getSize() != null) {
newVol.setSize(template.getSize());
} else {
newVol.setSize(volume.getSize());
}
return new CopyCmdAnswer(newVol);
} 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 createTemplateFromVolume.
private Ternary<String, Long, Long> createTemplateFromVolume(VmwareContext context, VirtualMachineMO vmMo, VmwareHypervisorHost hyperHost, String installPath, long templateId, String templateUniqueName, String secStorageUrl, String volumePath, String workerVmName, String nfsVersion) throws Exception {
String secondaryMountPoint = mountService.getMountPoint(secStorageUrl, nfsVersion);
String installFullPath = secondaryMountPoint + "/" + installPath;
synchronized (installPath.intern()) {
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: " + 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);
if (volumeDeviceInfo == null) {
String msg = "Unable to find related disk device for volume. volume path: " + volumePath;
s_logger.error(msg);
throw new Exception(msg);
}
DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool();
VirtualDisk requiredDisk = volumeDeviceInfo.first();
clonedVm = vmMo.createFullCloneWithSpecificDisk(templateUniqueName, dcMo.getVmFolder(), morPool, requiredDisk);
if (clonedVm == null) {
throw new Exception(String.format("Failed to clone VM with name %s during create template from volume operation", templateUniqueName));
}
clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, false, false);
// Get VMDK filename
String templateVMDKName = "";
File[] files = new File(installFullPath).listFiles();
if (files != null) {
for (File file : files) {
String fileName = file.getName();
if (fileName.toLowerCase().startsWith(templateUniqueName) && fileName.toLowerCase().endsWith(".vmdk")) {
templateVMDKName += fileName;
break;
}
}
}
long physicalSize = new File(installFullPath + "/" + templateVMDKName).length();
OVAProcessor processor = new OVAProcessor();
Map<String, Object> params = new HashMap<>();
params.put(StorageLayer.InstanceConfigKey, _storage);
processor.configure("OVA Processor", params);
long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName);
postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);
writeMetaOvaForTemplate(installFullPath, templateUniqueName + ".ovf", templateVMDKName, templateUniqueName, physicalSize);
return new Ternary<String, Long, Long>(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize);
} finally {
if (clonedVm != null) {
s_logger.debug(String.format("Destroying cloned VM: %s with its disks", clonedVm.getName()));
clonedVm.destroy();
}
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected AttachIsoAnswer execute(AttachIsoCommand cmd) {
try {
VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
if (vmMo == null) {
String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName();
s_logger.error(msg);
throw new Exception(msg);
}
String storeUrl = cmd.getStoreUrl();
if (storeUrl == null) {
if (!cmd.getIsoPath().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 (cmd.isAttach()) {
vmMo.mountToolsInstaller();
} else {
try {
if (!vmMo.unmountToolsInstaller()) {
return new AttachIsoAnswer(cmd, false, "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, cmd.isForce());
}
}
return new AttachIsoAnswer(cmd);
}
}
ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl);
String isoPath = cmd.getIsoPath();
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 + 1);
// TODO, check if iso is already attached, or if there is a previous
// attachment
DatastoreMO secondaryDsMo = new DatastoreMO(getServiceContext(), morSecondaryDs);
String storeName = secondaryDsMo.getName();
String isoDatastorePath = String.format("[%s] %s%s", storeName, isoStorePathFromRoot, isoFileName);
if (cmd.isAttach()) {
vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false, cmd.getDeviceKey(), cmd.isForce());
return new AttachIsoAnswer(cmd);
} else {
int key = vmMo.detachIso(isoDatastorePath, cmd.isForce());
return new AttachIsoAnswer(cmd, key);
}
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
invalidateServiceContext();
}
String message = String.format("AttachIsoCommand(%s) failed due to [%s].", cmd.isAttach() ? "attach" : "detach", VmwareHelper.getExceptionMessage(e));
s_logger.error(message, e);
return new AttachIsoAnswer(cmd, false, message);
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected Answer execute(GetVmDiskStatsCommand cmd) {
try {
final VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
final ManagedObjectReference perfMgr = getServiceContext().getServiceContent().getPerfManager();
VimPortType service = getServiceContext().getService();
Integer windowInterval = getVmwareWindowTimeInterval();
final XMLGregorianCalendar startTime = VmwareHelper.getXMLGregorianCalendar(new Date(), windowInterval);
final XMLGregorianCalendar endTime = VmwareHelper.getXMLGregorianCalendar(new Date(), 0);
PerfCounterInfo diskReadIOPerfCounterInfo = null;
PerfCounterInfo diskWriteIOPerfCounterInfo = null;
PerfCounterInfo diskReadKbsPerfCounterInfo = null;
PerfCounterInfo diskWriteKbsPerfCounterInfo = null;
// https://pubs.vmware.com/vsphere-5-5/topic/com.vmware.wssdk.apiref.doc/virtual_disk_counters.html
List<PerfCounterInfo> cInfo = getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter");
for (PerfCounterInfo info : cInfo) {
if ("virtualdisk".equalsIgnoreCase(info.getGroupInfo().getKey()) && "average".equalsIgnoreCase(info.getRollupType().value())) {
if ("numberReadAveraged".equalsIgnoreCase(info.getNameInfo().getKey())) {
diskReadIOPerfCounterInfo = info;
}
if ("numberWriteAveraged".equalsIgnoreCase(info.getNameInfo().getKey())) {
diskWriteIOPerfCounterInfo = info;
}
if ("read".equalsIgnoreCase(info.getNameInfo().getKey())) {
diskReadKbsPerfCounterInfo = info;
}
if ("write".equalsIgnoreCase(info.getNameInfo().getKey())) {
diskWriteKbsPerfCounterInfo = info;
}
}
}
final ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
final DatacenterMO dcMo = new DatacenterMO(getServiceContext(), dcMor);
final HashMap<String, List<VmDiskStatsEntry>> vmStatsMap = new HashMap<>();
for (final String vmName : cmd.getVmNames()) {
final VirtualMachineMO vmMo = dcMo.findVm(vmName);
final List<VmDiskStatsEntry> diskStats = new ArrayList<>();
for (final VirtualDisk disk : vmMo.getAllDiskDevice()) {
final String diskBusName = vmMo.getDeviceBusName(vmMo.getAllDeviceList(), disk);
long readReq = 0;
long readBytes = 0;
long writeReq = 0;
long writeBytes = 0;
final ArrayList<PerfMetricId> perfMetricsIds = new ArrayList<PerfMetricId>();
if (diskReadIOPerfCounterInfo != null) {
perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskReadIOPerfCounterInfo, diskBusName));
}
if (diskWriteIOPerfCounterInfo != null) {
perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskWriteIOPerfCounterInfo, diskBusName));
}
if (diskReadKbsPerfCounterInfo != null) {
perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskReadKbsPerfCounterInfo, diskBusName));
}
if (diskWriteKbsPerfCounterInfo != null) {
perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskWriteKbsPerfCounterInfo, diskBusName));
}
if (perfMetricsIds.size() > 0) {
try {
final PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(vmMo.getMor());
qSpec.setFormat("normal");
qSpec.setIntervalId(windowInterval);
qSpec.setStartTime(startTime);
qSpec.setEndTime(endTime);
qSpec.getMetricId().addAll(perfMetricsIds);
for (final PerfEntityMetricBase perfValue : service.queryPerf(perfMgr, Collections.singletonList(qSpec))) {
if (!(perfValue instanceof PerfEntityMetric)) {
continue;
}
final List<PerfMetricSeries> values = ((PerfEntityMetric) perfValue).getValue();
if (values == null || values.isEmpty()) {
continue;
}
for (final PerfMetricSeries value : values) {
if (!(value instanceof PerfMetricIntSeries) || !value.getId().getInstance().equals(diskBusName)) {
continue;
}
final List<Long> perfStats = ((PerfMetricIntSeries) value).getValue();
if (perfStats.size() > 0) {
long sum = 0;
for (long val : perfStats) {
sum += val;
}
long avg = sum / perfStats.size();
if (value.getId().getCounterId() == diskReadIOPerfCounterInfo.getKey()) {
readReq = avg;
} else if (value.getId().getCounterId() == diskWriteIOPerfCounterInfo.getKey()) {
writeReq = avg;
} else if (value.getId().getCounterId() == diskReadKbsPerfCounterInfo.getKey()) {
readBytes = avg * 1024;
} else if (value.getId().getCounterId() == diskWriteKbsPerfCounterInfo.getKey()) {
writeBytes = avg * 1024;
}
}
}
}
} catch (Exception e) {
s_logger.error(String.format("Unable to execute PerfQuerySpec due to: [%s]. The window interval is enabled in vCenter?", VmwareHelper.getExceptionMessage(e)), e);
}
}
diskStats.add(new VmDiskStatsEntry(vmName, VmwareHelper.getDiskDeviceFileName(disk), writeReq, readReq, writeBytes, readBytes));
}
if (CollectionUtils.isNotEmpty(diskStats)) {
vmStatsMap.put(vmName, diskStats);
}
}
s_logger.debug(String.format("VM Disks Maps is: [%s].", _gson.toJson(vmStatsMap)));
if (MapUtils.isNotEmpty(vmStatsMap)) {
return new GetVmDiskStatsAnswer(cmd, "", cmd.getHostName(), vmStatsMap);
}
} catch (Exception e) {
s_logger.error(String.format("Unable to execute GetVmDiskStatsCommand due to [%s].", VmwareHelper.getExceptionMessage(e)), e);
}
return new GetVmDiskStatsAnswer(cmd, null, null, null);
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected Answer execute(StopCommand cmd) {
// In the stop command, we're passed in the name of the VM as seen by cloudstack,
// i.e., i-x-y. This is the internal VM name.
VmwareContext context = getServiceContext();
VmwareHypervisorHost hyperHost = getHyperHost(context);
try {
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName());
if (vmMo != null) {
if (cmd.checkBeforeCleanup()) {
if (getVmPowerState(vmMo) != PowerState.PowerOff) {
String msg = "StopCommand is sent for cleanup and VM " + cmd.getVmName() + " is current running. ignore it.";
s_logger.warn(msg);
return new StopAnswer(cmd, msg, false);
} else {
String msg = "StopCommand is sent for cleanup and VM " + cmd.getVmName() + " is indeed stopped already.";
s_logger.info(msg);
return new StopAnswer(cmd, msg, true);
}
}
try {
vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, "0");
vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_VM_INTERNAL_NAME, cmd.getVmName());
if (getVmPowerState(vmMo) != PowerState.PowerOff) {
String msg = "Stop VM " + cmd.getVmName() + " Succeed";
boolean success = false;
if (cmd.isForceStop()) {
success = vmMo.powerOff();
} else {
success = vmMo.safePowerOff(_shutdownWaitMs);
}
if (!success) {
msg = "Have problem in powering off VM " + cmd.getVmName() + ", let the process continue";
s_logger.warn(msg);
}
return new StopAnswer(cmd, msg, true);
}
String msg = "VM " + cmd.getVmName() + " is already in stopped state";
s_logger.info(msg);
return new StopAnswer(cmd, msg, true);
} finally {
}
} else {
String msg = "VM " + cmd.getVmName() + " is no longer on the expected host in vSphere";
s_logger.info(msg);
return new StopAnswer(cmd, msg, true);
}
} catch (Exception e) {
return new StopAnswer(cmd, createLogMessageException(e, cmd), false);
}
}
Aggregations