Search in sources :

Example 36 with Folder

use of com.vmware.vim25.mo.Folder in project photon-model by vmware.

the class InstanceClient method deleteInstance.

public void deleteInstance(ServiceHost serviceHost) throws Exception {
    ManagedObjectReference vm = CustomProperties.of(this.ctx.child).getMoRef(CustomProperties.MOREF);
    if (vm == null) {
        logger.info("No moref associated with the given instance, skipping delete.");
        return;
    }
    ArrayOfVirtualDevice devices = this.get.entityProp(vm, VimPath.vm_config_hardware_device);
    // Handle disks of the VM during VM deletion based on its persistent flag.
    handleVirtualDiskCleanup(serviceHost, vm, devices, this.ctx.disks);
    TaskInfo info;
    // power off
    ManagedObjectReference task = getVimPort().powerOffVMTask(vm);
    info = waitTaskEnd(task);
    ignoreError("Ignore error powering off VM", info);
    // delete vm
    task = getVimPort().destroyTask(vm);
    info = waitTaskEnd(task);
    ignoreError("Ignore error deleting VM", info);
    // Handle CD ROM folder clean up.
    handleVirtualCDRomCleanup(this.ctx.disks);
}
Also used : TaskInfo(com.vmware.vim25.TaskInfo) ArrayOfVirtualDevice(com.vmware.vim25.ArrayOfVirtualDevice) ArrayOfManagedObjectReference(com.vmware.vim25.ArrayOfManagedObjectReference) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 37 with Folder

use of com.vmware.vim25.mo.Folder in project photon-model by vmware.

the class InstanceClient method createFullCloneAndAttach.

private VirtualDeviceConfigSpec createFullCloneAndAttach(String sourcePath, DiskStateExpanded ds, String dir, VirtualDevice scsiController, int unitNumber, List<VirtualMachineDefinedProfileSpec> pbmSpec) throws Exception {
    ManagedObjectReference diskManager = this.connection.getServiceContent().getVirtualDiskManager();
    String dsDirForDisk = getDatastorePathForDisk(ds, dir);
    // put full clone in the vm folder
    String destName = makePathToVmdkFile(ds.name, dsDirForDisk);
    // all ops are within a datacenter
    ManagedObjectReference sourceDc = this.ctx.datacenterMoRef;
    ManagedObjectReference destDc = sourceDc;
    Boolean force = true;
    // spec is not supported, should use null for now
    VirtualDiskSpec spec = null;
    ManagedObjectReference task = getVimPort().copyVirtualDiskTask(diskManager, sourcePath, sourceDc, destName, destDc, spec, force);
    // wait for the disk to be copied
    TaskInfo taskInfo = waitTaskEnd(task);
    if (taskInfo.getState() == TaskInfoState.ERROR) {
        return VimUtils.rethrow(taskInfo.getError());
    }
    VirtualDiskFlatVer2BackingInfo backing = new VirtualDiskFlatVer2BackingInfo();
    backing.setDiskMode(getDiskMode(ds));
    VirtualDiskType provisionType = getDiskProvisioningType(ds);
    if (provisionType != null) {
        backing.setThinProvisioned(provisionType == VirtualDiskType.THIN);
        backing.setEagerlyScrub(provisionType == VirtualDiskType.EAGER_ZEROED_THICK);
    }
    backing.setFileName(destName);
    backing.setDatastore(getDataStoreForDisk(ds, pbmSpec));
    VirtualDisk disk = new VirtualDisk();
    disk.setBacking(backing);
    disk.setStorageIOAllocation(getStorageIOAllocationInfo(ds));
    disk.setControllerKey(scsiController.getKey());
    disk.setUnitNumber(unitNumber);
    fillInControllerUnitNumber(ds, unitNumber);
    disk.setKey(-1);
    VirtualDeviceConfigSpec change = new VirtualDeviceConfigSpec();
    change.setDevice(disk);
    // Add storage policy spec
    if (pbmSpec != null) {
        pbmSpec.stream().forEach(sp -> {
            change.getProfile().add(sp);
        });
    }
    change.setOperation(VirtualDeviceConfigSpecOperation.ADD);
    return change;
}
Also used : TaskInfo(com.vmware.vim25.TaskInfo) VirtualDiskFlatVer2BackingInfo(com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) VirtualDiskType(com.vmware.vim25.VirtualDiskType) VirtualDiskSpec(com.vmware.vim25.VirtualDiskSpec) VirtualDisk(com.vmware.vim25.VirtualDisk) ClientUtils.getListOfVirtualDisk(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.getListOfVirtualDisk) ArrayOfManagedObjectReference(com.vmware.vim25.ArrayOfManagedObjectReference) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 38 with Folder

