com.vmware.vim25.mo.Datacenter Java Examples

The following examples show how to use com.vmware.vim25.mo.Datacenter. 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: VmwarePooledUpdateInstanceTaskTest.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
@Override
protected void setUp() throws Exception {
  super.setUp();
  myIdxStorage = createTempDir();
  FakeModel.instance().addDatacenter("dc");
  FakeModel.instance().addFolder("cf").setParent("dc", Datacenter.class);
  FakeModel.instance().addResourcePool("rp").setParentFolder("cf");
  FakeModel.instance().addVM("image1").setParentFolder("cf");
  FakeModel.instance().addVM("image2").setParentFolder("cf");
  FakeModel.instance().addVM("image_template").setParentFolder("cf");
  FakeModel.instance().addVMSnapshot("image2", "snap");
  FakeModel.instance().getCustomizationSpecs().put("someCustomization", new CustomizationSpec());
  FakeModel.instance().getCustomizationSpecs().put("linux", new CustomizationSpec());
  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null);
  setInternalProperty("teamcity.vsphere.instance.status.update.delay.ms", "250");
  myTaskManager = new MyExposingVmwareUpdateTaskManager();
}
 
Example #2
Source File: VmwareCloudIntegrationTest.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
public void check_same_datacenter() throws InterruptedException {
  FakeModel.instance().addDatacenter("dc2");
  FakeModel.instance().addFolder("cf2").setParent("dc2", Datacenter.class);
  FakeModel.instance().addResourcePool("rp2").setParentFolder("cf2");
  FakeModel.instance().addVM("image3").setParentFolder("cf");
  updateClientParameters(VmwareTestUtils.getImageParameters(PROJECT_ID,
                                                            "[{sourceVmName:'image1', behaviour:'START_STOP'}," +
      "{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp',maxInstances:3,behaviour:'ON_DEMAND_CLONE'}," +
      "{sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE + "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE'}, " +
      "{sourceVmName:'image3',snapshot:'" + VmwareConstants.CURRENT_STATE + "'," + "folder:'cf2',pool:'rp2',maxInstances:3,behaviour:'ON_DEMAND_CLONE'}]"));
  recreateClient();

  final CloudInstanceUserData userData = createUserData("image3_agent");
  final VmwareCloudInstance vmwareCloudInstance = myClient.startNewInstance(getImageByName("image3"), userData);
  new WaitFor(10 * 1000) {
    @Override
    protected boolean condition() {
      return vmwareCloudInstance.getStatus() == InstanceStatus.ERROR && vmwareCloudInstance.getErrorInfo() != null;
    }
  }.assertCompleted();

  final String msg = vmwareCloudInstance.getErrorInfo().getMessage();
  assertContains(msg, "Unable to find folder cf2 in datacenter dc");
}
 
Example #3
Source File: VmwareCloudImageTest.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  super.setUp();
  FakeModel.instance().clear();
  myTaskExecutor = new CloudAsyncTaskExecutor("Test-vmware");
  myApiConnector = new FakeApiConnector(VmwareCloudIntegrationTest.TEST_SERVER_UUID, VmwareCloudIntegrationTest.PROFILE_ID);
  myIdxStorage = createTempDir();

  myProfile = VmwareTestUtils.createProfileFromProps(new CloudClientParametersImpl(Collections.emptyMap(), Collections.emptyList()));

  Map<String, String> params = new HashMap<>();
  params.put("nickname", "imageNickname");
  params.put("sourceVmName", "srcVM");
  params.put("snapshot", "srcVMSnap");
  params.put("folder", "folderId");
  params.put("pool", "rpId");
  params.put("behaviour", CloneBehaviour.FRESH_CLONE.toString());
  params.put("maxInstances", "5");
  CloudImageParameters imageParameters = new CloudImageParametersImpl(new CloudImageDataImpl(params), myProfile.getProjectId(), UUID.randomUUID().toString());

  myImageDetails = new VmwareCloudImageDetails(imageParameters);

  FakeModel.instance().addDatacenter("dc2");
  FakeModel.instance().addFolder("folderId").setParent("dc2", Datacenter.class);
  FakeModel.instance().addVM("srcVM").setParentFolder("folderId");
  FakeModel.instance().addResourcePool("rpId").setParentFolder("folderId");

  FakeModel.instance().addVMSnapshot("srcVM", "srcVMSnap");

  myImage = new VmwareCloudImage(myApiConnector, myImageDetails, myTaskExecutor, myIdxStorage, myProfile);

  myCloudClient = new VMWareCloudClient(myProfile, myApiConnector, new VmwareUpdateTaskManager(), myIdxStorage);
  myCloudClient.populateImagesData(Collections.singletonList(myImageDetails));
  myUpdateTask = new UpdateInstancesTask<VmwareCloudInstance, VmwareCloudImage, VMWareCloudClient>(myApiConnector, myCloudClient, 10*1000, false);
}
 
