Search in sources :

Example 1 with DiskStateExpanded

use of com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded in project photon-model by vmware.

the class ClientUtils method handleVirtualDiskUpdate.

/**
 * Process VirtualDisk and update the details in the diskLinks of the provisioned compute
 */
public static Operation handleVirtualDiskUpdate(String endpointLink, DiskStateExpanded matchedDs, VirtualDisk disk, List<String> diskLinks, String regionId, Service service, String vm, String dcLink, EnumerationProgress ctx, ComputeState oldDocument) {
    if (disk.getBacking() == null || !(disk.getBacking() instanceof VirtualDeviceFileBackingInfo)) {
        return null;
    }
    VirtualDeviceFileBackingInfo backing = (VirtualDeviceFileBackingInfo) disk.getBacking();
    Operation operation;
    DiskService.DiskState ds;
    if (matchedDs == null) {
        // This is the new disk, hence add it to the list
        ds = new DiskService.DiskStateExpanded();
        ds.documentSelfLink = UriUtils.buildUriPath(DiskService.FACTORY_LINK, service.getHost().nextUUID());
        ds.name = disk.getDeviceInfo().getLabel();
        ds.creationTimeMicros = Utils.getNowMicrosUtc();
        ds.type = DiskService.DiskType.HDD;
        ds.regionId = regionId;
        ds.capacityMBytes = disk.getCapacityInKB() / 1024;
        ds.sourceImageReference = VimUtils.datastorePathToUri(backing.getFileName());
        ds.persistent = Boolean.FALSE;
        addEndpointLinks(ds, endpointLink);
        updateDiskStateFromVirtualDisk(disk, ds);
        updateDiskStateFromBackingInfo(backing, ds);
        if (disk.getStorageIOAllocation() != null) {
            StorageIOAllocationInfo storageInfo = disk.getStorageIOAllocation();
            CustomProperties.of(ds).put(SHARES, storageInfo.getShares().getShares()).put(LIMIT_IOPS, storageInfo.getLimit()).put(SHARES_LEVEL, storageInfo.getShares().getLevel().value());
        }
        if (null != oldDocument) {
            // we have vm state document, populate vm self link in disk state
            CustomProperties.of(ds).put(VIRTUAL_MACHINE_LINK, oldDocument.documentSelfLink);
        }
        fillInControllerUnitNumber(ds, disk.getUnitNumber());
        diskLinks.add(ds.documentSelfLink);
    } else {
        // This is known disk, hence update with the provisioned attributes.
        ds = matchedDs;
        ds.sourceImageReference = VimUtils.datastorePathToUri(backing.getFileName());
        if (matchedDs.persistent == null) {
            matchedDs.persistent = Boolean.FALSE;
        }
        ds.regionId = regionId;
        addEndpointLinks(ds, endpointLink);
        updateDiskStateFromVirtualDisk(disk, ds);
        updateDiskStateFromBackingInfo(backing, ds);
    }
    CustomProperties.of(ds).put(CustomProperties.DISK_DATASTORE_NAME, backing.getDatastore().getValue()).put(CustomProperties.TYPE, VirtualDisk.class.getSimpleName()).put(CustomProperties.DISK_PROVISION_IN_GB, disk.getCapacityInKB() / (1024 * 1024)).put(CustomProperties.DATACENTER_SELF_LINK, dcLink).put(CustomProperties.DISK_PARENT_VM, vm);
    // Disk needs the VMs MoRef for the functional Key
    if (ctx != null) {
        VsphereEnumerationHelper.populateResourceStateWithAdditionalProps(ds, ctx.getVcUuid(), VimUtils.convertStringToMoRef(vm));
    }
    operation = (matchedDs == null) ? createDisk(ds, service) : createDiskPatch(ds, service);
    return operation;
}
Also used : StorageIOAllocationInfo(com.vmware.vim25.StorageIOAllocationInfo) VirtualDeviceFileBackingInfo(com.vmware.vim25.VirtualDeviceFileBackingInfo) DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) VirtualDeviceConfigSpecFileOperation(com.vmware.vim25.VirtualDeviceConfigSpecFileOperation) Operation(com.vmware.xenon.common.Operation) VirtualDeviceConfigSpecOperation(com.vmware.vim25.VirtualDeviceConfigSpecOperation) DiskService(com.vmware.photon.controller.model.resources.DiskService)

