public void detachDiskFromVM() throws Exception { ArrayOfVirtualDevice devices = this.get .entityProp(this.vm, VimPath.vm_config_hardware_device); VirtualDisk vd = (VirtualDisk) findMatchingVirtualDevice(getListOfVirtualDisk(devices)); if (vd == null) { throw new IllegalStateException( String.format( "Matching Virtual Disk is not for disk %s.", this.diskState.documentSelfLink)); } // Detach the disk from VM. VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); deviceConfigSpec.setDevice(vd); VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec(); spec.getDeviceChange().add(deviceConfigSpec); ManagedObjectReference reconfigureTask = getVimPort().reconfigVMTask(this.vm, spec); TaskInfo info = VimUtils.waitTaskEnd(this.connection, reconfigureTask); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } }
/** * This method returns a boolean value specifying whether the Task is * succeeded or failed. * * @param task * ManagedObjectReference representing the Task. * @return boolean value representing the Task result. * @throws InvalidCollectorVersionFaultMsg * * @throws RuntimeFaultFaultMsg * @throws InvalidPropertyFaultMsg */ public boolean getTaskResultAfterDone(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { boolean retVal = false; // info has a property - state for state of the task Object[] result = wait(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } }); if (result[0].equals(TaskInfoState.SUCCESS)) { retVal = true; } if (result[1] instanceof LocalizedMethodFault) { throw new RuntimeException( ((LocalizedMethodFault) result[1]).getLocalizedMessage()); } return retVal; }
public static boolean waitForTask(VMwareConnection connection, ManagedObjectReference task) throws Exception { try { Object[] result = waitForValues(connection, task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } }); if (result[0].equals(TaskInfoState.SUCCESS)) { return true; } if (result[1] instanceof LocalizedMethodFault) { throw new Exception(((LocalizedMethodFault)result[1]).getLocalizedMessage()); } } catch (WebServiceException we) { s_logger.debug("Cancelling vCenter task because the task failed with the following error: " + we.getLocalizedMessage()); connection.getVimPortType().cancelTask(task); throw new Exception("The vCenter task failed due to the following error: " + we.getLocalizedMessage()); } return false; }
private void logTaskInfo(TaskInfo info) { if (info == null) { logger.debug("Deleted task info key"); return; } TaskInfoState state = info.getState(); Integer progress = info.getProgress(); if (state == TaskInfoState.SUCCESS) { progress = Integer.valueOf(100); } else if (progress == null) { progress = Integer.valueOf(0); } LocalizableMessage desc = info.getDescription(); String description = desc != null ? desc.getMessage() : ""; XMLGregorianCalendar queueT = info.getQueueTime(); String queueTime = queueT != null ? queueT.toGregorianCalendar().getTime().toString() : ""; XMLGregorianCalendar startT = info.getStartTime(); String startTime = startT != null ? startT.toGregorianCalendar().getTime().toString() : ""; XMLGregorianCalendar completeT = info.getCompleteTime(); String completeTime = completeT != null ? completeT.toGregorianCalendar().getTime().toString() : ""; logger.debug("Save task info key: " + info.getKey() + " name: " + info.getName() + " target: " + info.getEntityName() + " state: " + state.name() + " progress: " + progress + "% description: " + description + " queue-time: " + queueTime + " start-time: " + startTime + " complete-time: " + completeTime); }
/** * Power off virtual machine */ public static void powerOffVM(final Connection connection, final VimPortType vimPort, final ManagedObjectReference vm) throws Exception { ManagedObjectReference powerTask = vimPort.powerOffVMTask(vm); TaskInfo info = VimUtils.waitTaskEnd(connection, powerTask); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } }
/** * Power on virtual machine */ public static void powerOnVM(final Connection connection, final VimPortType vimPort, final ManagedObjectReference vm) throws Exception { ManagedObjectReference powerTask = vimPort.powerOnVMTask(vm, null); TaskInfo info = VimUtils.waitTaskEnd(connection, powerTask); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } }
/** * Reconfigure image disk with the customizations */ private void reconfigureBootDisk(ManagedObjectReference vmMoref, List<VirtualDeviceConfigSpec> deviceConfigSpecs) throws Exception { if (deviceConfigSpecs != null && !deviceConfigSpecs.isEmpty()) { VirtualMachineConfigSpec bootDiskSpec = new VirtualMachineConfigSpec(); bootDiskSpec.getDeviceChange().addAll(deviceConfigSpecs); ManagedObjectReference task = getVimPort().reconfigVMTask(vmMoref, bootDiskSpec); TaskInfo info = waitTaskEnd(task); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } } }
/** * Create Virtual Disk */ public void createVirtualDisk() throws Exception { ManagedObjectReference diskManager = this.connection.getServiceContent() .getVirtualDiskManager(); List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(this.diskState); String dsName = this.diskContext.datastoreName != null && !this.diskContext.datastoreName .isEmpty() ? this.diskContext.datastoreName : ClientUtils.getDefaultDatastore(this.finder); String diskName = getUniqueDiskName(); // Create the parent folder before creation of the disk file String parentDir = String.format(VM_PATH_FORMAT, dsName, diskName); createParentFolder(parentDir); String diskFullPath = constructDiskFullPath(dsName, diskName); ManagedObjectReference createTask = getVimPort().createVirtualDiskTask(diskManager, diskFullPath, this.diskContext.datacenterMoRef, createVirtualDiskSpec(this.diskState, pbmSpec)); TaskInfo info = waitTaskEnd(createTask); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } // Update the details of the disk CustomProperties.of(this.diskState) .put(DISK_FULL_PATH, diskFullPath) .put(DISK_PARENT_DIRECTORY, parentDir) .put(DISK_DATASTORE_NAME, dsName); this.diskState.status = DiskService.DiskStatus.AVAILABLE; this.diskState.id = diskName; }
/** * Delete Virtual disk. */ public void deleteVirtualDisk() throws Exception { ManagedObjectReference diskManager = this.connection.getServiceContent() .getVirtualDiskManager(); if (this.diskState.status != DiskService.DiskStatus.AVAILABLE) { throw new IllegalArgumentException("Only disk with status AVAILABLE can be deleted, as it is not attached to any VM."); } String diskFullPath = CustomProperties.of(this.diskState).getString(DISK_FULL_PATH, null); if (diskFullPath == null) { throw new IllegalArgumentException("Disk full path to issue delete request is empty."); } // Delete the vmdk file ManagedObjectReference deleteTask = getVimPort().deleteVirtualDiskTask(diskManager, diskFullPath, this.diskContext.datacenterMoRef); TaskInfo info = waitTaskEnd(deleteTask); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } // Delete the folder that holds the vmdk file String dirName = CustomProperties.of(this.diskState).getString(DISK_PARENT_DIRECTORY, null); if (dirName != null) { ManagedObjectReference fileManager = this.connection.getServiceContent() .getFileManager(); ManagedObjectReference deleteFile = getVimPort().deleteDatastoreFileTask(fileManager, dirName, this.diskContext .datacenterMoRef); info = waitTaskEnd(deleteFile); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } } else { Utils.logWarning("Disk parent directory is null, hence couldn't cleanup disk directory in the datastore"); } }
public static TaskInfo waitTaskEnd(Connection connection, ManagedObjectReference task) throws InvalidCollectorVersionFaultMsg, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { WaitForValues waitForValues = new WaitForValues(connection); Object[] info = waitForValues.wait(task, new String[] { VimPath.task_info }, new String[] { VimPath.task_info_state }, new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } }); return (TaskInfo) info[0]; }
private void handleTask(Task task) throws DestructionException, InterruptedException, RemoteException { task.waitForTask(); TaskInfo taskInfo = task.getTaskInfo(); if (TaskInfoState.error == taskInfo.getState()) { throw new DestructionException(taskInfo.getError().getLocalizedMessage()); } }
@Test public void destroy() throws DestructionException, IOException { when(this.inventoryNavigatorFactory.create()).thenReturn(this.inventoryNavigator); when(this.inventoryNavigator.searchManagedEntity("VirtualMachine", "test-id")).thenReturn(this.virtualMachine); when(this.virtualMachine.powerOffVM_Task()).thenReturn(this.task); when(this.virtualMachine.destroy_Task()).thenReturn(this.task); when(this.task.getTaskInfo()).thenReturn(this.taskInfo); when(this.taskInfo.getState()).thenReturn(TaskInfoState.success); this.infrastructure.destroy(this.member); verify(this.virtualMachine).powerOffVM_Task(); }
@Test(expected = DestructionException.class) public void taskFailure() throws DestructionException, IOException { when(this.inventoryNavigatorFactory.create()).thenReturn(this.inventoryNavigator); when(this.inventoryNavigator.searchManagedEntity("VirtualMachine", "test-id")).thenReturn(this.virtualMachine); when(this.virtualMachine.powerOffVM_Task()).thenReturn(this.task); when(this.task.getTaskInfo()).thenReturn(this.taskInfo); when(this.taskInfo.getState()).thenReturn(TaskInfoState.error); when(this.taskInfo.getError()).thenReturn(this.localizedMethodFault); this.infrastructure.destroy(this.member); }
static TaskFilterSpec createTaskFilterSpec(ManagedEntity ent) { TaskFilterSpec tfs = new TaskFilterSpec(); // only the root initiated tasks TaskFilterSpecByUsername nameFilter = new TaskFilterSpecByUsername(); nameFilter.setUserList(new String[] {"Administrator"}); // include tasks initiated by non-users, // for example, by ScheduledTaskManager. nameFilter.setSystemUser(true); tfs.setUserName(nameFilter); // only the tasks with one entity itself TaskFilterSpecByEntity entFilter = new TaskFilterSpecByEntity(); entFilter.setEntity(ent.getMOR()); entFilter.setRecursion(TaskFilterSpecRecursionOption.all); tfs.setEntity(entFilter); // only successfully finished tasks tfs.setState(new TaskInfoState[]{TaskInfoState.success }); // only tasks started within last one month // strictly speaking, time should be retrieved from server TaskFilterSpecByTime tFilter =new TaskFilterSpecByTime(); Calendar cal = Calendar.getInstance(); cal.roll(Calendar.MONTH, -1); tFilter.setBeginTime(cal); //we ignore the end time here so it gets the latest. tFilter.setTimeType(TaskFilterSpecTimeOption.startedTime); tfs.setTime(tFilter); // Optionally, you limits tasks initiated by scheduled task // with the setScheduledTask() method. return tfs; }
protected boolean getTaskResultAfterDone(ConnectionResources connectionResources, ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg { WaitForValues waitForValues = new WaitForValues(connectionResources.getConnection()); Object[] result = waitForValues.wait(task, new String[]{ManagedObjectType.INFO_STATE.getValue(), ManagedObjectType.INFO_ERROR.getValue()}, new String[]{ManagedObjectType.STATE.getValue()}, new Object[][]{new Object[]{TaskInfoState.SUCCESS, TaskInfoState.ERROR}}); if (result[1] instanceof LocalizedMethodFault) { throw new RuntimeException(((LocalizedMethodFault) result[1]).getLocalizedMessage()); } return result[0].equals(TaskInfoState.SUCCESS); }
private void logTaskInfo(TaskInfo info) { String key = info.getKey(); String name = info.getName(); String target = info.getEntityName(); TaskInfoState state = info.getState(); Integer progress = info.getProgress(); if (state == TaskInfoState.SUCCESS) { progress = Integer.valueOf(100); } else if (progress == null) { progress = Integer.valueOf(0); } LocalizableMessage desc = info.getDescription(); String description = desc != null ? desc.getMessage() : ""; TaskReason reason = info.getReason(); String initiatedBy = ""; if (reason != null) { if (reason instanceof TaskReasonUser) { initiatedBy = ((TaskReasonUser) reason).getUserName(); } else if (reason instanceof TaskReasonSystem) { initiatedBy = "System"; } else if (reason instanceof TaskReasonSchedule) { initiatedBy = ((TaskReasonSchedule) reason).getName(); } else if (reason instanceof TaskReasonAlarm) { initiatedBy = ((TaskReasonAlarm) reason).getAlarmName(); } } XMLGregorianCalendar queueT = info.getQueueTime(); String queueTime = queueT != null ? queueT.toGregorianCalendar().getTime().toString() : ""; XMLGregorianCalendar startT = info.getStartTime(); String startTime = startT != null ? startT.toGregorianCalendar().getTime().toString() : ""; XMLGregorianCalendar completeT = info.getCompleteTime(); String completeTime = completeT != null ? completeT.toGregorianCalendar().getTime().toString() : ""; logger.debug(key + " name: " + name + " target: " + target + " state: " + state + " progress: " + progress + "% description: " + description + " initiated: " + initiatedBy + " queue-time: " + queueTime + " start-time: " + startTime + " complete-time: " + completeTime); }
public ComputeState createInstanceFromSnapshot() throws Exception { String message = ""; if (this.ctx.snapshotMoRef == null) { message = String.format("No MoRef found for the specified snapshot %s", this.ctx.child.documentSelfLink); logger.error(message); this.ctx.fail(new IllegalStateException(message)); } if (this.ctx.referenceComputeMoRef == null) { if (this.ctx.snapshotMoRef == null) { message = String.format("No MoRef found for the reference compute for linkedclone creation for %s.", this.ctx.child.documentSelfLink); logger.error(message); this.ctx.fail(new IllegalStateException(message)); } } VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); relocateSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions .CREATE_NEW_CHILD_DISK_BACKING.value()); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setPowerOn(false); cloneSpec.setLocation(relocateSpec); cloneSpec.setSnapshot(this.ctx.snapshotMoRef); cloneSpec.setTemplate(false); ManagedObjectReference folder = getVmFolder(); String displayName = this.ctx.child.name; ManagedObjectReference linkedCloneTask = getVimPort() .cloneVMTask(this.ctx.referenceComputeMoRef, folder, displayName, cloneSpec); TaskInfo info = waitTaskEnd(linkedCloneTask); if (info.getState() == TaskInfoState.ERROR) { MethodFault fault = info.getError().getFault(); if (fault instanceof FileAlreadyExists) { // a .vmx file already exists, assume someone won the race to create the vm return null; } else { return VimUtils.rethrow(info.getError()); } } ManagedObjectReference clonedVM = (ManagedObjectReference) info.getResult(); if (clonedVM == null) { // vm was created by someone else return null; } // store reference to created vm for further processing this.vm = clonedVM; customizeAfterClone(); ComputeState state = new ComputeState(); state.resourcePoolLink = VimUtils .firstNonNull(this.ctx.child.resourcePoolLink, this.ctx.parent.resourcePoolLink); return state; }
private ManagedObjectReference cloneVm(ManagedObjectReference template) throws Exception { ManagedObjectReference folder = getVmFolder(); List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(this.bootDisk); ManagedObjectReference datastore = getDataStoreForDisk(this.bootDisk, pbmSpec); ManagedObjectReference resourcePool = getResourcePool(); Map<String, Object> props = this.get.entityProps(template, VimPath.vm_config_hardware_device); ArrayOfVirtualDevice devices = (ArrayOfVirtualDevice) props .get(VimPath.vm_config_hardware_device); VirtualDisk vd = devices.getVirtualDevice().stream() .filter(d -> d instanceof VirtualDisk) .map(d -> (VirtualDisk) d).findFirst().orElse(null); VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec(); relocSpec.setDatastore(datastore); if (pbmSpec != null) { pbmSpec.stream().forEach(spec -> { relocSpec.getProfile().add(spec); }); } relocSpec.setFolder(folder); relocSpec.setPool(resourcePool); relocSpec.setDiskMoveType(computeDiskMoveType().value()); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(relocSpec); //Set the provisioning type of the parent disk. VirtualMachineRelocateSpecDiskLocator diskProvisionTypeLocator = setProvisioningType(vd, datastore, pbmSpec); if (diskProvisionTypeLocator != null) { cloneSpec.getLocation().getDisk().add(diskProvisionTypeLocator); } cloneSpec.setPowerOn(false); cloneSpec.setTemplate(false); String displayName = this.ctx.child.name; ManagedObjectReference cloneTask = getVimPort() .cloneVMTask(template, folder, displayName, cloneSpec); TaskInfo info = waitTaskEnd(cloneTask); if (info.getState() == TaskInfoState.ERROR) { MethodFault fault = info.getError().getFault(); if (fault instanceof FileAlreadyExists) { // a .vmx file already exists, assume someone won the race to create the vm return null; } else { return VimUtils.rethrow(info.getError()); } } return (ManagedObjectReference) info.getResult(); }
private void ignoreError(String s, TaskInfo info) { if (info.getState() == TaskInfoState.ERROR) { logger.info(s + ": " + info.getError().getLocalizedMessage()); } }
/** * Creates a VM in vsphere. This method will block until the CreateVM_Task completes. The path * to the .vmx file is explicitly set and its existence is iterpreted as if the VM has been * successfully created and returns null. * * @return * @throws FinderException * @throws Exception */ private ManagedObjectReference createVm() throws Exception { ManagedObjectReference folder = getVmFolder(); List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(this.bootDisk); ManagedObjectReference datastore = getDataStoreForDisk(this.bootDisk, pbmSpec); ManagedObjectReference resourcePool = getResourcePool(); ManagedObjectReference host = getHost(); // If datastore for disk is null, if storage policy is configured pick the compatible // datastore from that. if (datastore == null) { ManagedObjectReference dsFromSp = getDatastoreFromStoragePolicy(this.connection, pbmSpec); datastore = dsFromSp == null ? getDatastore() : dsFromSp; } String datastoreName = this.get.entityProp(datastore, "name"); VirtualMachineConfigSpec spec = buildVirtualMachineConfigSpec(datastoreName); String gt = CustomProperties.of(this.ctx.child).getString(CustomProperties.GUEST_ID, null); if (gt != null) { try { gt = VirtualMachineGuestOsIdentifier.valueOf(gt).value(); } catch (IllegalArgumentException e) { // silently default to generic 64 bit guest. gt = DEFAULT_GUEST_ID.value(); } spec.setGuestId(gt); } populateCloudConfig(spec, null); recordTimestamp(spec.getExtraConfig()); // set the maximum snapshot limit if specified final String snapshotLimit = CustomProperties.of(this.ctx.child).getString(CustomProperties.SNAPSHOT_MAXIMUM_LIMIT); recordSnapshotLimit(spec.getExtraConfig(), snapshotLimit); ManagedObjectReference vmTask = getVimPort().createVMTask(folder, spec, resourcePool, host); TaskInfo info = waitTaskEnd(vmTask); if (info.getState() == TaskInfoState.ERROR) { MethodFault fault = info.getError().getFault(); if (fault instanceof FileAlreadyExists) { // a .vmx file already exists, assume someone won the race to create the vm return null; } else { return VimUtils.rethrow(info.getError()); } } return (ManagedObjectReference) info.getResult(); }
private void awaitTaskEnd(ManagedObjectReference task) throws Exception { TaskInfo taskInfo = VimUtils.waitTaskEnd(this.connection, task); if (taskInfo.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(taskInfo.getError()); } }
private void createSnapshot(Connection connection, SnapshotContext context, DeferredResult<SnapshotContext> deferredResult) { ManagedObjectReference vmMoRef = CustomProperties.of(context.computeDescription).getMoRef(CustomProperties.MOREF); if (vmMoRef == null) { deferredResult.fail(new IllegalStateException("Cannot find VM to snapshot")); return; } ManagedObjectReference task; TaskInfo info; try { logInfo("Creating snapshot for compute resource %s", context.computeDescription.name); task = connection.getVimPort() .createSnapshotTask(vmMoRef, context.snapshotState.name, context.snapshotState.description, context.snapshotMemory, false); info = VimUtils.waitTaskEnd(connection, task); if (info.getState() != TaskInfoState.SUCCESS) { VimUtils.rethrow(info.getError()); } } catch (Exception e) { deferredResult.fail(e); return; } CustomProperties.of(context.snapshotState).put(CustomProperties.MOREF, (ManagedObjectReference) info.getResult()); context.snapshotState.isCurrent = true; //mark this as current snapshot // create a new xenon SnapshotState logInfo(String.format("Creating a new snapshot state for compute : %s", context.computeDescription.name)); Operation createSnapshotState = Operation.createPost(PhotonModelUriUtils.createInventoryUri(getHost(), SnapshotService.FACTORY_LINK)) .setBody(context.snapshotState); if (context.existingSnapshotState != null) { // un-mark old snapshot as current snapshot context.existingSnapshotState.isCurrent = false; Operation patchOldSnapshot = Operation .createPatch(UriUtils.buildUri(getHost(), context.existingSnapshotState.documentSelfLink)) .setBody(context.existingSnapshotState); OperationSequence.create(createSnapshotState) .next(patchOldSnapshot) .setCompletion((o, e) -> { if (e != null && !e.isEmpty()) { deferredResult.fail(e.values().iterator().next()); } deferredResult.complete(context); }).sendWith(this); } else { context.computeDescription.customProperties.put(ComputeProperties.CUSTOM_PROP_COMPUTE_HAS_SNAPSHOTS, "true"); // patch compute adding the property '_hasSnapshots' with true Operation patchCompute = Operation .createPatch(UriUtils.buildUri(getHost(), context.snapshotState.computeLink)) .setBody(context.computeDescription); OperationSequence.create(createSnapshotState) .next(patchCompute) .setCompletion((o, e) -> { if (e != null && !e.isEmpty()) { deferredResult.fail(e.values().iterator().next()); } logInfo(String.format("Created a new snapshot state for compute : %s", context.computeDescription.name)); deferredResult.complete(context); }).sendWith(this); } }
private void deleteSnapshot(SnapshotContext context, Connection connection, DeferredResult<SnapshotContext> deferredResult) { final SnapshotState snapshot = context.snapshotState; // Physical snapshot processing ManagedObjectReference snapshotMoref = CustomProperties.of(snapshot) .getMoRef(CustomProperties.MOREF); if (snapshotMoref == null) { deferredResult.fail(new IllegalStateException(String.format("Cannot find the snapshot %s to removed", snapshotMoref))); return; } ManagedObjectReference task; TaskInfo info; try { logInfo("Deleting snapshot with name %s", context.snapshotState.name); task = connection.getVimPort() .removeSnapshotTask(snapshotMoref, REMOVE_CHILDREN, SNAPSHOT_CONSOLIDATION); info = VimUtils.waitTaskEnd(connection, task); if (info.getState() != TaskInfoState.SUCCESS) { VimUtils.rethrow(info.getError()); } } catch (Exception e) { logSevere("Deleting the snapshot %s failed", context.snapshotState.name); deferredResult.fail(e); return; } logInfo("Deleted the snapshot with name %s successfully", context.snapshotState.name); // Once the actual snapshot delete is successful, process the update of the children // snapshot states and the next current snapshot final List<SnapshotState> childSnapshots = new ArrayList<>(); DeferredResult<List<SnapshotState>> dr = getChildSnapshots(snapshot.documentSelfLink) ; List<SnapshotState> updatedChildSnapshots = new ArrayList<>(); dr.whenComplete((o, e) -> { if (e != null) { logSevere("Retrieving the details of children snapshots failed"); deferredResult.fail(e); return; } childSnapshots.addAll(o); logInfo("Retrieving the details of %s children snapshots ", childSnapshots.size()); // Update the children if (!childSnapshots.isEmpty()) { logInfo("Updating the state of child snapshots of: %s", snapshot.name); childSnapshots.forEach(c -> { c.parentLink = snapshot.parentLink; updatedChildSnapshots.add(c); }); context.snapshotOperations = updatedChildSnapshots .stream() .map(childSnapshot -> Operation.createPatch( PhotonModelUriUtils .createInventoryUri(getHost(), childSnapshot.documentSelfLink)) .setBody(childSnapshot) .setReferer(getUri())) .collect(Collectors.toList()); } processNextStepsForDeleteOperation(context, deferredResult); }); }
private void revertSnapshot(SnapshotContext context, Connection connection, DeferredResult<SnapshotContext> deferredResult) { final SnapshotState snapshot = context.snapshotState; SnapshotState existingSnapshotState = context.existingSnapshotState; // Physical snapshot processing ManagedObjectReference snapshotMoref = CustomProperties.of(snapshot) .getMoRef(CustomProperties.MOREF); if (snapshotMoref == null) { deferredResult.fail(new IllegalStateException(String.format("Cannot find the snapshot %s to revert to", snapshotMoref))); return; } ManagedObjectReference task; TaskInfo info; try { logInfo("Reverting to snapshot with name %s", context.snapshotState.name); task = connection.getVimPort() .revertToSnapshotTask(snapshotMoref, null, false); info = VimUtils.waitTaskEnd(connection, task); if (info.getState() != TaskInfoState.SUCCESS) { VimUtils.rethrow(info.getError()); } } catch (Exception e) { logSevere("Reverting to the snapshot %s failed", context.snapshotState.name); deferredResult.fail(e); return; } // Check if we're trying to revert to the current snapshot. In that case we need not // update the isCurrent for both the snapshot states (existing and the reverted). // Also sending multiple patch requests on the same snapshot document will // cause concurrency issue if (snapshot.isCurrent) { deferredResult.complete(context); } else { snapshot.isCurrent = true; context.snapshotOperations.add(Operation .createPatch(UriUtils.buildUri(getHost(), snapshot.documentSelfLink)) .setBody(snapshot) .setReferer(getUri())); if (existingSnapshotState != null) { existingSnapshotState.isCurrent = false; context.snapshotOperations.add(Operation .createPatch(UriUtils.buildUri(getHost(), existingSnapshotState.documentSelfLink)) .setBody(existingSnapshotState) .setReferer(getUri())); } OperationJoin.JoinedCompletionHandler joinCompletion = (ox, exc) -> { if (exc != null) { this.logSevere(() -> String.format("Error updating the snapshot states: %s", Utils.toString(exc))); deferredResult.fail( new IllegalStateException("Error updating the snapshot states")); return; } deferredResult.complete(context); }; OperationJoin joinOp = OperationJoin.create(context.snapshotOperations); joinOp.setCompletion(joinCompletion); joinOp.sendWith(this.getHost()); } }
public void setTaskState(TaskInfoState tis, Object result, LocalizedMethodFault fault) throws InvalidState, RuntimeFault, RemoteException { getVimService().setTaskState(getMOR(), tis, result, fault); }
public void setTaskState(TaskInfoState state, Object result, LocalizedMethodFault fault) throws Exception { _context.getService().setTaskState(_mor, state, result, fault); }
private VirtualDeviceConfigSpec createFullCloneAndAttach(String sourcePath, DiskStateExpanded ds, String dir, VirtualDevice scsiController, int unitNumber, List<VirtualMachineDefinedProfileSpec> pbmSpec) throws Exception { ManagedObjectReference diskManager = this.connection.getServiceContent() .getVirtualDiskManager(); String dsDirForDisk = getDatastorePathForDisk(ds, dir); // put full clone in the vm folder String destName = makePathToVmdkFile(ds.name, dsDirForDisk); // all ops are within a datacenter ManagedObjectReference sourceDc = this.ctx.datacenterMoRef; ManagedObjectReference destDc = sourceDc; Boolean force = true; // spec is not supported, should use null for now VirtualDiskSpec spec = null; ManagedObjectReference task = getVimPort() .copyVirtualDiskTask(diskManager, sourcePath, sourceDc, destName, destDc, spec, force); // wait for the disk to be copied TaskInfo taskInfo = waitTaskEnd(task); if (taskInfo.getState() == TaskInfoState.ERROR) { return VimUtils.rethrow(taskInfo.getError()); } VirtualDiskFlatVer2BackingInfo backing = new VirtualDiskFlatVer2BackingInfo(); backing.setDiskMode(getDiskMode(ds)); VirtualDiskType provisionType = getDiskProvisioningType(ds); if (provisionType != null) { backing.setThinProvisioned(provisionType == VirtualDiskType.THIN); backing.setEagerlyScrub(provisionType == VirtualDiskType.EAGER_ZEROED_THICK); } backing.setFileName(destName); backing.setDatastore(getDataStoreForDisk(ds, pbmSpec)); VirtualDisk disk = new VirtualDisk(); disk.setBacking(backing); disk.setStorageIOAllocation(getStorageIOAllocationInfo(ds)); disk.setControllerKey(scsiController.getKey()); disk.setUnitNumber(unitNumber); fillInControllerUnitNumber(ds, unitNumber); disk.setKey(-1); VirtualDeviceConfigSpec change = new VirtualDeviceConfigSpec(); change.setDevice(disk); // Add storage policy spec if (pbmSpec != null) { pbmSpec.stream().forEach(sp -> { change.getProfile().add(sp); }); } change.setOperation(VirtualDeviceConfigSpecOperation.ADD); return change; }