Search in sources :

Example 1 with CustomizationSpec

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

the class VSphereAdapterInstanceService method handleCreateInstance.

private void handleCreateInstance(ProvisionContext ctx) {
    ctx.pool.submit(ctx.getAdapterManagementReference(), ctx.vSphereCredentials, (connection, ce) -> {
        if (ctx.fail(ce)) {
            return;
        }
        try {
            InstanceClient client = new InstanceClient(connection, ctx);
            ComputeState state;
            if (ctx.templateMoRef != null) {
                state = client.createInstanceFromTemplate(ctx.templateMoRef);
            } else if (ctx.image != null) {
                ManagedObjectReference moRef = CustomProperties.of(ctx.image).getMoRef(CustomProperties.MOREF);
                if (moRef != null) {
                    // the image is backed by a template VM
                    state = client.createInstanceFromTemplate(moRef);
                } else {
                    // library item
                    state = client.createInstanceFromLibraryItem(ctx.image);
                }
            } else if (ctx.snapshotMoRef != null) {
                state = client.createInstanceFromSnapshot();
            } else {
                state = client.createInstance();
            }
            if (state == null) {
                // assume they will patch the task if they have provisioned the vm
                return;
            }
            // populate state, MAC address being very important
            VmOverlay vmOverlay = client.enrichStateFromVm(state);
            Operation[] finishTask = new Operation[1];
            for (NetworkInterfaceStateWithDetails nic : ctx.nics) {
                // request guest customization while vm of powered off
                SubnetState subnet = nic.subnet;
                if (subnet != null && nic.description != null && nic.description.assignment == IpAssignment.STATIC) {
                    CustomizationClient cc = new CustomizationClient(connection, ctx.child, vmOverlay.getGuestId());
                    CustomizationSpec template = new CustomizationSpec();
                    cc.customizeNic(vmOverlay.getPrimaryMac(), ctx.child.hostName, nic.address, subnet, template);
                    cc.customizeDns(subnet.dnsServerAddresses, subnet.dnsSearchDomains, template);
                    ManagedObjectReference task = cc.customizeGuest(client.getVm(), template);
                    TaskInfo taskInfo = VimUtils.waitTaskEnd(connection, task);
                    if (taskInfo.getState() == TaskInfoState.ERROR) {
                        VimUtils.rethrow(taskInfo.getError());
                    }
                }
            }
            // power on machine before enrichment
            if (ctx.child.powerState == PowerState.ON) {
                new PowerStateClient(connection).changePowerState(client.getVm(), PowerState.ON, null, 0);
                state.powerState = PowerState.ON;
                Operation op = ctx.mgr.createTaskPatch(TaskStage.FINISHED);
                Boolean awaitIp = CustomProperties.of(ctx.child).getBoolean(ComputeProperties.CUSTOM_PROP_COMPUTE_AWAIT_IP, true);
                if (awaitIp) {
                    Runnable runnable = createCheckForIpTask(ctx.pool, op, client.getVm(), connection.createUnmanagedCopy(), ctx.child.documentSelfLink, ctx);
                    ctx.pool.schedule(runnable, IP_CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS);
                } else {
                    finishTask[0] = op;
                }
            } else {
                // only finish the task without waiting for IP
                finishTask[0] = ctx.mgr.createTaskPatch(TaskStage.FINISHED);
            }
            updateNicsAfterProvisionSuccess(vmOverlay.getNics(), ctx);
            updateDiskLinksAfterProvisionSuccess(state, vmOverlay.getDisks(), ctx);
            state.lifecycleState = LifecycleState.READY;
            // Find the host link where the computed is provisioned and patch the
            // compute state.
            queryHostDocumentAndUpdateCompute(ctx, vmOverlay.getHost()).thenCompose(computeState -> {
                ComputeState hostState = computeState.iterator().next();
                CustomProperties.of(state).put(VC_UUID, CustomProperties.of(hostState).getString(VC_UUID)).put(DATACENTER_SELF_LINK, CustomProperties.of(hostState).getString(DATACENTER_SELF_LINK)).put(COMPUTE_HOST_LINK_PROP_NAME, hostState.documentSelfLink);
                return createComputeResourcePatch(state, ctx.computeReference);
            }).whenComplete((o, e) -> {
                if (e != null) {
                    ctx.fail(e);
                    return;
                }
                if (finishTask.length > 0) {
                    finishTask[0].sendWith(this);
                }
            });
        } catch (Exception e) {
            ctx.fail(e);
        }
    });
}
Also used : PowerState(com.vmware.photon.controller.model.resources.ComputeService.PowerState) IpAssignment(com.vmware.photon.controller.model.resources.NetworkInterfaceDescriptionService.IpAssignment) VirtualEthernetCardOpaqueNetworkBackingInfo(com.vmware.vim25.VirtualEthernetCardOpaqueNetworkBackingInfo) QueryTask(com.vmware.xenon.services.common.QueryTask) LifecycleState(com.vmware.photon.controller.model.resources.ComputeService.LifecycleState) DiskType(com.vmware.photon.controller.model.resources.DiskService.DiskType) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) Map(java.util.Map) COMPUTE_HOST_LINK_PROP_NAME(com.vmware.photon.controller.model.ComputeProperties.COMPUTE_HOST_LINK_PROP_NAME) Connection(com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection) URI(java.net.URI) VirtualDevice(com.vmware.vim25.VirtualDevice) TaskInfo(com.vmware.vim25.TaskInfo) NsxProperties(com.vmware.photon.controller.model.adapters.vsphere.network.NsxProperties) CustomizationSpec(com.vmware.vim25.CustomizationSpec) DiskStateExpanded(com.vmware.photon.controller.model.resources.DiskService.DiskStateExpanded) NetworkInterfaceState(com.vmware.photon.controller.model.resources.NetworkInterfaceService.NetworkInterfaceState) StatelessService(com.vmware.xenon.common.StatelessService) Collection(java.util.Collection) TaskManager(com.vmware.photon.controller.model.adapters.util.TaskManager) Collectors(java.util.stream.Collectors) ClientUtils.handleVirtualDiskUpdate(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.handleVirtualDiskUpdate) List(java.util.List) InvalidPropertyFaultMsg(com.vmware.vim25.InvalidPropertyFaultMsg) DeferredResult(com.vmware.xenon.common.DeferredResult) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) ClientUtils.handleVirtualDeviceUpdate(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.handleVirtualDeviceUpdate) VC_UUID(com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.VC_UUID) VirtualFloppy(com.vmware.vim25.VirtualFloppy) VimPath(com.vmware.photon.controller.model.adapters.vsphere.util.VimPath) ComputeProperties(com.vmware.photon.controller.model.ComputeProperties) PhotonModelUriUtils(com.vmware.photon.controller.model.util.PhotonModelUriUtils) VirtualEthernetCardDistributedVirtualPortBackingInfo(com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo) HashMap(java.util.HashMap) GetMoRef(com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef) RuntimeFaultFaultMsg(com.vmware.vim25.RuntimeFaultFaultMsg) StringUtil(io.netty.util.internal.StringUtil) DvsProperties(com.vmware.photon.controller.model.adapters.vsphere.network.DvsProperties) VirtualEthernetCardNetworkBackingInfo(com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) ComputeInstanceRequest(com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest) VirtualCdrom(com.vmware.vim25.VirtualCdrom) ServiceStateCollectionUpdateRequest(com.vmware.xenon.common.ServiceStateCollectionUpdateRequest) ClientUtils.findMatchingDiskState(com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findMatchingDiskState) CollectionUtils(org.apache.commons.collections.CollectionUtils) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) ResourceState(com.vmware.photon.controller.model.resources.ResourceState) DATACENTER_SELF_LINK(com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.DATACENTER_SELF_LINK) Operation(com.vmware.xenon.common.Operation) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) VirtualDeviceBackingInfo(com.vmware.vim25.VirtualDeviceBackingInfo) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) TaskStage(com.vmware.xenon.common.TaskState.TaskStage) NetworkInterfaceStateWithDetails(com.vmware.photon.controller.model.adapters.vsphere.ProvisionContext.NetworkInterfaceStateWithDetails) TimeUnit(java.util.concurrent.TimeUnit) VirtualDisk(com.vmware.vim25.VirtualDisk) ClusterUtil(com.vmware.photon.controller.model.util.ClusterUtil) VirtualEthernetCard(com.vmware.vim25.VirtualEthernetCard) Collections(java.util.Collections) TaskInfoState(com.vmware.vim25.TaskInfoState) OperationJoin(com.vmware.xenon.common.OperationJoin) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) NetworkInterfaceStateWithDetails(com.vmware.photon.controller.model.adapters.vsphere.ProvisionContext.NetworkInterfaceStateWithDetails) Operation(com.vmware.xenon.common.Operation) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) TaskInfo(com.vmware.vim25.TaskInfo) CustomizationSpec(com.vmware.vim25.CustomizationSpec) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 2 with CustomizationSpec

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