Example 2 with DiskStateExpanded

use of com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded in project photon-model by vmware.

the class VSphereAdapterInstanceService method updateDiskLinksAfterProvisionSuccess.

/**
 * Update the details of the disk into compute state after the provisioning is successful
 */
private void updateDiskLinksAfterProvisionSuccess(ComputeState state, List<VirtualDevice> disks, ProvisionContext ctx) {
    ArrayList<String> diskLinks = new ArrayList<>(disks.size());
    // Fill in the disk links from the input to the ComputeState, as it may contain non hdd
    // disk as well. For ex, Floppy or CD-Rom
    ctx.disks.stream().forEach(ds -> diskLinks.add(ds.documentSelfLink));
    // Handle all the HDD disk
    for (VirtualDevice disk : disks) {
        DiskStateExpanded matchedDs = findMatchingDiskState(disk, ctx.disks);
        if (disk instanceof VirtualDisk) {
            handleVirtualDiskUpdate(ctx.child.endpointLink, matchedDs, (VirtualDisk) disk, diskLinks, ctx.parent.description.regionId, this, CustomProperties.of(state).getString(CustomProperties.MOREF), CustomProperties.of(state).getString(CustomProperties.DATACENTER_SELF_LINK), null, null).sendWith(this);
        } else if (disk instanceof VirtualCdrom) {
            handleVirtualDeviceUpdate(ctx.child.endpointLink, matchedDs, DiskType.CDROM, disk, diskLinks, ctx.parent.description.regionId, this, true, CustomProperties.of(state).getString(CustomProperties.DATACENTER_SELF_LINK)).sendWith(this);
        } else if (disk instanceof VirtualFloppy) {
            handleVirtualDeviceUpdate(ctx.child.endpointLink, matchedDs, DiskType.FLOPPY, disk, diskLinks, ctx.parent.description.regionId, this, true, CustomProperties.of(state).getString(CustomProperties.DATACENTER_SELF_LINK)).sendWith(this);
        }
    }
    state.diskLinks = diskLinks;
}
Also used : VirtualCdrom(com.vmware.vim25.VirtualCdrom) ArrayList(java.util.ArrayList) VirtualDevice(com.vmware.vim25.VirtualDevice) DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) VirtualFloppy(com.vmware.vim25.VirtualFloppy) VirtualDisk(com.vmware.vim25.VirtualDisk)

Example 3 with DiskStateExpanded

use of com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded in project photon-model by vmware.

the class InstanceClient method getCustomizationConfigSpecs.

/**
 * Get customization config spec for all the image disks if any
 */