Example #4
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public void deleteDisk(String datastoreName, String fileName) {
    // Datacenter
    ManagedEntity datacenter = vmwareClient.getRootEntity();

    // Datastore
    Datastore datastore = vmwareClient.search(Datastore.class, datastoreName);
    if (datastore == null) {
        // データストアが見つからない場合
        throw new AutoException("EPROCESS-000505", datastoreName);
    }

    // ディスクの削除
    FileManager fileManager = vmwareClient.getServiceInstance().getFileManager();
    if (fileManager == null) {
        // fileManagerが利用できない場合
        throw new AutoException("EPROCESS-000533");
    }

    try {
        // ディスク削除
        fileManager.deleteDatastoreFile_Task(fileName, (Datacenter) datacenter);
        // ディスク削除後にごみができ、再度アタッチするとエラーになるので削除
        String flatname;
        flatname = fileName.substring(0, fileName.length() - 5) + "-flat.vmdk";
        fileManager.deleteDatastoreFile_Task(flatname, (Datacenter) datacenter);
    } catch (RemoteException e) {
        throw new AutoException("EPROCESS-000522", e, fileName);
    }

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100455", fileName));
    }
}
 
Example #5
Source File: VmwarePooledUpdateInstanceTaskTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
public void check_called_once() throws MalformedURLException {
  final AtomicBoolean listAllCanBeCalled = new AtomicBoolean();
  final AtomicBoolean listAllCalledOnce = new AtomicBoolean();

  final AtomicBoolean getByNameCanBeCalled = new AtomicBoolean();
  final AtomicBoolean getByNameCalledOnce = new AtomicBoolean();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      if (!listAllCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(listAllCalledOnce.get());
      listAllCalledOnce.set(true);
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      if (!getByNameCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(getByNameCalledOnce.get());
      getByNameCalledOnce.set(true);
      return super.searchVMsByNames(names, dc);
    }
  };

  final CloudClientParameters clientParameters1 = VmwareTestUtils.getClientParameters(PROJECT_ID, "[{sourceVmName:'image1', behaviour:'START_STOP'}]");
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]"));
  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);

  final CloudClientParameters clientParameters3 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,
    "[{'source-id':'image_template',sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE +
    "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE', customizationSpec: 'linux'}]"));
  final VMWareCloudClient client3 = new MyClient(clientParameters3, null);

  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  final VmwareUpdateInstanceTask task3 = myTaskManager.createUpdateTask(myFakeApiConnector, client3);

  listAllCanBeCalled.set(true);
  listAllCalledOnce.set(false);
  getByNameCalledOnce.set(false);
  getByNameCanBeCalled.set(true);
  task1.run();
  task2.run();
  task3.run();
  assertTrue(listAllCalledOnce.get());
  assertTrue(getByNameCalledOnce.get());
}
 
Example #6
Source File: VmwarePooledUpdateInstanceTaskTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
public void check_cleared_after_dispose_2() throws MalformedURLException {
  final AtomicBoolean canBeCalled = new AtomicBoolean();
  final AtomicInteger callsCount = new AtomicInteger();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {
    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }

    private void processChecks() {
      if (!canBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertTrue(callsCount.get() < 2);
      callsCount.incrementAndGet();
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }
  };

  final CloudClientParameters clientParameters1 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,"[{sourceVmName:'image1', behaviour:'START_STOP'}]"));
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]"));

  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);
  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);


  canBeCalled.set(true);
  callsCount.set(0);
  task1.run();
  assertTrue(callsCount.get() > 0);

  client1.dispose();
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  canBeCalled.set(true);
  callsCount.set(0);
  task2.run();
  assertTrue(callsCount.get() > 0);


}
 
Example #7
Source File: VmwareCloudIntegrationTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  super.setUp();
  //org.apache.log4j.Logger.getLogger("jetbrains.buildServer").setLevel(Level.DEBUG);
  //org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender());

  myIdxStorage = createTempDir();

  setInternalProperty("teamcity.vsphere.instance.status.update.delay.ms", "50");
  setInternalProperty("teamcity.vmware.instance.status.check.delay", "50");
  final String json = "[{sourceVmName:'image1', behaviour:'START_STOP'}," +
                      "{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp',maxInstances:3,behaviour:'ON_DEMAND_CLONE', " +
                      "customizationSpec:'someCustomization'}," +
                      "{sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE +
                      "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE', customizationSpec: 'linux'}]";
  myClientParameters = VmwareTestUtils.getClientParameters(PROJECT_ID, json);

  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null);
  FakeModel.instance().addDatacenter("dc");
  FakeModel.instance().addFolder("cf").setParent("dc", Datacenter.class);
  FakeModel.instance().addResourcePool("rp").setParentFolder("cf");
  FakeModel.instance().addVM("image1").setParentFolder("cf");
  FakeModel.instance().addVM("image2").setParentFolder("cf");
  FakeModel.instance().addVM("image_template").setParentFolder("cf");
  FakeModel.instance().addVMSnapshot("image2", "snap");
  FakeModel.instance().getCustomizationSpecs().put("someCustomization", new CustomizationSpec());
  FakeModel.instance().getCustomizationSpecs().put("linux", new CustomizationSpec());
  myLastRunTime = new AtomicLong(0);
  myStuckTime = new AtomicLong(2*60*1000);

  myTaskManager = new VmwareUpdateTaskManager(){
    @Override
    protected VmwarePooledUpdateInstanceTask createNewPooledTask(@NotNull final VMWareApiConnector connector, @NotNull final VMWareCloudClient client) {
      return new VmwarePooledUpdateInstanceTask(connector, client, myStuckTime.get(), false){
        @Override
        public void run() {
          super.run();
          myLastRunTime.set(System.currentTimeMillis());
        }
      };
    }
  };

  recreateClient();
  assertNull(myClient.getErrorInfo());
}
 
