Search in sources :

Example 66 with Task

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

the class VSphere method powerOffVm.

public void powerOffVm(VirtualMachine vm, boolean evenIfSuspended, boolean shutdownGracefully) throws VSphereException {
    if (vm.getConfig().template)
        throw new VSphereException("VM represents a template!");
    if (isPoweredOn(vm) || (evenIfSuspended && isSuspended(vm))) {
        boolean doHardShutdown = true;
        String status;
        try {
            if (!isSuspended(vm) && shutdownGracefully && vmToolIsEnabled(vm)) {
                LOGGER.log(Level.FINER, "Requesting guest shutdown");
                vm.shutdownGuest();
                // Wait for up to 180 seconds for a shutdown - then shutdown hard.
                for (int i = 0; i <= 180; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // build aborted
                        // pass interrupt upwards
                        Thread.currentThread().interrupt();
                        throw new VSphereException("VM power-down interrupted", e);
                    }
                    if (isPoweredOff(vm)) {
                        doHardShutdown = false;
                        LOGGER.log(Level.FINER, "VM gracefully powered down successfully.");
                        return;
                    }
                }
            }
            if (doHardShutdown) {
                LOGGER.log(Level.FINER, "Powering off the VM");
                final Task task = vm.powerOffVM_Task();
                status = task.waitForTask();
                if (status.equals(Task.SUCCESS)) {
                    LOGGER.log(Level.FINER, "VM was powered down successfully.");
                    return;
                }
                throw newVSphereException(task.getTaskInfo(), "Machine could not be powered down!");
            }
        } catch (RuntimeException | VSphereException e) {
            throw e;
        } catch (Exception e) {
            throw new VSphereException(e);
        }
    } else if (isPoweredOff(vm)) {
        LOGGER.log(Level.FINER, "Machine is already off.");
        return;
    }
    throw new VSphereException("Machine could not be powered down!");
}
Also used : Task(com.vmware.vim25.mo.Task) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException)

Example 67 with Task

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

the class VSphere method renameVm.

/**
 * Renames the VM vSphere
 * @param oldName the current name of the vm
 * @param newName the new name of the vm
 * @throws VSphereException If an error occurred.
 */
public void renameVm(String oldName, String newName) throws VSphereException {
    try {
        VirtualMachine vm = getVmByName(oldName);
        if (vm == null) {
            throw new VSphereNotFoundException("VM", oldName);
        }
        final Task task = vm.rename_Task(newName);
        final String status = task.waitForTask();
        if (status.equals(Task.SUCCESS)) {
            LOGGER.log(Level.FINER, "VM was renamed successfully.");
            return;
        }
        throw newVSphereException(task.getTaskInfo(), "Could not rename VM \"" + oldName + "\"!");
    } catch (RuntimeException | VSphereException e) {
        throw e;
    } catch (Exception e) {
        throw new VSphereException(e.getMessage(), e);
    }
}
Also used : Task(com.vmware.vim25.mo.Task) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) VirtualMachine(com.vmware.vim25.mo.VirtualMachine)

Example 68 with Task

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

the class VSphere method reconfigureVm.

public void reconfigureVm(String name, VirtualMachineConfigSpec spec) throws VSphereException {
    VirtualMachine vm = getVmByName(name);
    if (vm == null) {
        throw new VSphereNotFoundException("VM or template", name);
    }
    LOGGER.log(Level.FINER, "Reconfiguring VM. Please wait ...");
    try {
        Task task = vm.reconfigVM_Task(spec);
        String status = task.waitForTask();
        if (status.equals(TaskInfoState.success.toString())) {
            return;
        }
        throw newVSphereException(task.getTaskInfo(), "Couldn't reconfigure \"" + name + "\"!");
    } catch (RuntimeException | VSphereException e) {
        throw e;
    } catch (Exception e) {
        throw new VSphereException("VM cannot be reconfigured:" + e.getMessage(), e);
    }
}
Also used : Task(com.vmware.vim25.mo.Task) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) VirtualMachine(com.vmware.vim25.mo.VirtualMachine)

Example 69 with Task

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

the class VSphere method destroyVm.

/**
 * Destroys the VM in vSphere
 * @param name - VM object to destroy
 * @param failOnNoExist If true and the VM does not exist then a {@link VSphereNotFoundException} will be thrown.
 * @throws VSphereException If an error occurred.
 */
public void destroyVm(String name, boolean failOnNoExist) throws VSphereException {
    try {
        VirtualMachine vm = getVmByName(name);
        if (vm == null) {
            if (failOnNoExist)
                throw new VSphereNotFoundException("VM", name);
            LOGGER.log(Level.FINER, "VM \"" + name + "\" does not exist, or already deleted!");
            return;
        }
        if (!vm.getConfig().template) {
            powerOffVm(vm, true, false);
        }
        final Task task = vm.destroy_Task();
        String status = task.waitForTask();
        if (status.equals(Task.SUCCESS)) {
            LOGGER.log(Level.FINER, "VM \"" + name + "\" was deleted successfully.");
            return;
        }
        throw newVSphereException(task.getTaskInfo(), "Could not delete VM \"" + name + "\"!");
    } catch (RuntimeException | VSphereException e) {
        throw e;
    } catch (Exception e) {
        throw new VSphereException(e.getMessage(), e);
    }
}
Also used : Task(com.vmware.vim25.mo.Task) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) VirtualMachine(com.vmware.vim25.mo.VirtualMachine)

Example 70 with Task

use of com.vmware.vim25.mo.Task 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)39 Task (com.vmware.vim25.mo.Task)27 TaskInfo (com.vmware.vim25.TaskInfo)21 RemoteException (java.rmi.RemoteException)17 ArrayList (java.util.ArrayList)15 QueryTask (com.vmware.xenon.services.common.QueryTask)14 Operation (com.vmware.xenon.common.Operation)13 List (java.util.List)12 PhotonModelUriUtils (com.vmware.photon.controller.model.util.PhotonModelUriUtils)11 QueryUtils (com.vmware.photon.controller.model.query.QueryUtils)10 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)10 ComputeDescriptionService (com.vmware.photon.controller.model.resources.ComputeDescriptionService)9 DiskService (com.vmware.photon.controller.model.resources.DiskService)9 TaskInfoState (com.vmware.vim25.TaskInfoState)9 ComputeService (com.vmware.photon.controller.model.resources.ComputeService)8 ArrayOfManagedObjectReference (com.vmware.vim25.ArrayOfManagedObjectReference)8 RuntimeFaultFaultMsg (com.vmware.vim25.RuntimeFaultFaultMsg)8 DeferredResult (com.vmware.xenon.common.DeferredResult)8 ComputeProperties (com.vmware.photon.controller.model.ComputeProperties)7 InvalidPropertyFaultMsg (com.vmware.vim25.InvalidPropertyFaultMsg)7