private List<VirtualDeviceConfigSpec> getCustomizationConfigSpecs(ArrayOfVirtualDevice devices, List<DiskStateExpanded> diskStates) throws FinderException, InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    List<VirtualDeviceConfigSpec> specs = new ArrayList<>();
    List<VirtualDisk> virtualDisks = devices.getVirtualDevice().stream().filter(d -> d instanceof VirtualDisk).map(d -> (VirtualDisk) d).collect(Collectors.toList());
    for (VirtualDisk vd : virtualDisks) {
        VirtualDeviceConfigSpec diskSpec = getBootDiskCustomizeConfigSpec(findMatchingImageDiskState(vd, diskStates), vd);
        if (diskSpec != null) {
            specs.add(diskSpec);
        }
    }
    return specs;
}
Also used : ClientUtils.findMatchingVirtualDevice(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findMatchingVirtualDevice) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) VirtualMachineRelocateSpecDiskLocator(com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator) VirtualDiskSpec(com.vmware.vim25.VirtualDiskSpec) ClientUtils.fillInControllerUnitNumber(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.fillInControllerUnitNumber) ArrayOfVirtualDevice(com.vmware.vim25.ArrayOfVirtualDevice) ClientUtils.findFreeScsiUnit(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findFreeScsiUnit) VmConfigSpec(com.vmware.vim25.VmConfigSpec) ClientUtils.getFirstIdeController(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getFirstIdeController) VirtualDeviceConnectInfo(com.vmware.vim25.VirtualDeviceConnectInfo) Utils(com.vmware.xenon.common.Utils) Document(org.w3c.dom.Document) Map(java.util.Map) VirtualDevice(com.vmware.vim25.VirtualDevice) EnumSet(java.util.EnumSet) FinderException(com.vmware.photon.controller.model.adapters.vsphere.util.finders.FinderException) VapiConnection(com.vmware.photon.controller.model.adapters.vsphere.vapi.VapiConnection) ClientUtils.createHdd(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.createHdd) ClientUtils.getFirstScsiController(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getFirstScsiController) ArrayOfManagedObjectReference(com.vmware.vim25.ArrayOfManagedObjectReference) ClientUtils.nextUnitNumber(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.nextUnitNumber) ClientUtils.getFirstSioController(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getFirstSioController) ClientUtils.getDatastorePathForDisk(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDatastorePathForDisk) VirtualMachineFileInfo(com.vmware.vim25.VirtualMachineFileInfo) VirtualMachineSnapshotInfo(com.vmware.vim25.VirtualMachineSnapshotInfo) DuplicateNameFaultMsg(com.vmware.vim25.DuplicateNameFaultMsg) ArrayUpdateOperation(com.vmware.vim25.ArrayUpdateOperation) UriUtils(com.vmware.xenon.common.UriUtils) ClientUtils.detachDisk(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.detachDisk) VirtualFloppy(com.vmware.vim25.VirtualFloppy) ClientUtils.getStorageIOAllocationInfo(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getStorageIOAllocationInfo) Finder(com.vmware.photon.controller.model.adapters.vsphere.util.finders.Finder) OvfDeployer(com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfDeployer) VirtualLsiLogicController(com.vmware.vim25.VirtualLsiLogicController) OptionValue(com.vmware.vim25.OptionValue) RuntimeFaultFaultMsg(com.vmware.vim25.RuntimeFaultFaultMsg) ArrayList(java.util.ArrayList) ComputeInstanceRequest(com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest) VirtualCdrom(com.vmware.vim25.VirtualCdrom) STORAGE_REFERENCE(com.vmware.photon.controller.model.constants.PhotonModelConstants.STORAGE_REFERENCE) OvfRetriever(com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever) ClientUtils.getDiskProvisioningType(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDiskProvisioningType) DISK_DATASTORE_NAME(com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.DISK_DATASTORE_NAME) VirtualMachineRelocateDiskMoveOptions(com.vmware.vim25.VirtualMachineRelocateDiskMoveOptions) InvalidCollectorVersionFaultMsg(com.vmware.vim25.InvalidCollectorVersionFaultMsg) VirtualMachineGuestOsIdentifier(com.vmware.vim25.VirtualMachineGuestOsIdentifier) DiskStatus(com.vmware.photon.controller.model.resources.DiskService.DiskStatus) VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) VirtualDeviceBackingInfo(com.vmware.vim25.VirtualDeviceBackingInfo) ClientUtils.getDiskMode(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDiskMode) PROVIDER_DISK_UNIQUE_ID(com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.PROVIDER_DISK_UNIQUE_ID) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) ClientUtils.findFreeUnit(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findFreeUnit) ClientUtils.insertCdrom(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.insertCdrom) MethodFault(com.vmware.vim25.MethodFault) Lock(java.util.concurrent.locks.Lock) VirtualDisk(com.vmware.vim25.VirtualDisk) Paths(java.nio.file.Paths) InvalidNameFaultMsg(com.vmware.vim25.InvalidNameFaultMsg) ClientUtils.insertFloppy(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.insertFloppy) VAppPropertySpec(com.vmware.vim25.VAppPropertySpec) VirtualDiskType(com.vmware.vim25.VirtualDiskType) VirtualEthernetCardMacType(com.vmware.vim25.VirtualEthernetCardMacType) OvfParser(com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfParser) BaseHelper(com.vmware.photon.controller.model.adapters.vsphere.util.connection.BaseHelper) LoggerFactory(org.slf4j.LoggerFactory) ClientUtils.toKb(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.toKb) DiskType(com.vmware.photon.controller.model.resources.DiskService.DiskType) OvfNetworkMapping(com.vmware.vim25.OvfNetworkMapping) VAppPropertyInfo(com.vmware.vim25.VAppPropertyInfo) ClientUtils.getPbmProfileSpec(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getPbmProfileSpec) Connection(com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection) URI(java.net.URI) TaskInfo(com.vmware.vim25.TaskInfo) VirtualDiskFlatVer2BackingInfo(com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) VM_PATH_FORMAT(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.VM_PATH_FORMAT) DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) DuplicateName(com.vmware.vim25.DuplicateName) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayOfVAppPropertyInfo(com.vmware.vim25.ArrayOfVAppPropertyInfo) Collectors(java.util.stream.Collectors) ServiceHost(com.vmware.xenon.common.ServiceHost) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) InvalidPropertyFaultMsg(com.vmware.vim25.InvalidPropertyFaultMsg) VirtualMachineRelocateSpec(com.vmware.vim25.VirtualMachineRelocateSpec) VirtualPCIController(com.vmware.vim25.VirtualPCIController) ClientUtils.createCdrom(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.createCdrom) Entry(java.util.Map.Entry) DiskService(com.vmware.photon.controller.model.resources.DiskService) VimPath(com.vmware.photon.controller.model.adapters.vsphere.util.VimPath) PhotonModelUriUtils(com.vmware.photon.controller.model.util.PhotonModelUriUtils) FileAlreadyExists(com.vmware.vim25.FileAlreadyExists) ClientUtils.makePathToVmdkFile(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.makePathToVmdkFile) HashMap(java.util.HashMap) GetMoRef(com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef) VirtualMachineCloneSpec(com.vmware.vim25.VirtualMachineCloneSpec) VapiClient(com.vmware.photon.controller.model.adapters.vsphere.vapi.VapiClient) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CollectionUtils(org.apache.commons.collections.CollectionUtils) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) ClientUtils.getListOfVirtualDisk(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getListOfVirtualDisk) NetworkDeviceBackingFactory(com.vmware.photon.controller.model.adapters.vsphere.network.NetworkDeviceBackingFactory) ClientUtils.getDatastoreFromStoragePolicy(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDatastoreFromStoragePolicy) Logger(org.slf4j.Logger) Element(com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element) ReentrantLock(java.util.concurrent.locks.ReentrantLock) VirtualE1000(com.vmware.vim25.VirtualE1000) Operation(com.vmware.xenon.common.Operation) DISK_CONTROLLER_NUMBER(com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.DISK_CONTROLLER_NUMBER) ClientUtils.createFloppy(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.createFloppy) VirtualSCSIController(com.vmware.vim25.VirtualSCSIController) VimNames(com.vmware.photon.controller.model.adapters.vsphere.util.VimNames) NetworkInterfaceStateWithDetails(com.vmware.photon.controller.model.adapters.vsphere.ProvisionContext.NetworkInterfaceStateWithDetails) DISK_PARENT_DIRECTORY(com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.DISK_PARENT_DIRECTORY) TimeUnit(java.util.concurrent.TimeUnit) VirtualDeviceConfigSpecOperation(com.vmware.vim25.VirtualDeviceConfigSpecOperation) FileEntry(com.vmware.photon.controller.model.resources.DiskService.DiskState.BootConfig.FileEntry) VirtualSCSISharing(com.vmware.vim25.VirtualSCSISharing) LibraryClient(com.vmware.photon.controller.model.adapters.vsphere.vapi.LibraryClient) VirtualMachineDefinedProfileSpec(com.vmware.vim25.VirtualMachineDefinedProfileSpec) ImageState(com.vmware.photon.controller.model.resources.ImageService.ImageState) VirtualEthernetCard(com.vmware.vim25.VirtualEthernetCard) Collections(java.util.Collections) TaskInfoState(com.vmware.vim25.TaskInfoState) OperationJoin(com.vmware.xenon.common.OperationJoin) RESOURCE_GROUP_NAME(com.vmware.photon.controller.model.ComputeProperties.RESOURCE_GROUP_NAME) VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) ArrayList(java.util.ArrayList) VirtualDisk(com.vmware.vim25.VirtualDisk) ClientUtils.getListOfVirtualDisk(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getListOfVirtualDisk)