use of com.vmware.vim25.mo.Folder 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();
}
Also used : TaskInfo(com.vmware.vim25.TaskInfo) MethodFault(com.vmware.vim25.MethodFault) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) FileAlreadyExists(com.vmware.vim25.FileAlreadyExists) VirtualMachineDefinedProfileSpec(com.vmware.vim25.VirtualMachineDefinedProfileSpec) ArrayOfManagedObjectReference(com.vmware.vim25.ArrayOfManagedObjectReference) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 39 with Folder

use of com.vmware.vim25.mo.Folder in project photon-model by vmware.

the class VsphereFolderEnumerationHelper method handleFolderChanges.

public static void handleFolderChanges(VSphereIncrementalEnumerationService service, List<FolderOverlay> folderOverlays, EnumerationProgress enumerationProgress, EnumerationClient client) {
    enumerationProgress.expectFolderCount(folderOverlays.size());
    for (FolderOverlay folderOverlay : folderOverlays) {
        try {
            if (ObjectUpdateKind.ENTER == folderOverlay.getObjectUpdateKind()) {
                createFolder(service, enumerationProgress, folderOverlay, Collections.emptyList(), client);
            } else {
                QueryTask task = queryForFolder(enumerationProgress, folderOverlay);
                withTaskResults(service, task, result -> {
                    if (!result.documentLinks.isEmpty()) {
                        ResourceGroupState oldDocument = convertOnlyResultToDocument(result, ResourceGroupState.class);
                        if (ObjectUpdateKind.MODIFY.equals(folderOverlay.getObjectUpdateKind())) {
                            try {
                                updateFolder(service, enumerationProgress, folderOverlay, oldDocument, Collections.emptyList(), client, false);
                            } catch (Exception e) {
                                service.logSevere("Error occurred while processing folder!", e);
                                enumerationProgress.getFolderTracker().track(folderOverlay.getId(), ResourceTracker.ERROR);
                            }
                        } else {
                            Operation.createDelete(PhotonModelUriUtils.createInventoryUri(service.getHost(), oldDocument.documentSelfLink)).setCompletion((o, e) -> {
                                enumerationProgress.getFolderTracker().track();
                            }).sendWith(service);
                        }
                    } else {
                        enumerationProgress.getFolderTracker().track();
                    }
                });
            }
        } catch (Exception e) {
            service.logSevere("Error occurred while processing folder!", e);
            enumerationProgress.getFolderTracker().track(folderOverlay.getId(), ResourceTracker.ERROR);
        }
    }
}
Also used : AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) ComputeProperties(com.vmware.photon.controller.model.ComputeProperties) ResourceState(com.vmware.photon.controller.model.resources.ResourceState) PhotonModelUriUtils(com.vmware.photon.controller.model.util.PhotonModelUriUtils) Operation(com.vmware.xenon.common.Operation) QueryTask(com.vmware.xenon.services.common.QueryTask) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) ObjectUpdateKind(com.vmware.vim25.ObjectUpdateKind) RuntimeFaultFaultMsg(com.vmware.vim25.RuntimeFaultFaultMsg) ResourceGroupState(com.vmware.photon.controller.model.resources.ResourceGroupService.ResourceGroupState) VimNames(com.vmware.photon.controller.model.adapters.vsphere.util.VimNames) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) VsphereEnumerationHelper.getSelfLinkFromOperation(com.vmware.photon.controller.model.adapters.vsphere.VsphereEnumerationHelper.getSelfLinkFromOperation) ResourceGroupService(com.vmware.photon.controller.model.resources.ResourceGroupService) List(java.util.List) InvalidPropertyFaultMsg(com.vmware.vim25.InvalidPropertyFaultMsg) VsphereEnumerationHelper.convertOnlyResultToDocument(com.vmware.photon.controller.model.adapters.vsphere.VsphereEnumerationHelper.convertOnlyResultToDocument) CompletionHandler(com.vmware.xenon.common.Operation.CompletionHandler) VsphereEnumerationHelper.withTaskResults(com.vmware.photon.controller.model.adapters.vsphere.VsphereEnumerationHelper.withTaskResults) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult) Builder(com.vmware.xenon.services.common.QueryTask.Query.Builder) Collections(java.util.Collections) QueryTask(com.vmware.xenon.services.common.QueryTask) ResourceGroupState(com.vmware.photon.controller.model.resources.ResourceGroupService.ResourceGroupState)

