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()); } }
private void deleteDiskFromVSphere(DiskState diskState) throws Throwable { Connection connection = createConnection(); String diskFullPath = CustomProperties.of(diskState).getString(DISK_FULL_PATH, null); ManagedObjectReference diskManager = connection.getServiceContent() .getVirtualDiskManager(); ManagedObjectReference datacenterMoRef = VimUtils.convertStringToMoRef(diskState.regionId); ManagedObjectReference deleteTask = connection.getVimPort().deleteVirtualDiskTask(diskManager, diskFullPath, datacenterMoRef); TaskInfo info = VimUtils.waitTaskEnd(connection, deleteTask); String dirName = CustomProperties.of(diskState).getString(DISK_PARENT_DIRECTORY, null); ManagedObjectReference fileManager = connection.getServiceContent() .getFileManager(); deleteTask = connection.getVimPort().deleteDatastoreFileTask(fileManager, dirName, datacenterMoRef); info = VimUtils.waitTaskEnd(connection, deleteTask); }
static void printTaskInfo(TaskInfo ti) { System.out.println("\nName:" + ti.getName()); System.out.println("Key:" + ti.getKey()); System.out.println("Entity:" + ti.getEntityName()); System.out.println("Reason:" + taskReason(ti.getReason())); System.out.println("QueueTime:" + ti.getQueueTime().getTime()); Calendar calStart = ti.getStartTime(); Date dateStart = calStart==null? null : calStart.getTime(); System.out.println("StartTime:" + dateStart); Calendar calStop = ti.getCompleteTime(); Date dateStop = calStop==null? null : calStop.getTime(); System.out.println("CompleteTime:" + dateStop); System.out.println("Cancelable:" + ti.isCancelable()); System.out.println("Cancelled:" + ti.isCancelled()); }
public static String getTaskFailureInfo(VmwareContext context, ManagedObjectReference morTask) { StringBuffer sb = new StringBuffer(); try { TaskInfo info = (TaskInfo)context.getVimClient().getDynamicProperty(morTask, "info"); if (info != null) { LocalizedMethodFault fault = info.getError(); if (fault != null) { sb.append(fault.getLocalizedMessage()).append(" "); if (fault.getFault() != null) sb.append(fault.getFault().getClass().getName()); } } } catch (Exception e) { s_logger.info("[ignored]" + "error retrieving failure info for task : " + e.getLocalizedMessage()); } return sb.toString(); }
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); }
@StateMachineAction @Override protected String successfulTask(TaskInfo taskInfo, VMPropertyHandler ph) { ph.setSetting(VMPropertyHandler.GUEST_READY_TIMEOUT_REF, String.valueOf(System.currentTimeMillis())); if (TASK_NAME_CREATE_SNAPSHOT.equals(taskInfo.getName())) { ManagedObjectReference mor = (ManagedObjectReference) taskInfo .getResult(); ph.setSetting(VMPropertyHandler.SNAPSHOT_ID, mor.getValue()); } return EVENT_SUCCESS; }
protected String successfulTask( @SuppressWarnings("unused") TaskInfo taskInfo, VMPropertyHandler ph) { ph.setSetting(VMPropertyHandler.GUEST_READY_TIMEOUT_REF, String.valueOf(System.currentTimeMillis())); return EVENT_SUCCESS; }
protected TaskInfo getTaskInfo(VMwareClient vmw, VMPropertyHandler paramHandler) throws Exception { String instanceId = paramHandler.getInstanceName(); String taskKey = paramHandler .getServiceSetting(VMPropertyHandler.TASK_KEY); logger.debug("VM: " + instanceId + " taskId: " + taskKey); if (taskKey == null || "".equals(taskKey)) { return null; } VimPortType service = vmw.getConnection().getService(); ManagedObjectReference taskManager = vmw.getConnection() .getServiceContent().getTaskManager(); ManagedObjectReference taskHistoryCollector = service .createCollectorForTasks(taskManager, new TaskFilterSpec()); try { service.resetCollector(taskHistoryCollector); service.readNextTasks(taskHistoryCollector, 100); List<TaskInfo> taskList = vmw.getConnection().getService() .readPreviousTasks(taskHistoryCollector, 100); if (taskList != null) { for (TaskInfo taskInfo : taskList) { if (taskInfo != null && taskKey.equals(taskInfo.getKey())) { logTaskInfo(taskInfo); return taskInfo; } } } logger.error("Task not found. VM: " + instanceId + " taskId: " + taskKey); return null; } finally { service.destroyCollector(taskHistoryCollector); } }
public TaskInfo start() throws Exception { LOG.debug("instanceName: " + instanceName); ManagedObjectReference startTask = vmw.getConnection().getService() .powerOnVMTask(vmInstance, null); TaskInfo tInfo = (TaskInfo) vmw.getServiceUtil() .getDynamicProperty(startTask, "info"); return tInfo; }
/** * Reconfigures VMware instance. Memory, CPU, disk space and network * adapter. The VM has been created and must be stopped to reconfigure the * hardware. */ public TaskInfo reconfigureVirtualMachine(VMPropertyHandler paramHandler) throws Exception { LOG.debug("instanceName: " + instanceName); VimPortType service = vmw.getConnection().getService(); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec .setMemoryMB(Long.valueOf(paramHandler.getConfigMemoryMB())); vmConfigSpec.setNumCPUs(Integer.valueOf(paramHandler.getConfigCPUs())); String reqUser = paramHandler .getServiceSetting(VMPropertyHandler.REQUESTING_USER); String comment = Messages.get(paramHandler.getLocale(), "vm_comment", new Object[] { paramHandler.getSettings().getOrganizationName(), paramHandler.getSettings().getSubscriptionId(), reqUser }); String annotation = vmConfigSpec.getAnnotation(); comment = updateComment(comment, annotation); vmConfigSpec.setAnnotation(comment); DiskManager diskManager = new DiskManager(vmw, paramHandler); diskManager.reconfigureDisks(vmConfigSpec, vmInstance); NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmInstance); LOG.debug("Call vSphere API: reconfigVMTask()"); ManagedObjectReference reconfigureTask = service .reconfigVMTask(vmInstance, vmConfigSpec); return (TaskInfo) vmw.getServiceUtil() .getDynamicProperty(reconfigureTask, "info"); }
public TaskInfo updateCommentField(String comment) throws Exception { LOG.debug("instanceName: " + instanceName + " comment: " + comment); VimPortType service = vmw.getConnection().getService(); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); String annotation = vmConfigSpec.getAnnotation(); comment = updateComment(comment, annotation); vmConfigSpec.setAnnotation(comment); LOG.debug("Call vSphere API: reconfigVMTask()"); ManagedObjectReference reconfigureTask = service .reconfigVMTask(vmInstance, vmConfigSpec); return (TaskInfo) vmw.getServiceUtil() .getDynamicProperty(reconfigureTask, "info"); }
/** * Delete VMware instance on vSphere server. * * @param vmw * connected VMware client entity * @param instanceId * id of the instance */ public TaskInfo delete() throws Exception { LOG.debug("Call vSphere API: destroyTask() instanceName: " + instanceName); ManagedObjectReference startTask = vmw.getConnection().getService() .destroyTask(vmInstance); return (TaskInfo) vmw.getServiceUtil().getDynamicProperty(startTask, "info"); }
/** * 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]; }
public void should_report_isdone_for_error_tasks() throws ExecutionException, InterruptedException { VmwareTaskWrapper taskWrapper = new VmwareTaskWrapper(new Callable<Task>() { @Override public Task call() throws Exception { return new Task(null, null){ @Override public TaskInfo getTaskInfo() throws InvalidProperty, RuntimeFault, RemoteException { throw new RuntimeException("getTaskInfo exception"); } @Override public String waitForTask() throws RuntimeFault, RemoteException, InterruptedException { throw new RuntimeException("getTaskInfo exception"); } @Override public void cancelTask() throws RuntimeFault, RemoteException { throw new RuntimeException("getTaskInfo exception"); } }; } }, "myTask"); final Future<CloudTaskResult> async = taskWrapper.executeOrGetResultAsync(); int cnt = 0; while (!async.isDone()){ cnt++; assertTrue(cnt < 5); } final CloudTaskResult result = async.get(); assertTrue(result.isHasErrors()); }
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()); } }
static void printTaskInfos(TaskInfo[] tis) { for (int i = 0; tis!=null && i < tis.length; i++) { printTaskInfo(tis[i]); } }
public static void main(String[] args) throws Exception { if(args.length != 3) { System.out.println("Usage: java PrintTaskManager " + "<url> <username> <password>"); return; } ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); TaskManager taskMgr = si.getTaskManager(); int maxCollector = taskMgr.getMaxCollector(); System.out.println("Maximum number of collectors to " + "retrive historical tasks: " + maxCollector); System.out.println("\nTask description:"); TaskDescription td = taskMgr.getDescriptioin(); printTaskDescription(td); System.out.println("\nRecent tasks:"); Task[] recentTasks = taskMgr.getRecentTasks(); for(int i=0; recentTasks!=null && i<recentTasks.length; i++) { TaskInfo ti = recentTasks[i].getTaskInfo(); System.out.println("\nName:" + ti.getName()); System.out.println("Key:" + ti.getKey()); System.out.println("State:" + ti.getState()); } si.getServerConnection().logout(); }
public void waitForTaskProgressDone(ManagedObjectReference morTask) throws Exception { while (true) { TaskInfo tinfo = (TaskInfo)_vimClient.getDynamicProperty(morTask, "info"); Integer progress = tinfo.getProgress(); if (progress == null) break; if (progress.intValue() >= 100) break; Thread.sleep(1000); } }
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 TaskInfo retrieveTaskInfo(ManagedObjectReference task) throws Exception { return ((TaskInfo) getServiceUtil().getDynamicProperty(task, PROPERTY_INFO)); }
private static boolean migrateVM(ServiceInstance si, Folder rootFolder, HostSystem newHost, String targetVMName, String newHostName) throws Exception { log("Selected host [vm] for vMotion: " + newHostName + " [" + targetVMName + "]"); VirtualMachine vm = (VirtualMachine)new InventoryNavigator(rootFolder) .searchManagedEntity("VirtualMachine", targetVMName); if (vm == null) { log(WARNING, "Could not resolve VM " + targetVMName + ", vMotion of this VM cannot be performed."); return false; } ComputeResource cr = (ComputeResource)newHost.getParent(); String[] checks = new String[] { "cpu", "software" }; HostVMotionCompatibility[] vmcs = si.queryVMotionCompatibility(vm, new HostSystem[] { newHost }, checks); String[] comps = vmcs[0].getCompatibility(); if (checks.length != comps.length) { log(WARNING, "CPU/software NOT compatible, vMotion failed."); return false; } long start = System.currentTimeMillis(); Task task = vm.migrateVM_Task(cr.getResourcePool(), newHost, VirtualMachineMovePriority.highPriority, VirtualMachinePowerState.poweredOn); if (task.waitForMe() == Task.SUCCESS) { long end = System.currentTimeMillis(); log("vMotion of " + targetVMName + " to " + newHostName + " completed in " + (end - start) + "ms. Task result: " + task.getTaskInfo().getResult()); return true; } else { TaskInfo info = task.getTaskInfo(); log(WARNING, "vMotion of " + targetVMName + " to " + newHostName + " failed. Error details: " + info.getError().getFault()); return false; } }
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()); } }
private TaskInfo waitTaskEnd(ManagedObjectReference task) throws InvalidCollectorVersionFaultMsg, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { return VimUtils.waitTaskEnd(this.connection, task); }
/** * 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(); }
/** * Wait for the server initiated task to complete. */ private TaskInfo waitTaskEnd(ManagedObjectReference task) throws InvalidCollectorVersionFaultMsg, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { return VimUtils.waitTaskEnd(this.connection, task); }