Example 4 with DiskStateExpanded

use of com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded in project photon-model by vmware.

the class ProvisionContext method populateContextThen.

/**
 * Populates the given initial context and invoke the onSuccess handler when built. At every step,
 * if failure occurs the ProvisionContext's errorHandler is invoked to cleanup.
 *
 * @param ctx
 * @param onSuccess
 */
public static void populateContextThen(Service service, ProvisionContext ctx, Consumer<ProvisionContext> onSuccess) {
    // TODO fetch all required state in parallel using OperationJoin.
    if (ctx.child == null) {
        URI computeUri = UriUtils.extendUriWithQuery(ctx.computeReference, UriUtils.URI_PARAM_ODATA_EXPAND, Boolean.TRUE.toString());
        computeUri = createInventoryUri(service.getHost(), computeUri);
        AdapterUtils.getServiceState(service, computeUri, op -> {
            ctx.child = op.getBody(ComputeStateWithDescription.class);
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    String templateLink = VimUtils.firstNonNull(CustomProperties.of(ctx.child).getString(CustomProperties.TEMPLATE_LINK), CustomProperties.of(ctx.child.description).getString(CustomProperties.TEMPLATE_LINK));
    // in all other cases ignore the presence of the template
    if (templateLink != null && ctx.templateMoRef == null && ctx.instanceRequestType == InstanceRequestType.CREATE) {
        URI computeUri = createInventoryUri(service.getHost(), templateLink);
        AdapterUtils.getServiceState(service, computeUri, op -> {
            ImageState body = op.getBody(ImageState.class);
            ctx.templateMoRef = CustomProperties.of(body).getMoRef(CustomProperties.MOREF);
            if (ctx.templateMoRef == null) {
                String msg = String.format("The linked template %s does not contain a MoRef in its custom properties", templateLink);
                ctx.fail(new IllegalStateException(msg));
            } else {
                populateContextThen(service, ctx, onSuccess);
            }
        }, ctx.errorHandler);
        return;
    }
    // For creation based on linked clone of snapshot
    if (ctx.snapshotMoRef == null) {
        String snapshotLink = CustomProperties.of(ctx.child).getString(CustomProperties.SNAPSHOT_LINK);
        if (snapshotLink != null && ctx.instanceRequestType == InstanceRequestType.CREATE) {
            URI snapshotUri = createInventoryUri(service.getHost(), snapshotLink);
            AdapterUtils.getServiceState(service, snapshotUri, op -> {
                SnapshotService.SnapshotState snapshotState = op.getBody(SnapshotService.SnapshotState.class);
                ctx.snapshotMoRef = CustomProperties.of(snapshotState).getMoRef(CustomProperties.MOREF);
                if (ctx.snapshotMoRef == null) {
                    String msg = String.format("The linked clone snapshot %s does not contain a MoRef in its custom properties", snapshotLink);
                    ctx.fail(new IllegalStateException(msg));
                } else {
                    // Retrieve the reference endpoint moref from which the linkedclone has to be created.
                    String refComputeLink = snapshotState.computeLink;
                    if (refComputeLink != null) {
                        URI refComputeUri = createInventoryUri(service.getHost(), refComputeLink);
                        AdapterUtils.getServiceState(service, refComputeUri, opCompute -> {
                            ComputeStateWithDescription refComputeState = opCompute.getBody(ComputeStateWithDescription.class);
                            ctx.referenceComputeMoRef = CustomProperties.of(refComputeState).getMoRef(CustomProperties.MOREF);
                            if (ctx.referenceComputeMoRef == null) {
                                String msg = String.format("The linked clone endpoint ref %s does not contain a MoRef in its custom properties", refComputeLink);
                                ctx.fail(new IllegalStateException(msg));
                            }
                            populateContextThen(service, ctx, onSuccess);
                        }, ctx.errorHandler);
                    }
                }
            }, ctx.errorHandler);
            return;
        }
    }
    if (ctx.parent == null && ctx.child.parentLink != null) {
        URI computeUri = UriUtils.extendUriWithQuery(UriUtils.buildUri(service.getHost(), ctx.child.parentLink), UriUtils.URI_PARAM_ODATA_EXPAND, Boolean.TRUE.toString());
        computeUri = createInventoryUri(service.getHost(), computeUri);
        AdapterUtils.getServiceState(service, computeUri, op -> {
            ctx.parent = op.getBody(ComputeStateWithDescription.class);
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    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.parent.description.authCredentialsLink == null) {
                ctx.fail(new IllegalStateException("authCredentialsLink is not defined in resource " + ctx.parent.description.documentSelfLink));
                return;
            }
            URI credUri = createInventoryUri(service.getHost(), ctx.parent.description.authCredentialsLink);
            AdapterUtils.getServiceState(service, credUri, op -> {
                ctx.vSphereCredentials = op.getBody(AuthCredentialsServiceState.class);
                populateContextThen(service, ctx, onSuccess);
            }, ctx.errorHandler);
        }
        return;
    }
    if (ctx.task == null) {
        // Verify if this makes sense? These tasks should always be local to deployment?
        AdapterUtils.getServiceState(service, ctx.provisioningTaskReference, op -> {
            ctx.task = op.getBody(ServiceDocument.class);
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    if (ctx.nics == null && ctx.instanceRequestType == InstanceRequestType.CREATE) {
        if (ctx.child.networkInterfaceLinks == null || ctx.child.networkInterfaceLinks.isEmpty()) {
            ctx.nics = Collections.emptyList();
            populateContextThen(service, ctx, onSuccess);
            return;
        }
        ctx.nics = new ArrayList<>();
        Query query = Query.Builder.create().addInClause(ServiceDocument.FIELD_NAME_SELF_LINK, ctx.child.networkInterfaceLinks).build();
        QueryTask qt = QueryTask.Builder.createDirectTask().setQuery(query).addOption(QueryOption.EXPAND_CONTENT).addOption(QueryOption.EXPAND_LINKS).addOption(QueryOption.SELECT_LINKS).addOption(QueryOption.INDEXED_METADATA).addLinkTerm(NetworkInterfaceState.FIELD_NAME_NETWORK_LINK).addLinkTerm(NetworkInterfaceState.FIELD_NAME_SUBNET_LINK).addLinkTerm(NetworkInterfaceState.FIELD_NAME_DESCRIPTION_LINK).build();
        QueryUtils.startInventoryQueryTask(service, qt).whenComplete((o, e) -> {
            if (e != null) {
                ctx.errorHandler.accept(e);
                return;
            }
            QueryResultsProcessor processor = QueryResultsProcessor.create(o);
            for (NetworkInterfaceStateWithDetails nic : processor.documents(NetworkInterfaceStateWithDetails.class)) {
                if (nic.networkInterfaceDescriptionLink != null) {
                    NetworkInterfaceDescription desc = processor.selectedDocument(nic.networkInterfaceDescriptionLink, NetworkInterfaceDescription.class);
                    nic.description = desc;
                }
                if (nic.subnetLink != null) {
                    SubnetState subnet = processor.selectedDocument(nic.subnetLink, SubnetState.class);
                    nic.subnet = subnet;
                }
                if (nic.networkLink != null) {
                    NetworkState network = processor.selectedDocument(nic.networkLink, NetworkState.class);
                    nic.network = network;
                }
                ctx.nics.add(nic);
            }
            populateContextThen(service, ctx, onSuccess);
        });
        return;
    }
    if (ctx.computeMoRef == null) {
        String placementLink = CustomProperties.of(ctx.child).getString(ComputeProperties.PLACEMENT_LINK);
        if (placementLink == null) {
            Exception error = new IllegalStateException("A Compute resource must have a " + ComputeProperties.PLACEMENT_LINK + " custom property");
            ctx.fail(error);
            return;
        }
        URI expandedPlacementUri = UriUtils.extendUriWithQuery(createInventoryUri(service.getHost(), placementLink), UriUtils.URI_PARAM_ODATA_EXPAND, Boolean.TRUE.toString());
        expandedPlacementUri = createInventoryUri(service.getHost(), expandedPlacementUri);
        Operation.createGet(expandedPlacementUri).setCompletion((o, e) -> {
            if (e != null) {
                ctx.fail(e);
                return;
            }
            ComputeStateWithDescription host = o.getBody(ComputeStateWithDescription.class);
            // extract the target resource pool for the placement
            CustomProperties hostCustomProperties = CustomProperties.of(host);
            ctx.computeMoRef = hostCustomProperties.getMoRef(CustomProperties.MOREF);
            if (ctx.computeMoRef == null) {
                Exception error = new IllegalStateException(String.format("Compute @ %s does not contain a %s custom property", placementLink, CustomProperties.MOREF));
                ctx.fail(error);
                return;
            }
            if (host.description.regionId == null) {
                Exception error = new IllegalStateException(String.format("Compute @ %s does not specify a region", placementLink));
                ctx.fail(error);
                return;
            }
            try {
                ctx.datacenterMoRef = VimUtils.convertStringToMoRef(host.description.regionId);
            } catch (IllegalArgumentException ex) {
                ctx.fail(ex);
                return;
            }
            populateContextThen(service, ctx, onSuccess);
        }).sendWith(service);
        return;
    }
    if (ctx.disks == null) {
        // no disks attached
        if (ctx.child.diskLinks == null || ctx.child.diskLinks.isEmpty()) {
            ctx.disks = Collections.emptyList();
            populateContextThen(service, ctx, onSuccess);
            return;
        }
        ctx.disks = new ArrayList<>(ctx.child.diskLinks.size());
        // collect disks in parallel
        Stream<Operation> opsGetDisk = ctx.child.diskLinks.stream().map(link -> {
            URI diskStateUri = UriUtils.buildUri(service.getHost(), link);
            return Operation.createGet(createInventoryUri(service.getHost(), DiskStateExpanded.buildUri(diskStateUri)));
        });
        OperationJoin join = OperationJoin.create(opsGetDisk).setCompletion((os, errors) -> {
            if (errors != null && !errors.isEmpty()) {
                // fail on first error
                ctx.errorHandler.accept(new IllegalStateException("Cannot get disk state", errors.values().iterator().next()));
                return;
            }
            os.values().forEach(op -> ctx.disks.add(op.getBody(DiskStateExpanded.class)));
            populateContextThen(service, ctx, onSuccess);
        });
        join.sendWith(service);
        return;
    }
    String libraryItemLink = VimUtils.firstNonNull(CustomProperties.of(ctx.child).getString(CustomProperties.LIBRARY_ITEM_LINK), CustomProperties.of(ctx.child.description).getString(CustomProperties.LIBRARY_ITEM_LINK));
    if (libraryItemLink != null && ctx.image == null && ctx.instanceRequestType == InstanceRequestType.CREATE) {
        URI libraryUri = createInventoryUri(service.getHost(), libraryItemLink);
        AdapterUtils.getServiceState(service, libraryUri, op -> {
            ImageState body = op.getBody(ImageState.class);
            ctx.image = body;
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    if (ctx.instanceRequestType == InstanceRequestType.CREATE) {
        if (ctx.image == null) {
            DiskStateExpanded bootDisk = ctx.disks.stream().filter(d -> d.imageLink != null).findFirst().orElse(null);
            if (bootDisk != null) {
                URI bootImageRef = createInventoryUri(service.getHost(), bootDisk.imageLink);
                AdapterUtils.getServiceState(service, bootImageRef, op -> {
                    ImageState body = op.getBody(ImageState.class);
                    ctx.image = body;
                    populateContextThen(service, ctx, onSuccess);
                }, ctx.errorHandler);
                return;
            }
        }
    }
    // Order networks by deviceIndex so that nics are created in the same order
    if (ctx.nics != null) {
        // configure network
        ctx.nics.sort((lnis, rnis) -> {
            return Integer.compare(lnis.deviceIndex, rnis.deviceIndex);
        });
    }
    // context populated, invoke handler
    onSuccess.accept(ctx);
}
Also used : Service(com.vmware.xenon.common.Service) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) ComputeProperties(com.vmware.photon.controller.model.ComputeProperties) SessionUtil(com.vmware.photon.controller.model.resources.SessionUtil) QueryTask(com.vmware.xenon.services.common.QueryTask) ServiceDocument(com.vmware.xenon.common.ServiceDocument) JoinedCompletionHandler(com.vmware.xenon.common.OperationJoin.JoinedCompletionHandler) ArrayList(java.util.ArrayList) ComputeInstanceRequest(com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest) ResourceRequest(com.vmware.photon.controller.model.adapterapi.ResourceRequest) Utils(com.vmware.xenon.common.Utils) Query(com.vmware.xenon.services.common.QueryTask.Query) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) URI(java.net.URI) QueryResultsProcessor(com.vmware.xenon.common.QueryResultsProcessor) AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) NetworkInterfaceState(com.vmware.photon.controller.model.resources.NetworkInterfaceService.NetworkInterfaceState) Operation(com.vmware.xenon.common.Operation) TaskManager(com.vmware.photon.controller.model.adapters.util.TaskManager) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) InstanceRequestType(com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest.InstanceRequestType) SnapshotService(com.vmware.photon.controller.model.resources.SnapshotService) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) Consumer(java.util.function.Consumer) List(java.util.List) Stream(java.util.stream.Stream) ComputeStateWithDescription(com.vmware.photon.controller.model.resources.ComputeService.ComputeStateWithDescription) UriUtils(com.vmware.xenon.common.UriUtils) ImageState(com.vmware.photon.controller.model.resources.ImageService.ImageState) QueryOption(com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption) IAAS_API_ENABLED(com.vmware.photon.controller.model.UriPaths.IAAS_API_ENABLED) NetworkInterfaceDescription(com.vmware.photon.controller.model.resources.NetworkInterfaceDescriptionService.NetworkInterfaceDescription) NetworkState(com.vmware.photon.controller.model.resources.NetworkService.NetworkState) Collections(java.util.Collections) OperationJoin(com.vmware.xenon.common.OperationJoin) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) ComputeStateWithDescription(com.vmware.photon.controller.model.resources.ComputeService.ComputeStateWithDescription) Query(com.vmware.xenon.services.common.QueryTask.Query) OperationJoin(com.vmware.xenon.common.OperationJoin) DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) Operation(com.vmware.xenon.common.Operation) URI(java.net.URI) ServiceDocument(com.vmware.xenon.common.ServiceDocument) NetworkState(com.vmware.photon.controller.model.resources.NetworkService.NetworkState) NetworkInterfaceDescription(com.vmware.photon.controller.model.resources.NetworkInterfaceDescriptionService.NetworkInterfaceDescription) SnapshotService(com.vmware.photon.controller.model.resources.SnapshotService) QueryResultsProcessor(com.vmware.xenon.common.QueryResultsProcessor) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) QueryTask(com.vmware.xenon.services.common.QueryTask) ImageState(com.vmware.photon.controller.model.resources.ImageService.ImageState)

Example 5 with DiskStateExpanded

use of com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded in project photon-model by vmware.

the class InstanceClient method attachExternalDisks.

/**
 * Attach any externally created disks to the VM if any.
 */
public void attachExternalDisks() throws Exception {
    if (this.externalDisks == null || this.externalDisks.isEmpty()) {
        return;
    }
    if (this.vm == null) {
        throw new IllegalStateException("Cannot attach diskStates if VM is not created");
    }
    for (DiskStateExpanded diskState : this.externalDisks) {
        ArrayOfVirtualDevice devices = this.get.entityProp(this.vm, VimPath.vm_config_hardware_device);
        String diskDatastoreName = CustomProperties.of(diskState).getString(DISK_DATASTORE_NAME);
        ClientUtils.attachDiskToVM(devices, this.vm, diskState, this.finder.datastore(diskDatastoreName).object, this.connection, this.getVimPort());
    }
}
Also used : DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) ArrayOfVirtualDevice(com.vmware.vim25.ArrayOfVirtualDevice)

