Search in sources :

Example 41 with Folder

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

the class DiskClient method createVirtualDisk.

/**
 * Create Virtual Disk
 */
public void createVirtualDisk() throws Exception {
    ManagedObjectReference diskManager = this.connection.getServiceContent().getVirtualDiskManager();
    List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(this.diskState);
    String dsName = this.diskContext.datastoreName != null && !this.diskContext.datastoreName.isEmpty() ? this.diskContext.datastoreName : ClientUtils.getDefaultDatastore(this.finder);
    String diskName = getUniqueDiskName();
    // Create the parent folder before creation of the disk file
    String parentDir = String.format(VM_PATH_FORMAT, dsName, diskName);
    createParentFolder(parentDir);
    String diskFullPath = constructDiskFullPath(dsName, diskName);
    ManagedObjectReference createTask = getVimPort().createVirtualDiskTask(diskManager, diskFullPath, this.diskContext.datacenterMoRef, createVirtualDiskSpec(this.diskState, pbmSpec));
    TaskInfo info = waitTaskEnd(createTask);
    if (info.getState() == TaskInfoState.ERROR) {
        VimUtils.rethrow(info.getError());
    }
    // Update the details of the disk
    CustomProperties.of(this.diskState).put(DISK_FULL_PATH, diskFullPath).put(DISK_PARENT_DIRECTORY, parentDir).put(DISK_DATASTORE_NAME, dsName);
    this.diskState.status = DiskService.DiskStatus.AVAILABLE;
    this.diskState.id = diskName;
    this.diskState.regionId = VimUtils.convertMoRefToString(this.diskContext.datacenterMoRef);
    AdapterUtils.addToEndpointLinks(this.diskState, this.diskState.endpointLink);
}
Also used : TaskInfo(com.vmware.vim25.TaskInfo) VirtualMachineDefinedProfileSpec(com.vmware.vim25.VirtualMachineDefinedProfileSpec) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 42 with Folder

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

the class DiskClient method deleteVirtualDisk.

/**
 * Delete Virtual disk.
 */
public void deleteVirtualDisk() throws Exception {
    ManagedObjectReference diskManager = this.connection.getServiceContent().getVirtualDiskManager();
    if (this.diskState.status != DiskService.DiskStatus.AVAILABLE) {
        throw new IllegalArgumentException("Only disk with status AVAILABLE can be deleted, as it is not attached to any VM.");
    }
    String diskFullPath = CustomProperties.of(this.diskState).getString(DISK_FULL_PATH, null);
    if (diskFullPath == null) {
        throw new IllegalArgumentException("Disk full path to issue delete request is empty.");
    }
    // Delete the vmdk file
    ManagedObjectReference deleteTask = getVimPort().deleteVirtualDiskTask(diskManager, diskFullPath, this.diskContext.datacenterMoRef);
    TaskInfo info = waitTaskEnd(deleteTask);
    if (info.getState() == TaskInfoState.ERROR) {
        VimUtils.rethrow(info.getError());
    }
    // Delete the folder that holds the vmdk file
    String dirName = CustomProperties.of(this.diskState).getString(DISK_PARENT_DIRECTORY, null);
    if (dirName != null) {
        ManagedObjectReference fileManager = this.connection.getServiceContent().getFileManager();
        ManagedObjectReference deleteFile = getVimPort().deleteDatastoreFileTask(fileManager, dirName, this.diskContext.datacenterMoRef);
        info = waitTaskEnd(deleteFile);
        if (info.getState() == TaskInfoState.ERROR) {
            VimUtils.rethrow(info.getError());
        }
    } else {
        Utils.logWarning("Disk parent directory is null, hence couldn't cleanup disk directory in the datastore");
    }
}
Also used : TaskInfo(com.vmware.vim25.TaskInfo) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 43 with Folder

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

the class InstanceDiskClient method uploadISOContents.

/**
 * Uploads ISO content into the chosen datastore
 */
