use of com.vmware.vim25.VirtualMachineCloneSpec in project photon-model by vmware.
the class InstanceClient method createInstanceFromSnapshot.
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;
}
use of com.vmware.vim25.VirtualMachineCloneSpec in project photon-model by vmware.
the class InstanceClient method cloneOvfBasedTemplate.
private ManagedObjectReference cloneOvfBasedTemplate(ManagedObjectReference vmTempl, ManagedObjectReference datastore, ManagedObjectReference folder, ManagedObjectReference resourcePool, List<VirtualMachineDefinedProfileSpec> pbmSpec) throws Exception {
String vmName = this.ctx.child.name;
Map<String, Object> props = this.get.entityProps(vmTempl, VimPath.vm_summary_config_numCpu, VimPath.vm_summary_config_memorySizeMB, VimPath.vm_snapshot, VimPath.vm_config_hardware_device, VimPath.vm_config_vAppConfig_property);
VirtualMachineSnapshotInfo snapshot = (VirtualMachineSnapshotInfo) props.get(VimPath.vm_snapshot);
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);
VirtualSCSIController scsiController = getFirstScsiController(devices);
Integer[] scsiUnit = findFreeScsiUnit(scsiController, devices.getVirtualDevice());
VirtualMachineRelocateDiskMoveOptions diskMoveOption = computeDiskMoveType();
boolean customizeImageDisk = false;
List<VirtualDeviceConfigSpec> newDisks = new ArrayList<>();
VirtualMachineRelocateSpecDiskLocator bootDiskLocator = null;
List<VirtualDisk> vDisks = null;
if (this.bootDisk != null) {
if (vd == null) {
String datastoreName = this.get.entityProp(datastore, VimPath.ds_summary_name);
String path = makePathToVmdkFile("ephemeral_disk", vmName);
String diskName = String.format(VM_PATH_FORMAT, datastoreName, path);
VirtualDeviceConfigSpec hdd = createHdd(scsiController.getKey(), scsiUnit[0], this.bootDisk, diskName, datastore, pbmSpec);
newDisks.add(hdd);
} else {
// strategy
if (this.imageDisks != null && !this.imageDisks.isEmpty()) {
vDisks = devices.getVirtualDevice().stream().filter(d -> d instanceof VirtualDisk).map(d -> (VirtualDisk) d).filter(d -> {
DiskStateExpanded ds = findMatchingImageDiskState(d, this.imageDisks);
return toKb(ds.capacityMBytes) > d.getCapacityInKB() || ds.customProperties != null;
}).collect(Collectors.toList());
if (vDisks.size() > 0) {
diskMoveOption = VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING;
logger.warn("Changing clone strategy to MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING, as there is disk resize requested");
customizeImageDisk = true;
bootDiskLocator = setProvisioningType(vDisks.get(0), datastore, pbmSpec);
}
}
}
}
VirtualCdrom vcd = devices.getVirtualDevice().stream().filter(d -> d instanceof VirtualCdrom).map(d -> (VirtualCdrom) d).findFirst().orElse(null);
// add a cdrom so that ovf transport works
if (vcd == null) {
VirtualDevice ideController = getFirstIdeController(devices);
int ideUnit = findFreeUnit(ideController, devices.getVirtualDevice());
VirtualDeviceConfigSpec cdrom = createCdrom(ideController, ideUnit);
newDisks.add(cdrom);
} else {
VirtualDeviceConfigSpec cdrom = reconfigureCdrom(vcd);
newDisks.add(cdrom);
}
VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec();
// even though this is a clone, hw config from the compute resource
// is takes precedence
spec.setNumCPUs((int) this.ctx.child.description.cpuCount);
spec.setMemoryMB(toMemoryMb(this.ctx.child.description.totalMemoryBytes));
String gt = CustomProperties.of(this.ctx.child).getString(CustomProperties.GUEST_ID, null);
if (gt != null) {
spec.setGuestId(gt);
}
// set ovf environment
ArrayOfVAppPropertyInfo infos = (ArrayOfVAppPropertyInfo) props.get(// this.get.entityProp(vmTempl,
VimPath.vm_config_vAppConfig_property);
// VimPath.vm_config_vAppConfig_property);
populateVAppProperties(spec, infos);
populateCloudConfig(spec, infos);
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);
// add disks one at a time
for (VirtualDeviceConfigSpec newDisk : newDisks) {
spec.getDeviceChange().add(newDisk);
}
// configure network
VirtualPCIController pci = getFirstPciController(devices);
for (NetworkInterfaceStateWithDetails nicWithDetails : this.ctx.nics) {
VirtualDevice nic = createNic(nicWithDetails, pci.getControllerKey());
addDeviceToVm(spec, nic);
}
// remove any networks from the template
devices.getVirtualDevice().stream().filter(d -> VirtualEthernetCard.class.isAssignableFrom(d.getClass())).forEach(d -> addRemoveDeviceFromVm(spec, d));
VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec();
if (pbmSpec != null) {
pbmSpec.stream().forEach(sp -> {
relocSpec.getProfile().add(sp);
});
}
relocSpec.setDatastore(datastore);
relocSpec.setFolder(folder);
relocSpec.setPool(resourcePool);
relocSpec.setDiskMoveType(diskMoveOption.value());
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
cloneSpec.setLocation(relocSpec);
cloneSpec.setPowerOn(false);
cloneSpec.setTemplate(false);
if (snapshot != null) {
cloneSpec.setSnapshot(snapshot.getCurrentSnapshot());
}
cloneSpec.setConfig(spec);
if (bootDiskLocator != null) {
cloneSpec.getLocation().getDisk().add(bootDiskLocator);
}
ManagedObjectReference cloneTask = getVimPort().cloneVMTask(vmTempl, folder, vmName, cloneSpec);
TaskInfo info = waitTaskEnd(cloneTask);
if (info.getState() == TaskInfoState.ERROR) {
return VimUtils.rethrow(info.getError());
}
ManagedObjectReference vmMoref = (ManagedObjectReference) info.getResult();
// Apply boot disk customization if any, if done through full clone.
if (customizeImageDisk) {
ArrayOfVirtualDevice virtualDevices = this.get.entityProp(vmMoref, VimPath.vm_config_hardware_device);
reconfigureBootDisk(vmMoref, getCustomizationConfigSpecs(virtualDevices, this.imageDisks));
}
return vmMoref;
}
use of com.vmware.vim25.VirtualMachineCloneSpec in project photon-model by vmware.
the class InstanceClient method cloneVm.
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();
}
use of com.vmware.vim25.VirtualMachineCloneSpec in project vsphere-cloud-plugin by jenkinsci.
the class VSphere method cloneOrDeployVm.
/**
* Creates a new VM by cloning an existing VM or Template.
*
* @param cloneName
* The name for the new VM.
* @param sourceName
* The name of the VM or Template that is to be cloned.
* @param linkedClone
* If true then the clone will be defined as a delta from the
* original, rather than a "full fat" copy. If this is true then
* you will need to use a snapshot.
* @param resourcePoolName
* (Optional) The name of the resource pool to use, or null.
* @param cluster
* (Optional) The name of the cluster, or null.
* @param datastoreName
* (Optional) The name of the data store, or null.
* @param folderName
* (Optional) The name or path of the VSphere folder, or null
* @param useCurrentSnapshot
* If true then the clone will be created from the source VM's
* "current" snapshot. This means that the VM <em>must</em> have
* at least one snapshot.
* @param namedSnapshot
* If set then the clone will be created from the source VM's
* snapshot of this name. If this is set then
* <code>useCurrentSnapshot</code> must not be set.
* @param powerOn
* If true then the new VM will be switched on after it has been
* created.
* @param extraConfigParameters
* (Optional) parameters to set in the VM's "extra config"
* object. This data can then be read back at a later stage.In
* the case of parameters whose name starts "guestinfo.", the
* parameter can be read by the VMware Tools on the client OS.
* e.g. a variable named "guestinfo.Foo" with value "Bar" could
* be read on the guest using the command-line
* <tt>vmtoolsd --cmd "info-get guestinfo.Foo"</tt>.
* @param customizationSpec
* (Optional) Customization spec to use for this VM, or null
* @param jLogger
* Where to log to.
* @throws VSphereException
* if anything goes wrong.
*/
public void cloneOrDeployVm(String cloneName, String sourceName, boolean linkedClone, String resourcePoolName, String cluster, String datastoreName, String folderName, boolean useCurrentSnapshot, final String namedSnapshot, boolean powerOn, Map<String, String> extraConfigParameters, String customizationSpec, PrintStream jLogger) throws VSphereException {
try {
final VirtualMachine sourceVm = getVmByName(sourceName);
if (sourceVm == null) {
throw new VSphereNotFoundException("VM or template", sourceName);
}
if (getVmByName(cloneName) != null) {
throw new VSphereDuplicateException("VM", cloneName);
}
final VirtualMachineConfigInfo vmConfig = sourceVm.getConfig();
final boolean sourceIsATemplate = vmConfig.template;
final String sourceType = sourceIsATemplate ? "Template" : "VM";
final VirtualMachineRelocateSpec rel = createRelocateSpec(jLogger, linkedClone, resourcePoolName, cluster, datastoreName, sourceIsATemplate);
final VirtualMachineCloneSpec cloneSpec = createCloneSpec(rel);
cloneSpec.setTemplate(false);
cloneSpec.powerOn = powerOn;
if (namedSnapshot != null && !namedSnapshot.isEmpty()) {
if (useCurrentSnapshot) {
throw new IllegalArgumentException("It is not valid to request a clone of " + sourceType + " \"" + sourceName + "\" based on its snapshot \"" + namedSnapshot + "\" AND also specify that the latest snapshot should be used. Either choose to use the latest snapshot, or name a snapshot, or neither, but not both.");
}
final VirtualMachineSnapshot namedVMSnapshot = getSnapshotInTree(sourceVm, namedSnapshot);
if (namedVMSnapshot == null) {
throw new VSphereNotFoundException("Snapshot", namedSnapshot, "Source " + sourceType + " \"" + sourceName + "\" has no snapshot called \"" + namedSnapshot + "\".");
}
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will be based on named snapshot \"" + namedSnapshot + "\".");
cloneSpec.setSnapshot(namedVMSnapshot.getMOR());
}
if (useCurrentSnapshot) {
final VirtualMachineSnapshot currentSnapShot = sourceVm.getCurrentSnapShot();
if (currentSnapShot == null) {
throw new VSphereNotFoundException("Snapshot", null, "Source " + sourceType + " \"" + sourceName + "\" requires at least one snapshot.");
}
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will be based on current snapshot \"" + currentSnapShot.toString() + "\".");
cloneSpec.setSnapshot(currentSnapShot.getMOR());
}
if (extraConfigParameters != null && !extraConfigParameters.isEmpty()) {
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will have extra configuration parameters " + extraConfigParameters + ".");
VirtualMachineConfigSpec cs = createVMConfigSpecFromExtraConfigParameters(extraConfigParameters);
cloneSpec.setConfig(cs);
}
if (customizationSpec != null && customizationSpec.length() > 0) {
logMessage(jLogger, "Clone of " + sourceType + " \"" + sourceName + "\" will use customization specification \"" + customizationSpec + "\".");
CustomizationSpecItem spec = getCustomizationSpecByName(customizationSpec);
cloneSpec.setCustomization(spec.getSpec());
}
Folder folder;
if (folderName == null || folderName.isEmpty() || folderName.equals(" ")) {
// same folder as source
folder = (Folder) sourceVm.getParent();
} else if (!folderExists(folderName)) {
folder = (Folder) sourceVm.getParent();
logMessage(jLogger, "Unable to find the specified folder. Creating VM in the same folder as its parent ");
} else {
folder = getFolder(folderName);
}
final Task task = sourceVm.cloneVM_Task(folder, cloneName, cloneSpec);
logMessage(jLogger, "Started cloning of " + sourceType + " \"" + sourceName + "\". Please wait ...");
final String status = task.waitForTask();
if (!TaskInfoState.success.toString().equals(status)) {
throw newVSphereException(task.getTaskInfo(), "Couldn't clone \"" + sourceName + "\". " + "Clone task ended with status " + status + ".");
}
logMessage(jLogger, "Successfully cloned VM \"" + sourceName + "\" to create \"" + cloneName + "\".");
} catch (RuntimeException | VSphereException e) {
throw e;
} catch (Exception e) {
throw new VSphereException(e);
}
}
use of com.vmware.vim25.VirtualMachineCloneSpec in project cs-actions by CloudSlang.
the class VmService method cloneVM.
/**
* 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());
}
}
}
Aggregations