the class CustomizationClient method customizeNic.

public void customizeNic(String macAddress, String hostName, String address, SubnetState subnetState, CustomizationSpec template) {
    // remove existing mapping
    template.getNicSettingMap().removeIf(x -> Objects.equals(x.getMacAddress(), macAddress));
    CustomizationAdapterMapping mapping = new CustomizationAdapterMapping();
    mapping.setMacAddress(macAddress);
    CustomizationIPSettings adapter = new CustomizationIPSettings();
    mapping.setAdapter(adapter);
    adapter.setSubnetMask(cidr2mask(subnetState.subnetCIDR));
    adapter.getGateway().add(subnetState.gatewayAddress);
    adapter.setDnsDomain(subnetState.domain);
    CustomizationFixedIp ipGen = new CustomizationFixedIp();
    ipGen.setIpAddress(address);
    adapter.setIp(ipGen);
    template.getNicSettingMap().add(mapping);
    if (isLinux()) {
        CustomizationLinuxPrep identity = new CustomizationLinuxPrep();
        template.setIdentity(identity);
        identity.setDomain(subnetState.domain);
        CustomizationFixedName name = new CustomizationFixedName();
        if (hostName == null || hostName.isEmpty()) {
            hostName = makeHostName(UriUtils.getLastPathSegment(this.state.documentSelfLink));
        }
        name.setName(hostName);
        identity.setHostName(name);
        template.setOptions(new CustomizationLinuxOptions());
    }
}
Also used : CustomizationFixedIp(com.vmware.vim25.CustomizationFixedIp) CustomizationIPSettings(com.vmware.vim25.CustomizationIPSettings) CustomizationLinuxPrep(com.vmware.vim25.CustomizationLinuxPrep) CustomizationAdapterMapping(com.vmware.vim25.CustomizationAdapterMapping) CustomizationLinuxOptions(com.vmware.vim25.CustomizationLinuxOptions) CustomizationFixedName(com.vmware.vim25.CustomizationFixedName)

