use of com.vmware.vim25.VirtualMachineRuntimeInfo in project cloudstack by apache.
the class VirtualMachineMO method powerOn.
public boolean powerOn() throws Exception {
if (getResetSafePowerState() == VirtualMachinePowerState.POWERED_ON)
return true;
ManagedObjectReference morTask = _context.getService().powerOnVMTask(_mor, null);
// Monitor VM questions
final Boolean[] flags = { false };
final VirtualMachineMO vmMo = this;
Future<?> future = MonitorServiceExecutor.submit(new Runnable() {
@Override
public void run() {
s_logger.info("VM Question monitor started...");
while (!flags[0]) {
try {
VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo();
VirtualMachineQuestionInfo question = runtimeInfo.getQuestion();
if (question != null) {
s_logger.info("Question id: " + question.getId());
s_logger.info("Question text: " + question.getText());
if (question.getMessage() != null) {
for (VirtualMachineMessage msg : question.getMessage()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("msg id: " + msg.getId());
s_logger.info("msg text: " + msg.getText());
}
String logMsg = "Found that VM has a pending question that we need to answer programmatically, question id: " + msg.getId();
if ("msg.uuid.altered".equalsIgnoreCase(msg.getId())) {
s_logger.info(logMsg + ", we will automatically answer as 'moved it' to address out of band HA for the VM");
vmMo.answerVM(question.getId(), "1");
break;
} else if (msg.getId().equalsIgnoreCase("msg.cpuid.noVHVQuestion")) {
s_logger.info(logMsg + ", automatically answering 'yes'");
vmMo.answerVM(question.getId(), "0");
break;
}
}
}
if (s_logger.isTraceEnabled())
s_logger.trace("These are the choices we can have just in case");
ChoiceOption choice = question.getChoice();
if (choice != null) {
for (ElementDescription info : choice.getChoiceInfo()) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Choice option key: " + info.getKey());
s_logger.trace("Choice option label: " + info.getLabel());
}
}
}
}
} catch (Throwable e) {
s_logger.error("Unexpected exception: ", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
s_logger.debug("[ignored] interupted while dealing with vm questions.");
}
}
s_logger.info("VM Question monitor stopped");
}
});
try {
boolean result = _context.getVimClient().waitForTask(morTask);
if (result) {
_context.waitForTaskProgressDone(morTask);
return true;
} else {
s_logger.error("VMware powerOnVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
} finally {
// make sure to let VM question monitor exit
flags[0] = true;
}
return false;
}
use of com.vmware.vim25.VirtualMachineRuntimeInfo in project cloudstack by apache.
the class VirtualMachineMO method createFullCloneWithSpecificDisk.
public VirtualMachineMO createFullCloneWithSpecificDisk(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, VirtualDisk requiredDisk) throws Exception {
assert (morFolder != null);
assert (morResourcePool != null);
VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo();
HostMO hostMo = new HostMO(_context, runtimeInfo.getHost());
DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter());
DatastoreMO dsMo = new DatastoreMO(_context, morResourcePool);
VirtualMachineRelocateSpec rSpec = new VirtualMachineRelocateSpec();
VirtualDisk[] vmDisks = getAllDiskDevice();
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
s_logger.debug(String.format("Removing the disks other than the required disk with key %s to the cloned VM", requiredDisk.getKey()));
for (VirtualDisk disk : vmDisks) {
s_logger.debug(String.format("Original disk with key %s found in the VM %s", disk.getKey(), getName()));
if (requiredDisk.getKey() != disk.getKey()) {
VirtualDeviceConfigSpec virtualDeviceConfigSpec = new VirtualDeviceConfigSpec();
virtualDeviceConfigSpec.setDevice(disk);
virtualDeviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
vmConfigSpec.getDeviceChange().add(virtualDeviceConfigSpec);
}
}
rSpec.setPool(morResourcePool);
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
cloneSpec.setPowerOn(false);
cloneSpec.setTemplate(false);
cloneSpec.setLocation(rSpec);
cloneSpec.setMemory(false);
cloneSpec.setConfig(vmConfigSpec);
ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec);
boolean result = _context.getVimClient().waitForTask(morTask);
if (result) {
_context.waitForTaskProgressDone(morTask);
VirtualMachineMO clonedVm = dcMo.findVm(cloneName);
if (clonedVm == null) {
s_logger.error(String.format("Failed to clone VM %s", cloneName));
return null;
}
s_logger.debug(String.format("Cloned VM: %s as %s", getName(), cloneName));
clonedVm.tagAsWorkerVM();
makeSureVMHasOnlyRequiredDisk(clonedVm, requiredDisk, dsMo, dcMo);
return clonedVm;
} else {
s_logger.error("VMware cloneVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
return null;
}
}
use of com.vmware.vim25.VirtualMachineRuntimeInfo in project cloudstack by apache.
the class VirtualMachineMO method exportVm.
public void exportVm(String exportDir, String exportName, boolean packToOva, boolean leaveOvaFileOnly) throws Exception {
ManagedObjectReference morOvf = _context.getServiceContent().getOvfManager();
VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo();
HostMO hostMo = new HostMO(_context, runtimeInfo.getHost());
String hostName = hostMo.getHostName();
String vmName = getVmName();
DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter());
if (runtimeInfo.getPowerState() != VirtualMachinePowerState.POWERED_OFF) {
String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName;
s_logger.error(msg);
throw new Exception(msg);
}
ManagedObjectReference morLease = _context.getService().exportVm(getMor());
if (morLease == null) {
s_logger.error("exportVm() failed");
throw new Exception("exportVm() failed");
}
HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(_context, morLease);
HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
try {
if (state == HttpNfcLeaseState.READY) {
final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
boolean success = false;
List<String> fileNames = new ArrayList<String>();
try {
HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo();
final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024;
long totalBytesDownloaded = 0;
List<HttpNfcLeaseDeviceUrl> deviceUrls = leaseInfo.getDeviceUrl();
s_logger.info("volss: copy vmdk and ovf file starts " + System.currentTimeMillis());
if (deviceUrls != null) {
OvfFile[] ovfFiles = new OvfFile[deviceUrls.size()];
for (int i = 0; i < deviceUrls.size(); i++) {
String deviceId = deviceUrls.get(i).getKey();
String deviceUrlStr = deviceUrls.get(i).getUrl();
String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1);
String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk"));
String diskUrlStr = deviceUrlStr.replace("*", hostName);
diskUrlStr = HypervisorHostHelper.resolveHostNameInUrl(dcMo, diskUrlStr);
String diskLocalPath = exportDir + File.separator + diskFileName;
fileNames.add(diskLocalPath);
if (s_logger.isInfoEnabled()) {
s_logger.info("Download VMDK file for export. url: " + deviceUrlStr);
}
long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded, new ActionDelegate<Long>() {
@Override
public void action(Long param) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Download progress " + param + "/" + toHumanReadableSize(totalBytes));
}
progressReporter.reportProgress((int) (param * 100 / totalBytes));
}
});
totalBytesDownloaded += lengthOfDiskFile;
OvfFile ovfFile = new OvfFile();
ovfFile.setPath(diskFileName);
ovfFile.setDeviceId(deviceId);
ovfFile.setSize(lengthOfDiskFile);
ovfFiles[i] = ovfFile;
}
// write OVF descriptor file
OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
ovfDescParams.getOvfFiles().addAll(Arrays.asList(ovfFiles));
OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams);
String ovfPath = exportDir + File.separator + exportName + ".ovf";
fileNames.add(ovfPath);
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(ovfPath), "UTF-8");
out.write(ovfCreateDescriptorResult.getOvfDescriptor());
out.close();
// tar files into OVA
if (packToOva) {
// Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature)
s_logger.info("Sync file system before we package OVA...");
Script commandSync = new Script(true, "sync", 0, s_logger);
commandSync.execute();
Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(exportDir);
command.add("-cf", exportName + ".ova");
// OVF file should be the first file in OVA archive
command.add(exportName + ".ovf");
for (String name : fileNames) {
command.add((new File(name).getName()));
}
s_logger.info("Package OVA with command: " + command.toString());
command.execute();
// to be safe, physically test existence of the target OVA file
if ((new File(exportDir + File.separator + exportName + ".ova")).exists()) {
success = true;
} else {
s_logger.error(exportDir + File.separator + exportName + ".ova is not created as expected");
}
} else {
success = true;
}
}
s_logger.info("volss: copy vmdk and ovf file finished " + System.currentTimeMillis());
} catch (Throwable e) {
s_logger.error("Unexpected exception ", e);
} finally {
progressReporter.close();
if (leaveOvaFileOnly) {
for (String name : fileNames) {
new File(name).delete();
}
}
if (!success)
throw new Exception("Unable to finish the whole process to package as a OVA file");
}
}
} finally {
leaseMo.updateLeaseProgress(100);
leaseMo.completeLease();
}
}
Aggregations