public DeferredResult<DiskService.DiskStateExpanded> uploadISOContents(byte[] contentToUpload) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidDatastoreFaultMsg, FileFaultFaultMsg, FinderException {
    try {
        // 1) fetch data store for the disk
        String dsName = this.context.datastoreName;
        if (dsName == null || dsName.isEmpty()) {
            dsName = ClientUtils.getDefaultDatastore(this.finder);
        }
        String dataStoreName = dsName;
        List<Element> datastoreList = this.finder.datastoreList(dataStoreName);
        ManagedObjectReference dsFromSp;
        Optional<Element> datastoreOpt = datastoreList.stream().findFirst();
        if (datastoreOpt.isPresent()) {
            dsFromSp = datastoreOpt.get().object;
        } else {
            throw new IllegalArgumentException(String.format("No Datastore [%s] present on datacenter", dataStoreName));
        }
        // 2) Get available hosts for direct upload
        String hostName = null;
        ArrayOfDatastoreHostMount dsHosts = this.get.entityProp(dsFromSp, VimPath.res_host);
        if (dsHosts != null && dsHosts.getDatastoreHostMount() != null) {
            DatastoreHostMount dsHost = dsHosts.getDatastoreHostMount().stream().filter(hostMount -> hostMount.getMountInfo() != null && hostMount.getMountInfo().isAccessible() && hostMount.getMountInfo().isMounted()).findFirst().orElse(null);
            if (dsHost != null) {
                hostName = this.get.entityProp(dsHost.getKey(), VimPath.host_summary_config_name);
            }
        }
        if (hostName == null) {
            throw new IllegalStateException(String.format("No host found to upload ISO content " + "for Data Store Disk %s", dataStoreName));
        }
        // 3) Choose some unique filename
        String filename = ClientUtils.getUniqueName(ISO_FILE) + ISO_EXTENSION;
        // 4 ) Choose some unique folder name and create it.
        String folderName = ClientUtils.getUniqueName(ISO_FOLDER);
        ClientUtils.createFolder(this.connection, this.context.datacenterMoRef, String.format(VM_PATH_FORMAT, dataStoreName, folderName));
        // 5) form the upload url and acquire generic service ticket for it
        String isoUrl = String.format(ISO_UPLOAD_URL, hostName, VimUtils.encode(folderName), VimUtils.encode(filename), VimUtils.encode(dataStoreName));
        String ticket = this.connection.getGenericServiceTicket(isoUrl);
        // 6) create external client that accepts all certificates
        TrustManager[] trustManagers = new TrustManager[] { ClientUtils.getDefaultTrustManager() };
        ServiceClient serviceClient = ClientUtils.getCustomServiceClient(trustManagers, this.host, URI.create(isoUrl), this.getClass().getSimpleName());
        // 7) PUT operation for the iso content
        Operation putISO = Operation.createPut(URI.create(isoUrl));
        putISO.setContentType(MEDIA_TYPE_APPLICATION_OCTET_STREAM).setContentLength(contentToUpload.length).addRequestHeader("Cookie", "vmware_cgi_ticket=" + ticket).setBody(contentToUpload).setReferer(this.host.getUri());
        return serviceClient.sendWithDeferredResult(putISO).thenApply(op -> {
            String diskFullPath = String.format(FULL_PATH, dataStoreName, folderName, filename);
            // Update the details of the disk
            CustomProperties.of(this.diskState).put(DISK_FULL_PATH, diskFullPath).put(DISK_PARENT_DIRECTORY, String.format(PARENT_DIR, dataStoreName, folderName)).put(DISK_DATASTORE_NAME, dataStoreName);
            this.diskState.sourceImageReference = VimUtils.datastorePathToUri(diskFullPath);
            return this.diskState;
        });
    } catch (Exception e) {
        return DeferredResult.failed(e);
    }
}
Also used : Element(com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element) Operation(com.vmware.xenon.common.Operation) FinderException(com.vmware.photon.controller.model.adapters.vsphere.util.finders.FinderException) TrustManager(javax.net.ssl.TrustManager) ArrayOfDatastoreHostMount(com.vmware.vim25.ArrayOfDatastoreHostMount) ServiceClient(com.vmware.xenon.common.ServiceClient) DatastoreHostMount(com.vmware.vim25.DatastoreHostMount) ArrayOfDatastoreHostMount(com.vmware.vim25.ArrayOfDatastoreHostMount) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 44 with Folder

use of com.vmware.vim25.mo.Folder in project vsphere-cloud-plugin by jenkinsci.

the class VSphere method folderExists.

/*
     Check if folder exists along all the vSphere folders
     */
public Boolean folderExists(String folderPath) throws VSphereException {
    try {
        String[] folderHierarchy = folderPath.split("/");
        ManagedEntity folder = null;
        for (int i = 0; i < folderHierarchy.length; i++) {
            if (i == 0) {
                folder = new InventoryNavigator(getServiceInstance().getRootFolder()).searchManagedEntity("Folder", folderHierarchy[i]);
            } else {
                folder = new InventoryNavigator(folder).searchManagedEntity(null, folderHierarchy[i]);
            }
            if (folder == null) {
                return false;
            }
        }
        return true;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failed while checking if folder exists");
        throw new VSphereException(e);
    }
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) InventoryNavigator(com.vmware.vim25.mo.InventoryNavigator) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException)

Example 45 with Folder

use of com.vmware.vim25.mo.Folder 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);
    }
}
Also used : Task(com.vmware.vim25.mo.Task) VirtualMachineConfigInfo(com.vmware.vim25.VirtualMachineConfigInfo) Folder(com.vmware.vim25.mo.Folder) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) VirtualMachineSnapshot(com.vmware.vim25.mo.VirtualMachineSnapshot) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) CustomizationSpecItem(com.vmware.vim25.CustomizationSpecItem) VirtualMachineRelocateSpec(com.vmware.vim25.VirtualMachineRelocateSpec) VirtualMachineCloneSpec(com.vmware.vim25.VirtualMachineCloneSpec) VirtualMachine(com.vmware.vim25.mo.VirtualMachine)

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