use of com.vmware.vim25.mo.ResourcePool in project photon-model by vmware.
the class InstanceClient method replicateVMTemplate.
private ManagedObjectReference replicateVMTemplate(ManagedObjectReference resourcePool, ManagedObjectReference datastore, List<VirtualMachineDefinedProfileSpec> pbmSpec, ManagedObjectReference vmFolder, String vmName, ManagedObjectReference vm, GetMoRef get) throws Exception {
logger.info("Template lives on a different datastore, looking for a local copy of: {}.", vmName);
String replicatedName = vmName;
if (datastore != null) {
replicatedName = replicatedName + "_" + datastore.getValue();
}
ManagedObjectReference repVm = findTemplateByName(replicatedName, get);
if (repVm != null) {
return repVm;
}
logger.info("Replicating {} ({}) to {}", vmName, vm.getValue(), replicatedName);
Lock lock = getLock(replicatedName);
lock.lock();
try {
VirtualMachineRelocateSpec spec = new VirtualMachineRelocateSpec();
spec.setPool(resourcePool);
if (datastore != null) {
spec.setDatastore(datastore);
}
if (pbmSpec != null) {
pbmSpec.stream().forEach(sp -> {
spec.getProfile().add(sp);
});
}
spec.setFolder(vmFolder);
spec.setDiskMoveType(VirtualMachineRelocateDiskMoveOptions.MOVE_ALL_DISK_BACKINGS_AND_DISALLOW_SHARING.value());
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
cloneSpec.setLocation(spec);
cloneSpec.setTemplate(false);
cloneSpec.setPowerOn(false);
ManagedObjectReference cloneTask = getVimPort().cloneVMTask(vm, vmFolder, replicatedName, cloneSpec);
TaskInfo info = VimUtils.waitTaskEnd(this.connection, cloneTask);
if (info.getState() == TaskInfoState.ERROR) {
MethodFault fault = info.getError().getFault();
if (fault instanceof DuplicateName) {
logger.info("Template is being replicated by another thread, waiting for {} to be ready", replicatedName);
return awaitVM(replicatedName, vmFolder, get);
} else {
return VimUtils.rethrow(info.getError());
}
}
ManagedObjectReference rvm = (ManagedObjectReference) info.getResult();
logger.info("Replicated {} ({}) to {} ({})", vmName, vm.getValue(), replicatedName, rvm.getValue());
logger.info("Creating initial snapshot for linked clones on {}", rvm.getValue());
ManagedObjectReference snapshotTask = getVimPort().createSnapshotTask(rvm, "initial", null, false, false);
VimUtils.waitTaskEnd(this.connection, snapshotTask);
logger.info("Created initial snapshot for linked clones on {}", rvm.getValue());
return rvm;
} finally {
lock.unlock();
}
}
use of com.vmware.vim25.mo.ResourcePool 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.mo.ResourcePool 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.mo.ResourcePool in project photon-model by vmware.
the class InstanceClient method deployOvf.
private ManagedObjectReference deployOvf(URI ovfUri) throws Exception {
OvfDeployer deployer = new OvfDeployer(this.connection);
CustomProperties cust = CustomProperties.of(this.ctx.child.description);
URI archiveUri = cust.getUri(OvfParser.PROP_OVF_ARCHIVE_URI);
if (archiveUri != null) {
logger.info("Prefer ova {} uri to ovf {}", archiveUri, ovfUri);
OvfRetriever retriever = deployer.getRetriever();
ovfUri = retriever.downloadIfOva(archiveUri);
}
ManagedObjectReference folder = getVmFolder();
List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(this.bootDisk);
ManagedObjectReference ds = getDataStoreForDisk(this.bootDisk, pbmSpec);
ManagedObjectReference resourcePool = getResourcePool();
String vmName = "pmt-" + deployer.getRetriever().hash(ovfUri);
GetMoRef get = new GetMoRef(this.connection);
ManagedObjectReference vm = findTemplateByName(vmName, get);
if (vm == null) {
String config = cust.getString(OvfParser.PROP_OVF_CONFIGURATION);
Lock lock = getLock(vmName);
lock.lock();
try {
vm = findTemplateByName(vmName, get);
if (vm == null) {
OvfParser parser = new OvfParser();
Document ovfDoc = parser.retrieveDescriptor(ovfUri);
List<OvfNetworkMapping> networks = mapNetworks(parser.extractNetworks(ovfDoc), ovfDoc, this.ctx.nics);
vm = deployer.deployOvf(ovfUri, getHost(), folder, vmName, networks, ds, Collections.emptyList(), config, resourcePool);
logger.info("Removing NICs from deployed template: {} ({})", vmName, vm.getValue());
ArrayOfVirtualDevice devices = get.entityProp(vm, VimPath.vm_config_hardware_device);
if (devices != null) {
VirtualMachineConfigSpec reconfig = new VirtualMachineConfigSpec();
for (VirtualDevice device : devices.getVirtualDevice()) {
if (device instanceof VirtualEthernetCard) {
VirtualDeviceConfigSpec spec = new VirtualDeviceConfigSpec();
spec.setDevice(device);
spec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);
reconfig.getDeviceChange().add(spec);
}
}
ManagedObjectReference reconfigTask = getVimPort().reconfigVMTask(vm, reconfig);
VimUtils.waitTaskEnd(this.connection, reconfigTask);
}
ManagedObjectReference snapshotTask = getVimPort().createSnapshotTask(vm, "initial", null, false, false);
VimUtils.waitTaskEnd(this.connection, snapshotTask);
}
} catch (Exception e) {
logger.warn("Error deploying Ovf for template [" + vmName + "],reason:", e);
vm = awaitVM(vmName, folder, get);
} finally {
lock.unlock();
}
}
if (!isSameDatastore(ds, vm, get)) {
// make sure the original VM template is ready
Object snapshot = get.entityProp(vm, VimPath.vm_snapshot);
if (snapshot == null) {
vm = awaitVM(vmName, folder, get);
}
vm = replicateVMTemplate(resourcePool, ds, pbmSpec, folder, vmName, vm, get);
}
return cloneOvfBasedTemplate(vm, ds, folder, resourcePool, pbmSpec);
}
use of com.vmware.vim25.mo.ResourcePool in project photon-model by vmware.
the class InstanceClient method createVm.
/**
* Creates a VM in vsphere. This method will block until the CreateVM_Task completes. The path
* to the .vmx file is explicitly set and its existence is iterpreted as if the VM has been
* successfully created and returns null.
*
* @return
* @throws FinderException
* @throws Exception
*/
private ManagedObjectReference createVm() throws Exception {
ManagedObjectReference folder = getVmFolder();
List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(this.bootDisk);
ManagedObjectReference datastore = getDataStoreForDisk(this.bootDisk, pbmSpec);
ManagedObjectReference resourcePool = getResourcePool();
ManagedObjectReference host = getHost();
// datastore from that.
if (datastore == null) {
ManagedObjectReference dsFromSp = getDatastoreFromStoragePolicy(this.connection, pbmSpec);
datastore = dsFromSp == null ? getDatastore() : dsFromSp;
}
String datastoreName = this.get.entityProp(datastore, "name");
VirtualMachineConfigSpec spec = buildVirtualMachineConfigSpec(datastoreName);
String gt = CustomProperties.of(this.ctx.child).getString(CustomProperties.GUEST_ID, null);
if (gt != null) {
try {
gt = VirtualMachineGuestOsIdentifier.valueOf(gt).value();
} catch (IllegalArgumentException e) {
// silently default to generic 64 bit guest.
gt = DEFAULT_GUEST_ID.value();
}
spec.setGuestId(gt);
}
populateCloudConfig(spec, null);
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);
ManagedObjectReference vmTask = getVimPort().createVMTask(folder, spec, resourcePool, host);
TaskInfo info = waitTaskEnd(vmTask);
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();
}
Aggregations