Aggregations

DiskStateExpanded (com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded)9 ComputeInstanceRequest (com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest)6 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)5 RESOURCE_GROUP_NAME (com.vmware.photon.controller.model.ComputeProperties.RESOURCE_GROUP_NAME)5 VM_PATH_FORMAT (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.VM_PATH_FORMAT)5 ClientUtils.createCdrom (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.createCdrom)5 ClientUtils.createFloppy (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.createFloppy)5 ClientUtils.createHdd (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.createHdd)5 ClientUtils.detachDisk (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.detachDisk)5 ClientUtils.fillInControllerUnitNumber (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.fillInControllerUnitNumber)5 ClientUtils.findFreeScsiUnit (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findFreeScsiUnit)5 ClientUtils.findFreeUnit (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findFreeUnit)5 ClientUtils.findMatchingVirtualDevice (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findMatchingVirtualDevice)5 ClientUtils.getDatastoreFromStoragePolicy (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDatastoreFromStoragePolicy)5 ClientUtils.getDatastorePathForDisk (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDatastorePathForDisk)5 ClientUtils.getDiskMode (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDiskMode)5 ClientUtils.getDiskProvisioningType (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getDiskProvisioningType)5 ClientUtils.getFirstIdeController (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getFirstIdeController)5 ArrayOfVirtualDevice (com.vmware.vim25.ArrayOfVirtualDevice)5 ClientUtils.getFirstScsiController (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getFirstScsiController)4