com.vmware.vim25.mo.Task Java Examples

The following examples show how to use com.vmware.vim25.mo.Task. 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: VmwareTaskWrapper.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
public VmwareTaskWrapper(@NotNull final Callable<Task> vmwareTask, String taskName){
  myVmwareTask = vmwareTask;
  myTaskName = taskName;
  myResultLazy = new Lazy<CloudTaskResult>() {
    @Nullable
    @Override
    protected CloudTaskResult createValue() {
      try {
        myStartTime = System.currentTimeMillis();
        return getResult(myVmwareTask.call());
      } catch (Exception e) {
        return createErrorTaskResult(e);
      } finally {
        myIsDone.set(true);
      }
    }
  };
}
 
Example #2
Source File: VmwareCloudImage.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
private synchronized void reconfigureVmTask(@NotNull final VmwareCloudInstance instance, @NotNull final CloudInstanceUserData cloudInstanceUserData) {
  myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() {
                                     public Task call() throws Exception {
                                       return myApiConnector.reconfigureInstance(instance, instance.getName(), cloudInstanceUserData);
                                     }
                                   }, "Reconfigure " + instance.getName())
    , new ImageStatusTaskWrapper(instance) {
      @Override
      public void onSuccess() {
        instance.setStatus(InstanceStatus.RUNNING);
        instance.setStartDate(new Date());
        instance.updateErrors();
        LOG.info("Reconfiguration of '" + instance.getInstanceId() + "' is finished. Instance started successfully");
      }

      @Override
      public void onError(final Throwable th) {
        LOG.warnAndDebugDetails("Can't reconfigure '" + instance.getInstanceId() +"'. Instance will be terminated", th);
        terminateInstance(instance);
      }
    });
}
 
Example #3
Source File: VmwareCloudImage.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
public void terminateInstance(@NotNull final VmwareCloudInstance instance) {

    LOG.info("Stopping instance " + instance.getName());
    instance.setStatus(InstanceStatus.SCHEDULED_TO_STOP);
    myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() {
      public Task call() throws Exception {
        return myApiConnector.stopInstance(instance);
      }
    }, "Stop " + instance.getName()), new ImageStatusTaskWrapper(instance){

      @Override
      public void onComplete() {
        instance.setStatus(InstanceStatus.STOPPED);
        if (myImageDetails.getBehaviour().isDeleteAfterStop()) { // we only destroy proper instances.
          deleteInstance(instance);
        }
      }
    });

  }
 
Example #4
Source File: VmwareCloudImage.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
private void deleteInstance(@NotNull final VmwareCloudInstance instance){
  if (instance.getErrorInfo() == null) {
    LOG.info("Will delete instance " + instance.getName());
    myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() {
      public Task call() throws Exception {
        return myApiConnector.deleteInstance(instance);
      }
    }, "Delete " + instance.getName()), new ImageStatusTaskWrapper(instance) {
      @Override
      public void onSuccess() {
        removeInstance(instance.getName());
      }
    });
  } else {
    LOG.warn(String.format("Won't delete instance %s with error: %s (%s)",
                           instance.getName(), instance.getErrorInfo().getMessage(), instance.getErrorInfo().getDetailedMessage()));
  }
}
 
Example #5
Source File: VmwareCloudImage.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
private synchronized void startVM(@NotNull final VmwareCloudInstance instance, @NotNull final CloudInstanceUserData cloudInstanceUserData) {
  instance.setStartDate(new Date());
  instance.setStatus(InstanceStatus.STARTING);
  myAsyncTaskExecutor.executeAsync(new VmwareTaskWrapper(new Callable<Task>() {
    public Task call() throws Exception {
      return myApiConnector.startInstance(instance, instance.getName(), cloudInstanceUserData);
    }
  }, "Start instance " + instance.getName())
    , new ImageStatusTaskWrapper(instance) {
    @Override
    public void onSuccess() {
      reconfigureVmTask(instance, cloudInstanceUserData);
    }
  });
}
 
Example #6
Source File: VmwareCloudImageTest.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
public void check_can_start_new_instance_limits() throws RemoteException, InterruptedException {
  final CloudInstanceUserData data = new CloudInstanceUserData("aaa", "bbbb", "localhost", 10000l, "profileDescr", Collections.<String, String>emptyMap());
  assertTrue(myImage.canStartNewInstance());
  myImage.startNewInstance(data);
  assertTrue(myImage.canStartNewInstance());
  myImage.startNewInstance(data);
  assertTrue(myImage.canStartNewInstance());
  myImage.startNewInstance(data);
  assertTrue(myImage.canStartNewInstance());
  myImage.startNewInstance(data);
  assertTrue(myImage.canStartNewInstance());
  final VmwareCloudInstance instance2Stop = myImage.startNewInstance(data);
  assertFalse(myImage.canStartNewInstance());
  new WaitFor(5*1000){

    @Override
    protected boolean condition() {
      return instance2Stop.getStatus() == InstanceStatus.RUNNING;
    }
  };
  final FakeVirtualMachine vm2Stop = FakeModel.instance().getVirtualMachine(instance2Stop.getName());
  final String result = vm2Stop.powerOffVM_Task().waitForTask();
  assertEquals(Task.SUCCESS, result);
  instance2Stop.setStatus(InstanceStatus.STOPPED);
  assertTrue(myImage.canStartNewInstance());
  System.setProperty(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT, "true");
  assertFalse(myImage.canStartNewInstance());
  System.getProperties().remove(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT);
  assertTrue(myImage.canStartNewInstance());
}
 
