use of com.vmware.vim25.mo.Datastore in project photon-model by vmware.
the class Lister method listFolder.
private List<Element> listFolder() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException {
PropertyFilterSpec spec = new PropertyFilterSpec();
ObjectSpec objSpec = new ObjectSpec();
objSpec.setObj(this.start);
TraversalSpec selectionSpec = new TraversalSpec();
selectionSpec.setPath("childEntity");
selectionSpec.setType("Folder");
selectionSpec.setSkip(false);
objSpec.getSelectSet().add(selectionSpec);
spec.getObjectSet().add(objSpec);
// Retrieve all objects that we can deal with
String[] childTypes = { "Folder", "Datacenter", "VirtualMachine", "Network", "ComputeResource", "ClusterComputeResource", "Datastore" };
for (String t : childTypes) {
PropertySpec pspec = new PropertySpec();
pspec.setType(t);
pspec.getPathSet().add("name");
// Additional basic properties.
if (t.equals("ComputeResource") || t.equals("ClusterComputeResource")) {
// The ComputeResource and ClusterComputeResource are dereferenced in
// the ResourcePoolFlag. Make sure they always have their resourcePool
// field populated.
pspec.getPathSet().add("resourcePool");
}
spec.getPropSet().add(pspec);
}
return callPropertyCollectorAndConvert(spec);
}
use of com.vmware.vim25.mo.Datastore in project photon-model by vmware.
the class Lister method listDatacenter.
private List<Element> listDatacenter() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException {
ObjectSpec ospec = new ObjectSpec();
ospec.setObj(this.start);
ospec.setSkip(true);
// Include every datastore folder in the select set
String[] fields = { "vmFolder", "hostFolder", "datastoreFolder", "networkFolder", "datastore" };
for (String f : fields) {
TraversalSpec tspec = new TraversalSpec();
tspec.setPath(f);
tspec.setSkip(false);
tspec.setType(VimNames.TYPE_DATACENTER);
ospec.getSelectSet().add(tspec);
}
PropertySpec pspec = new PropertySpec();
pspec.setType(VimNames.TYPE_FOLDER);
pspec.getPathSet().add(VimNames.PROPERTY_NAME);
PropertySpec dcspec = new PropertySpec();
dcspec.setType(VimNames.TYPE_DATACENTER);
dcspec.getPathSet().add(VimNames.PROPERTY_NAME);
PropertySpec dsspec = new PropertySpec();
dsspec.setType(VimNames.TYPE_DATASTORE);
dsspec.getPathSet().add(VimNames.PROPERTY_NAME);
PropertyFilterSpec spec = new PropertyFilterSpec();
spec.getObjectSet().add(ospec);
spec.getPropSet().add(pspec);
spec.getPropSet().add(dcspec);
spec.getPropSet().add(dsspec);
return callPropertyCollectorAndConvert(spec);
}
use of com.vmware.vim25.mo.Datastore in project photon-model by vmware.
the class DiskContext method populateContextThen.
/**
* Populates the given initial context and invoke the onSuccess handler when built. At every
* step, if failure occurs the DiskContext's errorHandler is invoked to cleanup.
*/
public static void populateContextThen(Service service, DiskContext ctx, Consumer<DiskContext> onSuccess) {
// Step 1: Get disk details
if (ctx.diskState == null) {
URI diskUri = createInventoryUri(service.getHost(), DiskService.DiskStateExpanded.buildUri(ctx.diskReference));
AdapterUtils.getServiceState(service, diskUri, op -> {
ctx.diskState = op.getBody(DiskService.DiskStateExpanded.class);
EnumSet<DiskService.DiskType> notSupportedTypes = EnumSet.of(DiskService.DiskType.SSD, DiskService.DiskType.NETWORK);
if (notSupportedTypes.contains(ctx.diskState.type)) {
ctx.fail(new IllegalStateException(String.format("Not supported disk type %s.", ctx.diskState.type)));
return;
}
populateContextThen(service, ctx, onSuccess);
}, ctx.errorHandler);
return;
}
// the disk.
if (ctx.datastoreName == null && ctx.diskInstanceRequest.requestType == DiskInstanceRequest.DiskRequestType.CREATE) {
if (ctx.diskState.storageDescription != null) {
ctx.datastoreName = ctx.diskState.storageDescription.id;
populateContextThen(service, ctx, onSuccess);
} else if (ctx.diskState.resourceGroupStates != null && !ctx.diskState.resourceGroupStates.isEmpty()) {
// There will always be only one resource group state existing for a disk
ResourceGroupState resource = ctx.diskState.resourceGroupStates.iterator().next();
ClientUtils.getDatastoresForProfile(service, resource.documentSelfLink, ctx.diskState.endpointLink, ctx.diskState.tenantLinks, ctx.errorHandler, (result) -> {
if (result.documents != null && result.documents.size() > 0) {
// pick the first datastore and proceed.
StorageDescription dsStorageDesc = Utils.fromJson(result.documents.values().iterator().next(), StorageDescription.class);
ctx.datastoreName = dsStorageDesc.id;
ctx.diskState.storageDescriptionLink = dsStorageDesc.documentSelfLink;
} else {
// Since no result found default to the available datastore.
ctx.datastoreName = "";
}
populateContextThen(service, ctx, onSuccess);
});
} else if (CustomProperties.of(ctx.diskState).getString(CustomProperties.DISK_DATASTORE_NAME) != null) {
ctx.datastoreName = CustomProperties.of(ctx.diskState).getString(CustomProperties.DISK_DATASTORE_NAME);
populateContextThen(service, ctx, onSuccess);
} else {
// Mark empty so that it can fall back to any available datastore from the system.
ctx.datastoreName = "";
populateContextThen(service, ctx, onSuccess);
}
return;
}
// Step 3: Get Credentials
if (ctx.vSphereCredentials == null) {
if (IAAS_API_ENABLED) {
if (ctx.operation == null) {
ctx.fail(new IllegalArgumentException("Caller operation cannot be empty"));
return;
}
SessionUtil.retrieveExternalToken(service, ctx.operation.getAuthorizationContext()).whenComplete((authCredentialsServiceState, throwable) -> {
if (throwable != null) {
ctx.errorHandler.accept(throwable);
return;
}
ctx.vSphereCredentials = authCredentialsServiceState;
populateContextThen(service, ctx, onSuccess);
});
} else {
if (ctx.diskState.authCredentialsLink == null || ctx.diskState.authCredentialsLink.isEmpty()) {
ctx.fail(new IllegalArgumentException("Auth credentials cannot be empty"));
return;
}
URI credUri = createInventoryUri(service.getHost(), ctx.diskState.authCredentialsLink);
AdapterUtils.getServiceState(service, credUri, op -> {
ctx.vSphereCredentials = op.getBody(AuthCredentialsServiceState.class);
populateContextThen(service, ctx, onSuccess);
}, ctx.errorHandler);
}
return;
}
// Step 4: Get the endpoint compute link
if (ctx.endpointComputeLink == null) {
URI endpointUri = createInventoryUri(service.getHost(), UriUtils.buildUri(service.getHost(), ctx.diskState.endpointLink));
AdapterUtils.getServiceState(service, endpointUri, op -> {
EndpointService.EndpointState endpointState = op.getBody(EndpointService.EndpointState.class);
ctx.endpointComputeLink = endpointState.computeLink;
populateContextThen(service, ctx, onSuccess);
}, ctx.errorHandler);
return;
}
// Step 5: Get the adapter reference to from the endpoint compute link
if (ctx.adapterManagementReference == null) {
URI computeUri = createInventoryUri(service.getHost(), UriUtils.buildUri(service.getHost(), ctx.endpointComputeLink));
AdapterUtils.getServiceState(service, computeUri, op -> {
ComputeService.ComputeState computeState = op.getBody(ComputeService.ComputeState.class);
ctx.adapterManagementReference = computeState.adapterManagementReference;
populateContextThen(service, ctx, onSuccess);
}, ctx.errorHandler);
return;
}
// Step 6: Obtain reference to the datacenter moref.
if (ctx.datacenterMoRef == null) {
try {
ctx.datacenterMoRef = VimUtils.convertStringToMoRef(ctx.diskState.regionId);
} catch (IllegalArgumentException ex) {
ctx.fail(ex);
return;
}
}
onSuccess.accept(ctx);
}
use of com.vmware.vim25.mo.Datastore 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.Datastore 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;
}
Aggregations