com.vmware.vim25.TaskInfo Java Examples

The following examples show how to use com.vmware.vim25.TaskInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TaskMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #2
Source File: MountLunTask.java    From nbp with Apache License 2.0 6 votes vote down vote up
/**
 * go run task to attach volume
 * @throws Exception
 */
@Override
public void runTask() throws Exception {
    logger.info("---------Step two, run create the datastoreInfo task and mount volume...");

    List<TaskInfo> taskInfoList = new ArrayList<>();
    try {
        createTaskList(taskInfoList, TaskInfoConst.Type.TASK_MOUNT_LUN_TO_HOST);
        ResultInfo<Object> resultInfo = hostServiceImpl.mountVolume(hostMos, serverInfo, storage, volumeMO);
        if (resultInfo.getStatus().equals("ok")) {
            connectMO = (ConnectMO)resultInfo.getData();
            changeTaskState(taskInfoList, TaskInfoConst.Status.SUCCESS,
                    String.format("Mount volume %s fininsh.", datastore.getName()));
        } else {
            changeTaskState(taskInfoList, TaskInfoConst.Status.ERROR,
                    String.format("Mount volume failed: %s", resultInfo.getMsg()));
            throw new Exception(resultInfo.getMsg());
        }
    } catch (Exception e) {
        changeTaskState(taskInfoList, TaskInfoConst.Status.ERROR,
                String.format("Mount volume failed: %s", e.getMessage()));
        throw e;
    }
}
 
Example #3
Source File: MountLunTask.java    From nbp with Apache License 2.0 6 votes vote down vote up
@Override
public void rollBack() throws Exception {
    if (connectMO == null) {
        logger.info("---------MountTask, Cannot roll back for unmount volume.");
        return;
    }
    logger.info("---------MountTask, rolling back mount volume...");
    List<TaskInfo> rollBackTaskInfoList = new ArrayList<>();
    try {
        createTaskList(rollBackTaskInfoList, TaskInfoConst.Type.TASK_UNMOUNT_LUN_FROM_HOST);
        storage.detachVolume(volumeMO.id, connectMO);
        changeTaskState(rollBackTaskInfoList, TaskInfoConst.Status.SUCCESS,
                String.format("Umount volume %s finished.", volumeMO.name));
    } catch (Exception e) {
        changeTaskState(rollBackTaskInfoList, TaskInfoConst.Status.ERROR,
                String.format("Unmount volume failed: %s", e.getMessage()));
        throw e;
    }
}
 
Example #4
Source File: CreateLunTask.java    From nbp with Apache License 2.0 6 votes vote down vote up
/**
 * go run task to create volume
 * @throws Exception
 */
@Override
public void runTask() throws Exception {
    logger.info("---------Step one, run create the datastoreInfo task and create volume...");
    List<TaskInfo> taskInfoList = new ArrayList<>();
    try {
        createTaskList(taskInfoList, TaskInfoConst.Type.TASK_CREATE_LUN);
        VolumeInfo volumeInfo = ((VMFSDatastore)datastore).getVolumeInfos()[0];
        volumeMO = storage.createVolume(volumeInfo.getName(), volumeInfo.getDescription(),
                volumeInfo.getAllocType().equals("thin") ? ALLOC_TYPE.THIN : ALLOC_TYPE.THICK,
                CapacityUtil.convertCapToLong(volumeInfo.getCapacity()),
                volumeInfo.getStoragePoolId());
        context.put(VolumeMO.class.getName(), volumeMO);
        changeTaskState(taskInfoList, TaskInfoConst.Status.SUCCESS,
                String.format(Locale.ROOT, "Create volume %s finished.", volumeMO.name));
    } catch (Exception ex) {
        logger.error( "---------Step one error : " + ex.getMessage());
        changeTaskState(taskInfoList, TaskInfoConst.Status.ERROR,
                String.format(Locale.ROOT, "Create volume failed: %s", ex.getMessage()));
        throw ex;
    }
}
 
Example #5
Source File: CreateLunTask.java    From nbp with Apache License 2.0 6 votes vote down vote up
@Override
public void rollBack() throws Exception {
    if (volumeMO == null) {
        logger.info("Could not create the volume...");
        return;
    }
    logger.info("---------CreateLun/VolumeTask, rolling back and deleted created volume...");
    List<TaskInfo> rollBackTaskInfoList = new ArrayList<>();
    try {
        createTaskList(rollBackTaskInfoList, TaskInfoConst.Type.TASK_DELETE_LUN);
        storage.deleteVolume(volumeMO.id);
        changeTaskState(rollBackTaskInfoList, TaskInfoConst.Status.SUCCESS, "Delete volume finished.");
        for (ManagedObjectReference hostMo : hostMos) {
            hostServiceImpl.rescanAllHba(hostMo, serverInfo);
        }
    } catch (NullPointerException ex) {
        changeTaskState(rollBackTaskInfoList, TaskInfoConst.Status.ERROR,
                String.format(Locale.ROOT, "Delete volume failed: %s", ex.getMessage()));
        throw ex;
    }
}
 