Example #8
Source File: VmwareCloudIntegrationTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
public void do_not_clear_image_instances_list_on_error() throws ExecutionException, InterruptedException, MalformedURLException {
  final AtomicBoolean failure = new AtomicBoolean(false);
  final AtomicLong lastApiCallTime = new AtomicLong(0);
  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID){
    @Override
    protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Pair<T,Datacenter> findEntityByIdNameOld(final String name, final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findEntityByIdNameOld(name, instanceType);
    }
  };
  recreateClient(250);
  startNewInstanceAndWait("image2");
  startNewInstanceAndWait("image2");
  startNewInstanceAndWait("image2");
  Thread.sleep(5*1000);
  failure.set(true);
  final long problemStart = System.currentTimeMillis();
  new WaitFor(5*1000){

    @Override
    protected boolean condition() {
      return myLastRunTime.get() > problemStart;
    }
  }.assertCompleted("Should have been checked at least once - delay set to 2 sec");

  assertEquals(3, getImageByName("image2").getInstances().size());
}
 
Example #9
Source File: VmwareCloudIntegrationTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
public void start_instance_should_not_block_ui() throws MalformedURLException, InterruptedException, CheckedCloudException {
  final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  final Lock lock = new ReentrantLock();
  final AtomicBoolean shouldLock = new AtomicBoolean(false);
  try {
    myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID) {

      @Override
      protected <T extends ManagedEntity> T findEntityByIdNameNullableOld(final String name, final Class<T> instanceType, final Datacenter dc) throws VmwareCheckedCloudException {
        try {
          if (shouldLock.get()) {
            lock.lock(); // will stuck here
          }
          return super.findEntityByIdNameNullableOld(name, instanceType, dc);
        } finally {
          if (shouldLock.get())
            lock.unlock();
        }
      }

      @Override
      protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
        try {
          if (shouldLock.get()) {
            lock.lock(); // will stuck here
          }
          return super.findAllEntitiesOld(instanceType);
        } finally {
          if (shouldLock.get())
          lock.unlock();
        }
      }

      @Override
      protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
        try {
          if (shouldLock.get()) {
            lock.lock(); // will stuck here
          }
          return super.findAllEntitiesAsMapOld(instanceType);
        } finally {
          if (shouldLock.get())
          lock.unlock();
        }
      }

    };

    recreateClient();
    final VmwareCloudInstance startedInstance = startNewInstanceAndWait("image2");
    terminateAndDeleteIfNecessary(false, startedInstance);

    shouldLock.set(true);
    lock.lock();
    executor.execute(new Runnable() {
      public void run() {
        // start already existing clone
        myClient.startNewInstance(getImageByName("image2"), createUserData("image2_agent"));
        // start-stop instance
        myClient.startNewInstance(getImageByName("image1"), createUserData("image1_agent"));
        // clone a new one
        myClient.startNewInstance(getImageByName("image_template"), createUserData("image_template_agent"));
      }
    });
    executor.shutdown();
    assertTrue("canStart method blocks the thread!", executor.awaitTermination(100000, TimeUnit.MILLISECONDS));
  } finally {
    lock.unlock();
    executor.shutdownNow();
  }

}
 
Example #10
Source File: VmwareCloudIntegrationTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
@TestFor(issues = "TW-61456")
public void recover_if_cant_connect_on_start() throws MalformedURLException {
  final AtomicBoolean failure = new AtomicBoolean(false);
  final AtomicLong lastApiCallTime = new AtomicLong(0);
  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID){
    @Override
    protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Pair<T,Datacenter> findEntityByIdNameOld(final String name, final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findEntityByIdNameOld(name, instanceType);
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull Collection<String> names, @Nullable Datacenter dc) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.searchVMsByNames(names, dc);
    }
  };
  failure.set(true);
  recreateClient(250);
  new WaitFor(1000){
    @Override
    protected boolean condition() {
      return myClient.isInitialized();
    }
  };
  myClient.getImages().forEach(img-> assertNotNull(img.getErrorInfo()));
  failure.set(false);
  new WaitFor(1000){
    @Override
    protected boolean condition() {
      AtomicBoolean result = new AtomicBoolean(true);
      myClient.getImages().forEach(img-> result.compareAndSet(true, img.getErrorInfo()==null));
      return result.get();
    }
  };
  myClient.getImages().forEach(img-> assertNull(img.getErrorInfo()));

}
 
Example #11
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 );
	}
}