Example 3 with CustomizationSpec

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

the class CustomizationClient method customizeDns.

public void customizeDns(List<String> dnsServers, List<String> dnsSearchDomains, CustomizationSpec template) {
    CustomizationGlobalIPSettings settings = new CustomizationGlobalIPSettings();
    if (dnsServers != null) {
        settings.getDnsServerList().addAll(dnsServers);
    }
    if (dnsSearchDomains != null) {
        settings.getDnsSuffixList().addAll(dnsSearchDomains);
    }
    template.setGlobalIPSettings(settings);
}
Also used : CustomizationGlobalIPSettings(com.vmware.vim25.CustomizationGlobalIPSettings)

Example 4 with CustomizationSpec

use of com.vmware.vim25.CustomizationSpec 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

ComputeProperties (com.vmware.photon.controller.model.ComputeProperties)1 COMPUTE_HOST_LINK_PROP_NAME (com.vmware.photon.controller.model.ComputeProperties.COMPUTE_HOST_LINK_PROP_NAME)1 ComputeInstanceRequest (com.vmware.photon.controller.model.adapterapi.ComputeInstanceRequest)1 TaskManager (com.vmware.photon.controller.model.adapters.util.TaskManager)1 ClientUtils.findMatchingDiskState (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.findMatchingDiskState)1 ClientUtils.handleVirtualDeviceUpdate (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.handleVirtualDeviceUpdate)1 ClientUtils.handleVirtualDiskUpdate (com.vmware.photon.controller.model.adapters.vsphere.ClientUtils.handleVirtualDiskUpdate)1 DATACENTER_SELF_LINK (com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.DATACENTER_SELF_LINK)1 VC_UUID (com.vmware.photon.controller.model.adapters.vsphere.CustomProperties.VC_UUID)1 NetworkInterfaceStateWithDetails (com.vmware.photon.controller.model.adapters.vsphere.ProvisionContext.NetworkInterfaceStateWithDetails)1 DvsProperties (com.vmware.photon.controller.model.adapters.vsphere.network.DvsProperties)1 NsxProperties (com.vmware.photon.controller.model.adapters.vsphere.network.NsxProperties)1 VimPath (com.vmware.photon.controller.model.adapters.vsphere.util.VimPath)1 Connection (com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection)1 GetMoRef (com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef)1 QueryUtils (com.vmware.photon.controller.model.query.QueryUtils)1 ComputeService (com.vmware.photon.controller.model.resources.ComputeService)1 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)1 LifecycleState (com.vmware.photon.controller.model.resources.ComputeService.LifecycleState)1 PowerState (com.vmware.photon.controller.model.resources.ComputeService.PowerState)1