Example #6
Source File: CreateDatastoreTask.java    From nbp with Apache License 2.0 6 votes vote down vote up
/**
 * run task to create datastore
 * @throws Exception
 */
@Override
public void runTask() throws Exception {
    logger.info("---------CreateDatastoreTask, running create the datastoreInfo task and convert volume to Datastore...");
    List<TaskInfo> taskInfoList = new ArrayList<>();
    ResultInfo<Object> resultInfo = hostServiceImpl.convertVmfsDatastore(hostMos, serverInfo,
            volumeMO, (VMFSDatastore)datastore);
    if (resultInfo.getStatus().equals("ok")) {
        createTaskList(taskInfoList, TaskInfoConst.Type.TASK_CREATE_DATASTORE);
        changeTaskState(taskInfoList, TaskInfoConst.Status.SUCCESS,
                String.format(Locale.ROOT, "Create Datastore %s finished.", volumeMO.name));
    } else if (resultInfo.getStatus().equals("error")) {
        changeTaskState(taskInfoList, TaskInfoConst.Status.ERROR,
                String.format(Locale.ROOT, "Create Datastore %s failed.", volumeMO.name));
        throw new Exception(resultInfo.getMsg());
    } else {
        throw new IllegalArgumentException("Result status is illegal!");
    }
}
 
Example #7
Source File: Actions.java    From development with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: VmwareContext.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #9
Source File: VSphereInfrastructure.java    From chaos-lemur with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #10
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example #11
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #12
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example #13
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: Actions.java    From development with Apache License 2.0 5 votes vote down vote up
protected String successfulTask(
        @SuppressWarnings("unused") TaskInfo taskInfo,
        VMPropertyHandler ph) {
    ph.setSetting(VMPropertyHandler.GUEST_READY_TIMEOUT_REF,
            String.valueOf(System.currentTimeMillis()));
    return EVENT_SUCCESS;
}
 
Example #15
Source File: SnapshotActions.java    From development with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #16
Source File: VMPropertyHandler.java    From development with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #17
Source File: AbstractTask.java    From nbp with Apache License 2.0 5 votes vote down vote up
/**
 * create task in ESXI host
 * @param taskInfoList List<TaskInfo>
 * @param taskType String
 */
protected void createTaskList(List<TaskInfo> taskInfoList, String taskType) {
    for (ManagedObjectReference hostMo :hostMos) {
        TaskInfo taskInfo = hostServiceImpl.createStorageTask(hostMo, serverInfo, taskType);
        taskInfoList.add(taskInfo);
    }
}
 
Example #18
Source File: Actions.java    From development with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #19
Source File: VMotionTrigger.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
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;
  }
}
 
Example #20
Source File: VMwareClient.java    From development with Apache License 2.0 4 votes vote down vote up
public TaskInfo retrieveTaskInfo(ManagedObjectReference task)
        throws Exception {

    return ((TaskInfo) getServiceUtil().getDynamicProperty(task,
            PROPERTY_INFO));
}
 
Example #21
Source File: VMotionTrigger.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
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;
  }
}
 
Example #22
Source File: TaskMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public TaskInfo getTaskInfo() throws Exception {
    return (TaskInfo)getContext().getVimClient().getDynamicProperty(_mor, "info");
}
 
Example #23
Source File: DistributedVirtualSwitchMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public TaskInfo updateVMWareDVSwitchGetTask(ManagedObjectReference dvSwitchMor, VMwareDVSConfigSpec dvsSpec) throws Exception {
    ManagedObjectReference task = _context.getService().reconfigureDvsTask(dvSwitchMor, dvsSpec);
    TaskInfo info = (TaskInfo)(_context.getVimClient().getDynamicProperty(task, "info"));
    _context.getVimClient().waitForTask(task);
    return info;
}
 
Example #24
Source File: AbstractTask.java    From nbp with Apache License 2.0 2 votes vote down vote up
/**
 * change the task state
 * @param taskInfoList List<TaskInfo>
 * @param taskStatus String
 * @param msg String
 */
protected void changeTaskState(List<TaskInfo> taskInfoList, String taskStatus, String msg) {
    for (TaskInfo taskInfo : taskInfoList) {
        hostServiceImpl.changeTaskState(taskInfo, taskStatus, msg);
    }
}
 
Example #25
Source File: HostService.java    From nbp with Apache License 2.0 2 votes vote down vote up
/**
 * Change the task state
 *
 * @param taskInfo  task info
 * @param taskState String
 * @param message   change message
 * @return
 */
Boolean changeTaskState(TaskInfo taskInfo, String taskState, String message);
 
Example #26
Source File: HostService.java    From nbp with Apache License 2.0 2 votes vote down vote up
/**
 * Create a task in host
 *
 * @param hostMo     ManagedObjectReference mob
 * @param serverInfo Server mob
 * @param taskId     String
 * @return TaskInfo
 */
TaskInfo createStorageTask(ManagedObjectReference hostMo, ServerInfo serverInfo, String taskId);