use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected Answer execute(GetVncPortCommand cmd) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd));
}
try {
VmwareContext context = getServiceContext();
VmwareHypervisorHost hyperHost = getHyperHost(context);
assert (hyperHost instanceof HostMO);
VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName());
if (vmMo == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the owner VM for GetVncPortCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter");
}
vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName());
if (vmMo == null) {
throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName());
}
}
Pair<String, Integer> portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO) hyperHost));
if (s_logger.isTraceEnabled()) {
s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second());
}
return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second());
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
invalidateServiceContext();
}
String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg, e);
return new GetVncPortAnswer(cmd, msg);
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
private Answer execute(ResizeVolumeCommand cmd) {
String path = cmd.getPath();
String vmName = cmd.getInstanceName();
long newSize = cmd.getNewSize() / 1024;
long oldSize = cmd.getCurrentSize() / 1024;
boolean useWorkerVm = false;
VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
String poolId = cmd.getPoolUuid();
VirtualMachineMO vmMo = null;
DatastoreMO dsMo = null;
ManagedObjectReference morDS = null;
String vmdkDataStorePath = null;
try {
if (newSize < oldSize) {
throw new Exception("VMware doesn't support shrinking volume from larger size: " + oldSize / (1024 * 1024) + " GB to a smaller size: " + newSize / (1024 * 1024) + " GB");
} else if (newSize == oldSize) {
return new ResizeVolumeAnswer(cmd, true, "success", newSize * 1024);
}
if (vmName.equalsIgnoreCase("none")) {
// we need to spawn a worker VM to attach the volume to and
// resize the volume.
useWorkerVm = true;
vmName = getWorkerName(getServiceContext(), cmd, 0);
morDS = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolId);
dsMo = new DatastoreMO(hyperHost.getContext(), morDS);
s_logger.info("Create worker VM " + vmName);
vmMo = HypervisorHostHelper.createWorkerVM(hyperHost, dsMo, vmName);
if (vmMo == null) {
throw new Exception("Unable to create a worker VM for volume resize");
}
synchronized (this) {
vmdkDataStorePath = VmwareStorageLayoutHelper.getLegacyDatastorePathFromVmdkFileName(dsMo, path + ".vmdk");
vmMo.attachDisk(new String[] { vmdkDataStorePath }, morDS);
}
}
// find VM through datacenter (VM is not at the target host yet)
vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
if (vmMo == null) {
String msg = "VM " + vmName + " does not exist in VMware datacenter";
s_logger.error(msg);
throw new Exception(msg);
}
Pair<VirtualDisk, String> vdisk = vmMo.getDiskDevice(path);
if (vdisk == null) {
if (s_logger.isTraceEnabled())
s_logger.trace("resize volume done (failed)");
throw new Exception("No such disk device: " + path);
}
// IDE virtual disk cannot be re-sized if VM is running
if (vdisk.second() != null && vdisk.second().contains("ide")) {
throw new Exception("Re-sizing a virtual disk over IDE controller is not supported in VMware hypervisor. " + "Please re-try when virtual disk is attached to a VM using SCSI controller.");
}
if (vdisk.second() != null && !vdisk.second().toLowerCase().startsWith("scsi")) {
s_logger.error("Unsupported disk device bus " + vdisk.second());
throw new Exception("Unsupported disk device bus " + vdisk.second());
}
VirtualDisk disk = vdisk.first();
if ((VirtualDiskFlatVer2BackingInfo) disk.getBacking() != null && ((VirtualDiskFlatVer2BackingInfo) disk.getBacking()).getParent() != null) {
s_logger.error("Resize is not supported because Disk device has Parent " + ((VirtualDiskFlatVer2BackingInfo) disk.getBacking()).getParent().getUuid());
throw new Exception("Resize is not supported because Disk device has Parent " + ((VirtualDiskFlatVer2BackingInfo) disk.getBacking()).getParent().getUuid());
}
String vmdkAbsFile = getAbsoluteVmdkFile(disk);
if (vmdkAbsFile != null && !vmdkAbsFile.isEmpty()) {
vmMo.updateAdapterTypeIfRequired(vmdkAbsFile);
}
disk.setCapacityInKB(newSize);
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(disk);
deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure VM to resize disk. vmName: " + vmName);
}
return new ResizeVolumeAnswer(cmd, true, "success", newSize * 1024);
} catch (Exception e) {
s_logger.error("Unable to resize volume", e);
String error = "Failed to resize volume: " + e.getMessage();
return new ResizeVolumeAnswer(cmd, false, error);
} finally {
try {
if (useWorkerVm == true) {
s_logger.info("Destroy worker VM after volume resize");
vmMo.detachDisk(vmdkDataStorePath, false);
vmMo.destroy();
}
} catch (Throwable e) {
s_logger.info("Failed to destroy worker VM: " + vmName);
}
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project CloudStack-archive by CloudStack-extras.
the class VmwareHelper method pickOneVmOnRunningHost.
public static VirtualMachineMO pickOneVmOnRunningHost(List<VirtualMachineMO> vmList, boolean bFirstFit) throws Exception {
List<VirtualMachineMO> candidates = new ArrayList<VirtualMachineMO>();
for (VirtualMachineMO vmMo : vmList) {
HostMO hostMo = vmMo.getRunningHost();
if (hostMo.isHyperHostConnected())
candidates.add(vmMo);
}
if (candidates.size() == 0)
return null;
if (bFirstFit)
return candidates.get(0);
Random random = new Random();
return candidates.get(random.nextInt(candidates.size()));
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method execute.
protected Answer execute(AttachIsoCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(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("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 Answer(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);
}
}
return new Answer(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(), isoNameStartPos);
// 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);
} else {
vmMo.detachIso(isoDatastorePath);
}
return new Answer(cmd);
} catch (Throwable e) {
if (e instanceof RemoteException) {
s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
invalidateServiceContext();
}
if (cmd.isAttach()) {
String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg, e);
return new Answer(cmd, false, msg);
} else {
String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e);
s_logger.warn(msg, e);
return new Answer(cmd, false, msg);
}
}
}
use of com.cloud.hypervisor.vmware.mo.VirtualMachineMO in project cloudstack by apache.
the class VmwareResource method configureVnc.
protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception {
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
if (!mgr.beginExclusiveOperation(600))
throw new Exception("Unable to begin exclusive operation, lock time out");
try {
int maxVncPorts = 64;
int vncPort = 0;
Random random = new Random();
HostMO vmOwnerHost = vmMo.getRunningHost();
ManagedObjectReference morParent = vmOwnerHost.getParentMor();
HashMap<String, Integer> portInfo;
if (morParent.getType().equalsIgnoreCase("ClusterComputeResource")) {
ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent);
portInfo = clusterMo.getVmVncPortsOnCluster();
} else {
portInfo = vmOwnerHost.getVmVncPortsOnHost();
}
// allocate first at 5900 - 5964 range
Collection<Integer> existingPorts = portInfo.values();
int val = random.nextInt(maxVncPorts);
int startVal = val;
do {
if (!existingPorts.contains(5900 + val)) {
vncPort = 5900 + val;
break;
}
val = (++val) % maxVncPorts;
} while (val != startVal);
if (vncPort == 0) {
s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000");
Pair<Integer, Integer> additionalRange = mgr.getAddiionalVncPortRange();
maxVncPorts = additionalRange.second();
val = random.nextInt(maxVncPorts);
startVal = val;
do {
if (!existingPorts.contains(additionalRange.first() + val)) {
vncPort = additionalRange.first() + val;
break;
}
val = (++val) % maxVncPorts;
} while (val != startVal);
}
if (vncPort == 0) {
throw new Exception("Unable to find an available VNC port on host");
}
if (s_logger.isInfoEnabled()) {
s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName());
}
return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout);
} finally {
try {
mgr.endExclusiveOperation();
} catch (Throwable e) {
assert (false);
s_logger.error("Unexpected exception ", e);
}
}
}
Aggregations