use of com.vmware.vim25.mo.Task in project vsphere-cloud-plugin by jenkinsci.
the class VSphere method cloneOrDeployVm.
/**
* Creates a new VM by cloning an existing VM or Template.
*
* @param cloneName
* The name for the new VM.
* @param sourceName
* The name of the VM or Template that is to be cloned.
* @param linkedClone
* If true then the clone will be defined as a delta from the
* original, rather than a "full fat" copy. If this is true then
* you will need to use a snapshot.
* @param resourcePoolName
* (Optional) The name of the resource pool to use, or null.
* @param cluster
* (Optional) The name of the cluster, or null.
* @param datastoreName
* (Optional) The name of the data store, or null.
* @param folderName
* (Optional) The name or path of the VSphere folder, or null
* @param useCurrentSnapshot
* If true then the clone will be created from the source VM's
* "current" snapshot. This means that the VM <em>must</em> have
* at least one snapshot.
* @param namedSnapshot
* If set then the clone will be created from the source VM's
* snapshot of this name. If this is set then
* <code>useCurrentSnapshot</code> must not be set.
* @param powerOn
* If true then the new VM will be switched on after it has been
* created.
* @param extraConfigParameters
* (Optional) parameters to set in the VM's "extra config"
* object. This data can then be read back at a later stage.In
* the case of parameters whose name starts "guestinfo.", the
* parameter can be read by the VMware Tools on the client OS.
* e.g. a variable named "guestinfo.Foo" with value "Bar" could
* be read on the guest using the command-line
* <tt>vmtoolsd --cmd "info-get guestinfo.Foo"</tt>.
* @param customizationSpec
* (Optional) Customization spec to use for this VM, or null
* @param jLogger
* Where to log to.
* @throws VSphereException
* if anything goes wrong.
*/
public void cloneOrDeployVm(String cloneName, String sourceName, boolean linkedClone, String resourcePoolName, String cluster, String datastoreName, String folderName, boolean useCurrentSnapshot, final String namedSnapshot, boolean powerOn, Map<String, String> extraConfigParameters, String customizationSpec, PrintStream jLogger) throws VSphereException {
try {
final VirtualMachine sourceVm = getVmByName(sourceName);
if (sourceVm == null) {
throw new VSphereNotFoundException("VM or template", sourceName);
}
if (getVmByName(cloneName) != null) {
throw new VSphereDuplicateException("VM", cloneName);
}
final VirtualMachineConfigInfo vmConfig = sourceVm.getConfig();
final boolean sourceIsATemplate = vmConfig.template;
final String sourceType = sourceIsATemplate ? "Template" : "VM";
final VirtualMachineRelocateSpec rel = createRelocateSpec(jLogger, linkedClone, resourcePoolName, cluster, datastoreName, sourceIsATemplate);
final VirtualMachineCloneSpec cloneSpec = createCloneSpec(rel);
cloneSpec.setTemplate(false);
cloneSpec.powerOn = powerOn;
if (namedSnapshot != null && !namedSnapshot.isEmpty()) {
if (useCurrentSnapshot) {
throw new IllegalArgumentException("It is not valid to request a clone of " + sourceType + " \"" + sourceName + "\" based on its snapshot \"" + namedSnapshot + "\" AND also specify that the latest snapshot should be used. Either choose to use the latest snapshot, or name a snapshot, or neither, but not both.");
}
final VirtualMachineSnapshot namedVMSnapshot = getSnapshotInTree(sourceVm, namedSnapshot);
if (namedVMSnapshot == null) {
throw new VSphereNotFoundException("Snapshot", namedSnapshot, "Source " + sourceType + " \"" + sourceName + "\" has no snapshot called \"" + namedSnapshot + "\".");
}
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will be based on named snapshot \"" + namedSnapshot + "\".");
cloneSpec.setSnapshot(namedVMSnapshot.getMOR());
}
if (useCurrentSnapshot) {
final VirtualMachineSnapshot currentSnapShot = sourceVm.getCurrentSnapShot();
if (currentSnapShot == null) {
throw new VSphereNotFoundException("Snapshot", null, "Source " + sourceType + " \"" + sourceName + "\" requires at least one snapshot.");
}
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will be based on current snapshot \"" + currentSnapShot.toString() + "\".");
cloneSpec.setSnapshot(currentSnapShot.getMOR());
}
if (extraConfigParameters != null && !extraConfigParameters.isEmpty()) {
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will have extra configuration parameters " + extraConfigParameters + ".");
VirtualMachineConfigSpec cs = createVMConfigSpecFromExtraConfigParameters(extraConfigParameters);
cloneSpec.setConfig(cs);
}
if (customizationSpec != null && customizationSpec.length() > 0) {
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will use customization specification \"" + customizationSpec + "\".");
CustomizationSpecItem spec = getCustomizationSpecByName(customizationSpec);
cloneSpec.setCustomization(spec.getSpec());
}
Folder folder;
if (folderName == null || folderName.isEmpty() || folderName.equals(" ")) {
// same folder as source
folder = (Folder) sourceVm.getParent();
} else if (!folderExists(folderName)) {
folder = (Folder) sourceVm.getParent();
logMessage(jLogger, "Unable to find the specified folder. Creating VM in the same folder as its parent ");
} else {
folder = getFolder(folderName);
}
final Task task = sourceVm.cloneVM_Task(folder, cloneName, cloneSpec);
logMessage(jLogger, "Started cloning of " + sourceType + " \"" + sourceName + "\". Please wait ...");
final String status = task.waitForTask();
if (!TaskInfoState.success.toString().equals(status)) {
throw newVSphereException(task.getTaskInfo(), "Couldn't clone \"" + sourceName + "\". " + "Clone task ended with status " + status + ".");
}
logMessage(jLogger, "Successfully cloned VM \"" + sourceName + "\" to create \"" + cloneName + "\".");
} catch (RuntimeException | VSphereException e) {
throw e;
} catch (Exception e) {
throw new VSphereException(e);
}
}
use of com.vmware.vim25.mo.Task in project vsphere-cloud-plugin by jenkinsci.
the class VSphere method renameVm.
/**
* Renames the VM vSphere
* @param oldName the current name of the vm
* @param newName the new name of the vm
* @throws VSphereException If an error occurred.
*/
public void renameVm(String oldName, String newName) throws VSphereException {
try {
VirtualMachine vm = getVmByName(oldName);
if (vm == null) {
throw new VSphereNotFoundException("VM", oldName);
}
final Task task = vm.rename_Task(newName);
final String status = task.waitForTask();
if (status.equals(Task.SUCCESS)) {
LOGGER.log(Level.FINER, "VM was renamed successfully.");
return;
}
throw newVSphereException(task.getTaskInfo(), "Could not rename VM \"" + oldName + "\"!");
} catch (RuntimeException | VSphereException e) {
throw e;
} catch (Exception e) {
throw new VSphereException(e.getMessage(), e);
}
}
use of com.vmware.vim25.mo.Task in project vsphere-cloud-plugin by jenkinsci.
the class VSphere method reconfigureVm.
public void reconfigureVm(String name, VirtualMachineConfigSpec spec) throws VSphereException {
VirtualMachine vm = getVmByName(name);
if (vm == null) {
throw new VSphereNotFoundException("VM or template", name);
}
LOGGER.log(Level.FINER, "Reconfiguring VM. Please wait ...");
try {
Task task = vm.reconfigVM_Task(spec);
String status = task.waitForTask();
if (status.equals(TaskInfoState.success.toString())) {
return;
}
throw newVSphereException(task.getTaskInfo(), "Couldn't reconfigure \"" + name + "\"!");
} catch (RuntimeException | VSphereException e) {
throw e;
} catch (Exception e) {
throw new VSphereException("VM cannot be reconfigured:" + e.getMessage(), e);
}
}
use of com.vmware.vim25.mo.Task in project cloudstack by apache.
the class VmwareClient method cancelTask.
public void cancelTask(ManagedObjectReference task) throws Exception {
TaskInfo info = (TaskInfo) (getDynamicProperty(task, "info"));
if (info == null) {
s_logger.warn("Unable to get the task info, so couldn't cancel the task");
return;
}
String taskName = StringUtils.isNotBlank(info.getName()) ? info.getName() : "Unknown";
taskName += "(" + info.getKey() + ")";
String entityName = StringUtils.isNotBlank(info.getEntityName()) ? info.getEntityName() : "";
if (info.getState().equals(TaskInfoState.SUCCESS)) {
s_logger.debug(taskName + " task successfully completed for the entity " + entityName + ", can't cancel it");
return;
}
if (info.getState().equals(TaskInfoState.ERROR)) {
s_logger.debug(taskName + " task execution failed for the entity " + entityName + ", can't cancel it");
return;
}
s_logger.debug(taskName + " task pending for the entity " + entityName + ", trying to cancel");
if (!info.isCancelable()) {
s_logger.warn(taskName + " task will continue to run on vCenter because it can't be cancelled");
return;
}
s_logger.debug("Cancelling task " + taskName + " of the entity " + entityName);
getService().cancelTask(task);
// Since task cancellation is asynchronous, wait for the task to be cancelled
Object[] result = waitForValues(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } });
if (result != null && result.length == 2) {
// result for 2 properties: info.state, info.error
if (result[0].equals(TaskInfoState.SUCCESS)) {
s_logger.warn("Failed to cancel" + taskName + " task of the entity " + entityName + ", the task successfully completed");
}
if (result[1] instanceof LocalizedMethodFault) {
MethodFault fault = ((LocalizedMethodFault) result[1]).getFault();
if (fault instanceof RequestCanceled) {
s_logger.debug(taskName + " task of the entity " + entityName + " was successfully cancelled");
}
} else {
s_logger.warn("Couldn't cancel " + taskName + " task of the entity " + entityName + " due to " + ((LocalizedMethodFault) result[1]).getLocalizedMessage());
}
}
}
use of com.vmware.vim25.mo.Task in project cloudstack by apache.
the class HypervisorHostHelper method importVmFromOVF.
/**
* deploys a new VM from a ovf spec. It ignores network, defaults locale to 'US'
* @throws Exception shoud be a VmwareResourceException
*/
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost, String configurationId) throws CloudRuntimeException, IOException {
assert (morRp != null);
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
importSpecParams.setHostSystem(morHost);
importSpecParams.setLocale("US");
importSpecParams.setEntityName(vmName);
String deploymentOption = StringUtils.isNotBlank(configurationId) ? configurationId : "";
importSpecParams.setDeploymentOption(deploymentOption);
// diskOption: thin, thick, etc
importSpecParams.setDiskProvisioning(diskOption);
String ovfDescriptor = removeOVFNetwork(HttpNfcLeaseMO.readOvfContent(ovfFilePath));
VmwareContext context = host.getContext();
OvfCreateImportSpecResult ovfImportResult = null;
try {
ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
} catch (ConcurrentAccessFaultMsg | FileFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidStateFaultMsg | RuntimeFaultFaultMsg | TaskInProgressFaultMsg | VmConfigFaultFaultMsg error) {
throw new CloudRuntimeException("ImportSpec creation failed", error);
}
if (ovfImportResult == null) {
String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
if (!ovfImportResult.getError().isEmpty()) {
for (LocalizedMethodFault fault : ovfImportResult.getError()) {
s_logger.error("createImportSpec error: " + fault.getLocalizedMessage());
}
throw new CloudRuntimeException("Failed to create an import spec from " + ovfFilePath + ". Check log for details.");
}
if (!ovfImportResult.getWarning().isEmpty()) {
for (LocalizedMethodFault fault : ovfImportResult.getError()) {
s_logger.warn("createImportSpec warning: " + fault.getLocalizedMessage());
}
}
DatacenterMO dcMo = null;
try {
dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
} catch (Exception e) {
throw new CloudRuntimeException(String.format("no datacenter for host '%s' available in context", context.getServerAddress()), e);
}
ManagedObjectReference folderMO = null;
try {
folderMO = dcMo.getVmFolder();
} catch (Exception e) {
throw new CloudRuntimeException("no management handle for VmFolder", e);
}
ManagedObjectReference morLease = null;
try {
morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), folderMO, morHost);
} catch (DuplicateNameFaultMsg | FileFaultFaultMsg | InsufficientResourcesFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidNameFaultMsg | OutOfBoundsFaultMsg | RuntimeFaultFaultMsg | VmConfigFaultFaultMsg fault) {
throw new CloudRuntimeException("import vApp failed", fault);
}
if (morLease == null) {
String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
boolean importSuccess = true;
final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
HttpNfcLeaseState state = null;
try {
state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
} catch (Exception e) {
throw new CloudRuntimeException("exception while waiting for leaseMO", e);
}
try {
if (state == HttpNfcLeaseState.READY) {
final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
File ovfFile = new File(ovfFilePath);
HttpNfcLeaseInfo httpNfcLeaseInfo = null;
try {
httpNfcLeaseInfo = leaseMo.getLeaseInfo();
} catch (Exception e) {
throw new CloudRuntimeException("error waiting for lease info", e);
}
List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
long bytesAlreadyWritten = 0;
final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
try {
for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
String deviceKey = deviceUrl.getImportKey();
for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
if (deviceKey.equals(ovfFileItem.getDeviceId())) {
String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
s_logger.info("Uploading file: " + absoluteFile);
File f = new File(absoluteFile);
if (f.exists()) {
String urlToPost = deviceUrl.getUrl();
urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate<Long>() {
@Override
public void action(Long param) {
progressReporter.reportProgress((int) (param * 100 / totalBytes));
}
});
bytesAlreadyWritten += ovfFileItem.getSize();
}
}
}
}
} catch (Exception e) {
String erroMsg = "File upload task failed to complete due to: " + e.getMessage();
s_logger.error(erroMsg);
// Set flag to cleanup the stale template left due to failed import operation, if any
importSuccess = false;
throw new CloudRuntimeException(erroMsg, e);
} catch (Throwable th) {
String errorMsg = "throwable caught during file upload task: " + th.getMessage();
s_logger.error(errorMsg);
// Set flag to cleanup the stale template left due to failed import operation, if any
importSuccess = false;
throw new CloudRuntimeException(errorMsg, th);
} finally {
progressReporter.close();
}
if (bytesAlreadyWritten == totalBytes) {
try {
leaseMo.updateLeaseProgress(100);
} catch (Exception e) {
throw new CloudRuntimeException("error while waiting for lease update", e);
}
}
} else if (state == HttpNfcLeaseState.ERROR) {
LocalizedMethodFault error = null;
try {
error = leaseMo.getLeaseError();
} catch (Exception e) {
throw new CloudRuntimeException("error getting lease error", e);
}
MethodFault fault = error.getFault();
String erroMsg = "Object creation on vCenter failed due to: Exception: " + fault.getClass().getName() + ", message: " + error.getLocalizedMessage();
s_logger.error(erroMsg);
throw new CloudRuntimeException(erroMsg);
}
} finally {
try {
if (!importSuccess) {
s_logger.error("Aborting the lease on " + vmName + " after import operation failed.");
leaseMo.abortLease();
} else {
leaseMo.completeLease();
}
} catch (Exception e) {
throw new CloudRuntimeException("error completing lease", e);
}
}
}
Aggregations