Example 40 with Folder

use of com.vmware.vim25.mo.Folder in project photon-model by vmware.

the class VsphereFolderEnumerationHelper method makeFolderFromResults.

private static ResourceGroupState makeFolderFromResults(EnumerationProgress ctx, FolderOverlay folder, List<FolderOverlay> rootFolders, EnumerationClient client) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
    ResourceGroupState state = new ResourceGroupState();
    state.name = state.id = folder.getName();
    state.endpointLink = ctx.getRequest().endpointLink;
    AdapterUtils.addToEndpointLinks(state, ctx.getRequest().endpointLink);
    state.tenantLinks = ctx.getTenantLinks();
    // Get the parent of the folder.
    // If the parent is one of the root folder, set the parent as root folders parent
    String parent = null;
    if (!rootFolders.isEmpty()) {
        for (FolderOverlay rootFolderOverlay : rootFolders) {
            if (rootFolderOverlay.getMoRefValue().equals(folder.getParent().getValue())) {
                parent = VimUtils.convertMoRefToString(rootFolderOverlay.getParent());
                break;
            }
        }
    } else {
        // retrieve parent folder Moref
        ManagedObjectReference parentFolder = folder.getParent();
        // retrieve parent of parent folder
        ManagedObjectReference parentOfParentFolder = client.getParentOfFolder(parentFolder);
        if (parentOfParentFolder.getType().equals(VimNames.TYPE_DATACENTER)) {
            parent = VimUtils.convertMoRefToString(parentOfParentFolder);
        } else {
            parent = VimUtils.convertMoRefToString(parentFolder);
        }
    }
    CustomProperties.of(state).put(CustomProperties.MOREF, folder.getId()).put(CustomProperties.TYPE, folder.getId().getType()).put(CustomProperties.DATACENTER_SELF_LINK, ctx.getDcLink()).put(ComputeProperties.ENDPOINT_LINK_PROP_NAME, ctx.getRequest().endpointLink).put(CustomProperties.DATACENTER, ctx.getRegionId()).put(CustomProperties.PARENT_ID, parent).put(CustomProperties.VC_VIEW, folder.getView()).put(CustomProperties.FOLDER_TYPE, folder.getFolderType());
    VsphereEnumerationHelper.populateResourceStateWithAdditionalProps(state, ctx.getVcUuid());
    return state;
}
Also used : ResourceGroupState(com.vmware.photon.controller.model.resources.ResourceGroupService.ResourceGroupState) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Aggregations

ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)30 TraversalSpec (com.vmware.vim25.TraversalSpec)15 ArrayList (java.util.ArrayList)15 PropertyFilterSpec (com.vmware.vim25.PropertyFilterSpec)13 SelectionSpec (com.vmware.vim25.SelectionSpec)12 ObjectSpec (com.vmware.vim25.ObjectSpec)11 PropertySpec (com.vmware.vim25.PropertySpec)11 TaskInfo (com.vmware.vim25.TaskInfo)10 RemoteException (java.rmi.RemoteException)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 ArrayOfManagedObjectReference (com.vmware.vim25.ArrayOfManagedObjectReference)8 InvalidPropertyFaultMsg (com.vmware.vim25.InvalidPropertyFaultMsg)8 RuntimeFaultFaultMsg (com.vmware.vim25.RuntimeFaultFaultMsg)8 VirtualDisk (com.vmware.vim25.VirtualDisk)7 Operation (com.vmware.xenon.common.Operation)7 VimNames (com.vmware.photon.controller.model.adapters.vsphere.util.VimNames)6 PhotonModelUriUtils (com.vmware.photon.controller.model.util.PhotonModelUriUtils)6 VirtualMachineConfigSpec (com.vmware.vim25.VirtualMachineConfigSpec)6 VirtualMachineDefinedProfileSpec (com.vmware.vim25.VirtualMachineDefinedProfileSpec)6 VirtualMachineRelocateSpec (com.vmware.vim25.VirtualMachineRelocateSpec)6