Example #7
Source File: VmwareCloudImageTest.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
public void terminate_instance_if_cant_reconfigure() throws IOException {
  final CloudInstanceUserData data = new CloudInstanceUserData("aaa", "bbbb", "localhost", 10000l, "profileDescr", Collections.<String, String>emptyMap());
  final AtomicBoolean stopInstanceCalled = new AtomicBoolean();
  myApiConnector = new FakeApiConnector(VmwareCloudIntegrationTest.TEST_SERVER_UUID, VmwareCloudIntegrationTest.PROFILE_ID){
    @Override
    public Task reconfigureInstance(@NotNull final VmwareCloudInstance instance, @NotNull final String agentName, @NotNull final CloudInstanceUserData userData)
      throws VmwareCheckedCloudException {
      return FakeVirtualMachine.failureTask();
    }

    @Override
    public Task stopInstance(@NotNull final VmwareCloudInstance instance) {
      stopInstanceCalled.set(true);
      return super.stopInstance(instance);
    }
  };
  myImage = new VmwareCloudImage(myApiConnector, myImageDetails, myTaskExecutor, myIdxStorage, myProfile);

  myCloudClient = new VMWareCloudClient(myProfile, myApiConnector, new VmwareUpdateTaskManager(), createTempDir());
  myCloudClient.populateImagesData(Collections.singletonList(myImageDetails));

  myImage.startNewInstance(data);

  new WaitFor(1000){

    @Override
    protected boolean condition() {
      return stopInstanceCalled.get();
    }
  };

  assertTrue("Should have stopped if can't reconfigure", stopInstanceCalled.get());
}
 
Example #8
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 #9
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 #10
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 #11
Source File: VMWareApiConnector.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
@Nullable
Task startInstance(VmwareCloudInstance instance, String agentName, CloudInstanceUserData userData)
  throws VmwareCheckedCloudException, InterruptedException;
 
Example #12
Source File: VMWareApiConnector.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
Task reconfigureInstance(@NotNull final VmwareCloudInstance instance,
@NotNull final String agentName,
@NotNull final CloudInstanceUserData userData) throws VmwareCheckedCloudException;
 
Example #13
Source File: VmwareIaasHandler.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Override
public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

	this.logger.fine( "Creating a new VM @ VMware." );

	// For IaaS, we only expect root instance names to be passed
	if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 )
		throw new TargetException( "Only root instances can be passed in arguments." );

	String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());

	// Deal with the creation
	try {
		System.setProperty("org.xml.sax.driver","org.apache.xerces.parsers.SAXParser");
		Map<String,String> targetProperties = parameters.getTargetProperties();
		final String machineImageId = targetProperties.get( TEMPLATE );
		final ServiceInstance vmwareServiceInstance = getServiceInstance( targetProperties );

		final ComputeResource vmwareComputeResource = (ComputeResource)(
				new InventoryNavigator( vmwareServiceInstance.getRootFolder())
				.searchManagedEntity("ComputeResource", targetProperties.get( CLUSTER )));

		// Generate the user data first, so that nothing has been done on the IaaS if it fails
		String userData = UserDataHelpers.writeUserDataAsString(
				parameters.getMessagingProperties(),
				parameters.getDomain(),
				parameters.getApplicationName(),
				rootInstanceName );

		VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineImageId );
		String vmwareDataCenter = targetProperties.get( DATA_CENTER );
		Folder vmFolder =
				((Datacenter)(new InventoryNavigator( vmwareServiceInstance.getRootFolder())
				.searchManagedEntity("Datacenter", vmwareDataCenter)))
				.getVmFolder();

		this.logger.fine("machineImageId=" + machineImageId);
		if (vm == null || vmFolder == null)
			throw new TargetException("VirtualMachine (= " + vm + " ) or Datacenter path (= " + vmFolder + " ) is NOT correct. Please, double check.");

		VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
		cloneSpec.setLocation(new VirtualMachineRelocateSpec());
		cloneSpec.setPowerOn(false);
		cloneSpec.setTemplate(true);

		VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec();
		vmSpec.setAnnotation( userData );
		cloneSpec.setConfig(vmSpec);

		Task task = vm.cloneVM_Task( vmFolder, rootInstanceName, cloneSpec );
		this.logger.fine("Cloning the template: "+ machineImageId +" ...");
		String status = task.waitForTask();
		if (!status.equals(Task.SUCCESS))
			throw new TargetException("Failure: Virtual Machine cannot be cloned." );

		VirtualMachine vm2 = getVirtualMachine( vmwareServiceInstance, rootInstanceName );
		this.logger.fine("Transforming the clone template to Virtual machine ...");
		vm2.markAsVirtualMachine( vmwareComputeResource.getResourcePool(), null);

		DynamicProperty dprop = new DynamicProperty();
		dprop.setName("guestinfo.userdata");
		dprop.setVal(userData);
		vm2.getGuest().setDynamicProperty(new DynamicProperty[]{dprop});

		task = vm2.powerOnVM_Task(null);
		this.logger.fine("Starting the virtual machine: "+ rootInstanceName +" ...");
		status = task.waitForTask();
		if( ! status.equals( Task.SUCCESS ))
			throw new TargetException("Failure: Virtual Machine cannot be started." );

		return vm2.getName();

	} catch( Exception e ) {
		throw new TargetException( e );
	}
}
 
Example #14
Source File: VMWareApiConnector.java    From teamcity-vmware-plugin with Apache License 2.0 votes vote down vote up
Task cloneAndStartVm(@NotNull final VmwareCloudInstance instance) throws VmwareCheckedCloudException; 
Example #15
Source File: VMWareApiConnector.java    From teamcity-vmware-plugin with Apache License 2.0 votes vote down vote up
Task stopInstance(VmwareCloudInstance instance); 
Example #16
Source File: VMWareApiConnector.java    From teamcity-vmware-plugin with Apache License 2.0 votes vote down vote up
Task deleteInstance(VmwareCloudInstance instance);