com.vmware.vim25.VirtualMachineCloneSpec Java Examples

The following examples show how to use com.vmware.vim25.VirtualMachineCloneSpec. 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: FakeModel.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
public FakeVirtualMachine addVM(String name, boolean isRunning, VirtualMachineCloneSpec spec){
  final FakeVirtualMachine vm = new FakeVirtualMachine(name, name.contains("template"), isRunning);
  putVM(name, vm);
  if (spec != null && spec.getLocation()!= null
      && VirtualMachineRelocateDiskMoveOptions.createNewChildDiskBacking.name().equals(spec.getLocation().getDiskMoveType())){
    //((FakeVirtualMachine)vm).set
  }
  if (spec != null && spec.getConfig() != null) {
    final OptionValue[] extraConfig = spec.getConfig().getExtraConfig();
    if (extraConfig != null) {
      for (OptionValue optionValue : extraConfig) {
        vm.addCustomParam(optionValue.getKey(), String.valueOf(optionValue.getValue()));
      }
    }
  }

  return vm;
}
 
Example #2
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public boolean createFullClone(String cloneName, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool, ManagedObjectReference morDs)
        throws Exception {

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

    relocSpec.setDatastore(morDs);
    relocSpec.setPool(morResourcePool);
    ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec);

    boolean result = _context.getVimClient().waitForTask(morTask);
    if (result) {
        _context.waitForTaskProgressDone(morTask);
        return true;
    } else {
        s_logger.error("VMware cloneVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
    }

    return false;
}
 
Example #3
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
protected VirtualMachineCloneSpec createCloneSpec(String computeResourceName, String resourcePoolName,
        String datastoreName) {
    VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec();

    // ComputeResource
    ComputeResource computeResource = vmwareClient.search(ComputeResource.class, computeResourceName);
    if (computeResource == null) {
        // ComputeResourceが見つからない場合
        throw new AutoException("EPROCESS-000503", computeResourceName);
    }

    // ResourcePool
    if (StringUtils.isEmpty(resourcePoolName)) {
        resourcePoolName = "Resources";
    }
    ResourcePool resourcePool = vmwareClient.search(computeResource, ResourcePool.class, resourcePoolName);
    if (resourcePool == null) {
        // ResourcePoolが見つからない場合
        throw new AutoException("EPROCESS-000504", resourcePoolName);
    }
    relocateSpec.setPool(resourcePool.getMOR());

    // Datastore
    if (StringUtils.isNotEmpty(datastoreName)) {
        // データストアが指定されている場合
        Datastore datastore = vmwareClient.search(Datastore.class, datastoreName);
        if (datastore == null) {
            // データストアが見つからない場合
            throw new AutoException("EPROCESS-000505", datastoreName);
        }
        relocateSpec.setDatastore(datastore.getMOR());
    }

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

    return cloneSpec;
}
 
Example #4
Source File: VmService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to connect to data center and clone a virtual machine identified by the inputs provided.
 *
 * @param httpInputs Object that has all the inputs necessary to made a connection to data center
 * @param vmInputs   Object that has all the specific inputs necessary to identify the virtual machine that will be
 *                   cloned
 * @return Map with String as key and value that contains returnCode of the operation, success message with task id
 *         of the execution or failure message and the exception if there is one
 * @throws Exception
 */
public Map<String, String> cloneVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception {
    ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
    try {
        ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources,
                ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName());

        if (vmMor != null) {
            VmUtils utils = new VmUtils();
            ManagedObjectReference folder = utils.getMorFolder(vmInputs.getFolderName(), connectionResources);
            ManagedObjectReference resourcePool = utils.getMorResourcePool(vmInputs.getCloneResourcePool(), connectionResources);
            ManagedObjectReference host = utils.getMorHost(vmInputs.getCloneHost(), connectionResources, vmMor);
            ManagedObjectReference dataStore = utils.getMorDataStore(vmInputs.getCloneDataStore(), connectionResources,
                    vmMor, vmInputs);

            VirtualMachineRelocateSpec vmRelocateSpec = utils.getVirtualMachineRelocateSpec(resourcePool, host, dataStore, vmInputs);

            VirtualMachineCloneSpec cloneSpec = new VmConfigSpecs().getCloneSpec(vmInputs, vmRelocateSpec);

            ManagedObjectReference taskMor = connectionResources.getVimPortType()
                    .cloneVMTask(vmMor, folder, vmInputs.getCloneName(), cloneSpec);

            return new ResponseHelper(connectionResources, taskMor).getResultsMap("Success: The [" +
                    vmInputs.getVirtualMachineName() + "] VM was successfully cloned. The taskId is: " +
                    taskMor.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be cloned.");
        } else {
            return ResponseUtils.getVmNotFoundResultsMap(vmInputs);
        }
    } catch (Exception ex) {
        return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
    } finally {
        if (httpInputs.isCloseSession()) {
            connectionResources.getConnection().disconnect();
            clearConnectionFromContext(httpInputs.getGlobalSessionObject());
        }
    }
}
 
Example #5
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 #6
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public boolean createLinkedClone(String cloneName, ManagedObjectReference morBaseSnapshot, ManagedObjectReference morFolder, ManagedObjectReference morResourcePool,
        ManagedObjectReference morDs) throws Exception {

    assert (morBaseSnapshot != null);
    assert (morFolder != null);
    assert (morResourcePool != null);
    assert (morDs != null);

    VirtualDisk[] independentDisks = getAllIndependentDiskDevice();
    VirtualMachineRelocateSpec rSpec = new VirtualMachineRelocateSpec();
    if (independentDisks.length > 0) {
        List<VirtualMachineRelocateSpecDiskLocator> diskLocator = new ArrayList<VirtualMachineRelocateSpecDiskLocator>(independentDisks.length);
        for (int i = 0; i < independentDisks.length; i++) {
            VirtualMachineRelocateSpecDiskLocator loc = new VirtualMachineRelocateSpecDiskLocator();
            loc.setDatastore(morDs);
            loc.setDiskId(independentDisks[i].getKey());
            loc.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING.value());
            diskLocator.add(loc);
        }

        rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.value());
        rSpec.getDisk().addAll(diskLocator);
    } else {
        rSpec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.CREATE_NEW_CHILD_DISK_BACKING.value());
    }
    rSpec.setPool(morResourcePool);

    VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
    cloneSpec.setPowerOn(false);
    cloneSpec.setTemplate(false);
    cloneSpec.setLocation(rSpec);
    cloneSpec.setSnapshot(morBaseSnapshot);

    ManagedObjectReference morTask = _context.getService().cloneVMTask(_mor, morFolder, cloneName, cloneSpec);

    boolean result = _context.getVimClient().waitForTask(morTask);
    if (result) {
        _context.waitForTaskProgressDone(morTask);
        return true;
    } else {
        s_logger.error("VMware cloneVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
    }

    return false;
}