Search in sources :

Example 1 with DatastoreFile

use of com.cloud.hypervisor.vmware.mo.DatastoreFile in project cloudstack by apache.

the class VmwareResource method deleteUnregisteredVmFiles.

private void deleteUnregisteredVmFiles(VirtualMachineFileLayoutEx vmFileLayout, DatacenterMO dcMo, boolean deleteDisks) throws Exception {
    s_logger.debug("Deleting files associated with an existing VM that was unregistered");
    DatastoreFile vmFolder = null;
    try {
        List<VirtualMachineFileLayoutExFileInfo> fileInfo = vmFileLayout.getFile();
        for (VirtualMachineFileLayoutExFileInfo file : fileInfo) {
            DatastoreFile fileInDatastore = new DatastoreFile(file.getName());
            // In case of linked clones, VM file layout includes the base disk so don't delete all disk files.
            if (file.getType().startsWith("disk") || file.getType().startsWith("digest"))
                continue;
            else if (file.getType().equals("config"))
                vmFolder = new DatastoreFile(fileInDatastore.getDatastoreName(), fileInDatastore.getDir());
            DatastoreMO dsMo = new DatastoreMO(dcMo.getContext(), dcMo.findDatastore(fileInDatastore.getDatastoreName()));
            s_logger.debug("Deleting file: " + file.getName());
            dsMo.deleteFile(file.getName(), dcMo.getMor(), true);
        }
        // Delete files that are present in the VM folder - this will take care of the VM disks as well.
        DatastoreMO vmFolderDsMo = new DatastoreMO(dcMo.getContext(), dcMo.findDatastore(vmFolder.getDatastoreName()));
        String[] files = vmFolderDsMo.listDirContent(vmFolder.getPath());
        if (deleteDisks) {
            for (String file : files) {
                String vmDiskFileFullPath = String.format("%s/%s", vmFolder.getPath(), file);
                s_logger.debug("Deleting file: " + vmDiskFileFullPath);
                vmFolderDsMo.deleteFile(vmDiskFileFullPath, dcMo.getMor(), true);
            }
        }
        // Delete VM folder
        if (deleteDisks || files.length == 0) {
            s_logger.debug("Deleting folder: " + vmFolder.getPath());
            vmFolderDsMo.deleteFolder(vmFolder.getPath(), dcMo.getMor());
        }
    } catch (Exception e) {
        String message = "Failed to delete files associated with an existing VM that was unregistered due to " + VmwareHelper.getExceptionMessage(e);
        s_logger.warn(message, e);
    }
}
Also used : DatastoreFile(com.cloud.hypervisor.vmware.mo.DatastoreFile) VirtualMachineFileLayoutExFileInfo(com.vmware.vim25.VirtualMachineFileLayoutExFileInfo) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException)

Example 2 with DatastoreFile

use of com.cloud.hypervisor.vmware.mo.DatastoreFile in project cloudstack by apache.

the class VmwareResource method syncDiskChain.

// return the finalized disk chain for startup, from top to bottom
private String[] syncDiskChain(DatacenterMO dcMo, VirtualMachineMO vmMo, VirtualMachineTO vmSpec, DiskTO vol, VirtualMachineDiskInfo diskInfo, HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> dataStoresDetails) throws Exception {
    VolumeObjectTO volumeTO = (VolumeObjectTO) vol.getData();
    DataStoreTO primaryStore = volumeTO.getDataStore();
    Map<String, String> details = vol.getDetails();
    boolean isManaged = false;
    String iScsiName = null;
    if (details != null) {
        isManaged = Boolean.parseBoolean(details.get(DiskTO.MANAGED));
        iScsiName = details.get(DiskTO.IQN);
    }
    // if the storage is managed, iScsiName should not be null
    String datastoreName = isManaged ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid();
    Pair<ManagedObjectReference, DatastoreMO> volumeDsDetails = dataStoresDetails.get(datastoreName);
    if (volumeDsDetails == null) {
        throw new Exception("Primary datastore " + primaryStore.getUuid() + " is not mounted on host.");
    }
    DatastoreMO dsMo = volumeDsDetails.second();
    // we will honor vCenter's meta if it exists
    if (diskInfo != null) {
        // to deal with run-time upgrade to maintain the new datastore folder structure
        String[] disks = diskInfo.getDiskChain();
        for (int i = 0; i < disks.length; i++) {
            DatastoreFile file = new DatastoreFile(disks[i]);
            if (!isManaged && file.getDir() != null && file.getDir().isEmpty()) {
                s_logger.info("Perform run-time datastore folder upgrade. sync " + disks[i] + " to VM folder");
                disks[i] = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmMo.getName(), dsMo, file.getFileBaseName());
            }
        }
        return disks;
    }
    final String datastoreDiskPath;
    if (isManaged) {
        if (volumeTO.getVolumeType() == Volume.Type.ROOT) {
            datastoreDiskPath = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmMo.getName(), dsMo, volumeTO.getName());
        } else {
            datastoreDiskPath = dsMo.getDatastorePath(dsMo.getName() + ".vmdk");
        }
    } else {
        datastoreDiskPath = VmwareStorageLayoutHelper.syncVolumeToVmDefaultFolder(dcMo, vmMo.getName(), dsMo, volumeTO.getPath());
    }
    if (!dsMo.fileExists(datastoreDiskPath)) {
        s_logger.warn("Volume " + volumeTO.getId() + " does not seem to exist on datastore, out of sync? path: " + datastoreDiskPath);
    }
    return new String[] { datastoreDiskPath };
}
Also used : PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) DatastoreFile(com.cloud.hypervisor.vmware.mo.DatastoreFile) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 3 with DatastoreFile

use of com.cloud.hypervisor.vmware.mo.DatastoreFile in project cloudstack by apache.

the class VmwareResource method postDiskConfigBeforeStart.

private void postDiskConfigBeforeStart(VirtualMachineMO vmMo, VirtualMachineTO vmSpec, DiskTO[] sortedDisks, int ideControllerKey, int scsiControllerKey, Map<String, String> iqnToPath, VmwareHypervisorHost hyperHost, VmwareContext context) throws Exception {
    VirtualMachineDiskInfoBuilder diskInfoBuilder = vmMo.getDiskInfoBuilder();
    for (DiskTO vol : sortedDisks) {
        if (vol.getType() == Volume.Type.ISO)
            continue;
        VolumeObjectTO volumeTO = (VolumeObjectTO) vol.getData();
        VirtualMachineDiskInfo diskInfo = getMatchingExistingDisk(diskInfoBuilder, vol, hyperHost, context);
        assert (diskInfo != null);
        String[] diskChain = diskInfo.getDiskChain();
        assert (diskChain.length > 0);
        Map<String, String> details = vol.getDetails();
        boolean managed = false;
        if (details != null) {
            managed = Boolean.parseBoolean(details.get(DiskTO.MANAGED));
        }
        DatastoreFile file = new DatastoreFile(diskChain[0]);
        if (managed) {
            DatastoreFile originalFile = new DatastoreFile(volumeTO.getPath());
            if (!file.getFileBaseName().equalsIgnoreCase(originalFile.getFileBaseName())) {
                if (s_logger.isInfoEnabled())
                    s_logger.info("Detected disk-chain top file change on volume: " + volumeTO.getId() + " " + volumeTO.getPath() + " -> " + diskChain[0]);
            }
        } else {
            if (!file.getFileBaseName().equalsIgnoreCase(volumeTO.getPath())) {
                if (s_logger.isInfoEnabled())
                    s_logger.info("Detected disk-chain top file change on volume: " + volumeTO.getId() + " " + volumeTO.getPath() + " -> " + file.getFileBaseName());
            }
        }
        VolumeObjectTO volInSpec = getVolumeInSpec(vmSpec, volumeTO);
        if (volInSpec != null) {
            if (managed) {
                String datastoreVolumePath = diskChain[0];
                iqnToPath.put(details.get(DiskTO.IQN), datastoreVolumePath);
                vol.setPath(datastoreVolumePath);
                volumeTO.setPath(datastoreVolumePath);
                volInSpec.setPath(datastoreVolumePath);
            } else {
                volInSpec.setPath(file.getFileBaseName());
            }
            volInSpec.setChainInfo(_gson.toJson(diskInfo));
        }
    }
}
Also used : DatastoreFile(com.cloud.hypervisor.vmware.mo.DatastoreFile) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) VirtualMachineDiskInfoBuilder(com.cloud.hypervisor.vmware.mo.VirtualMachineDiskInfoBuilder) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) DiskTO(com.cloud.agent.api.to.DiskTO)

Example 4 with DatastoreFile

use of com.cloud.hypervisor.vmware.mo.DatastoreFile in project cloudstack by apache.

the class VmwareResource method getMatchingExistingDisk.

private VirtualMachineDiskInfo getMatchingExistingDisk(VirtualMachineDiskInfoBuilder diskInfoBuilder, DiskTO vol, VmwareHypervisorHost hyperHost, VmwareContext context) throws Exception {
    if (diskInfoBuilder != null) {
        VolumeObjectTO volume = (VolumeObjectTO) vol.getData();
        String dsName = null;
        String diskBackingFileBaseName = null;
        Map<String, String> details = vol.getDetails();
        boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED));
        if (isManaged) {
            String iScsiName = details.get(DiskTO.IQN);
            // if the storage is managed, iScsiName should not be null
            dsName = VmwareResource.getDatastoreName(iScsiName);
            diskBackingFileBaseName = new DatastoreFile(volume.getPath()).getFileBaseName();
        } else {
            ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, volume.getDataStore().getUuid());
            DatastoreMO dsMo = new DatastoreMO(context, morDs);
            dsName = dsMo.getName();
            diskBackingFileBaseName = volume.getPath();
        }
        VirtualMachineDiskInfo diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(diskBackingFileBaseName, dsName);
        if (diskInfo != null) {
            s_logger.info("Found existing disk info from volume path: " + volume.getPath());
            return diskInfo;
        } else {
            String chainInfo = volume.getChainInfo();
            if (chainInfo != null) {
                VirtualMachineDiskInfo infoInChain = _gson.fromJson(chainInfo, VirtualMachineDiskInfo.class);
                if (infoInChain != null) {
                    String[] disks = infoInChain.getDiskChain();
                    if (disks.length > 0) {
                        for (String diskPath : disks) {
                            DatastoreFile file = new DatastoreFile(diskPath);
                            diskInfo = diskInfoBuilder.getDiskInfoByBackingFileBaseName(file.getFileBaseName(), dsName);
                            if (diskInfo != null) {
                                s_logger.info("Found existing disk from chain info: " + diskPath);
                                return diskInfo;
                            }
                        }
                    }
                    if (diskInfo == null) {
                        diskInfo = diskInfoBuilder.getDiskInfoByDeviceBusName(infoInChain.getDiskDeviceBusName());
                        if (diskInfo != null) {
                            s_logger.info("Found existing disk from from chain device bus information: " + infoInChain.getDiskDeviceBusName());
                            return diskInfo;
                        }
                    }
                }
            }
        }
    }
    return null;
}
Also used : DatastoreFile(com.cloud.hypervisor.vmware.mo.DatastoreFile) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 5 with DatastoreFile

use of com.cloud.hypervisor.vmware.mo.DatastoreFile in project cloudstack by apache.

the class VmwareResource method execute.

protected StartAnswer execute(StartCommand cmd) {
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Executing resource StartCommand: " + _gson.toJson(cmd));
    }
    VirtualMachineTO vmSpec = cmd.getVirtualMachine();
    boolean vmAlreadyExistsInVcenter = false;
    String existingVmName = null;
    VirtualMachineFileInfo existingVmFileInfo = null;
    VirtualMachineFileLayoutEx existingVmFileLayout = null;
    Pair<String, String> names = composeVmNames(vmSpec);
    String vmInternalCSName = names.first();
    String vmNameOnVcenter = names.second();
    String dataDiskController = vmSpec.getDetails().get(VmDetailConstants.DATA_DISK_CONTROLLER);
    String rootDiskController = vmSpec.getDetails().get(VmDetailConstants.ROOT_DISK_CONTROLLER);
    DiskTO rootDiskTO = null;
    // This helps avoid mix of different scsi subtype controllers in instance.
    if (DiskControllerType.lsilogic == DiskControllerType.getType(rootDiskController)) {
        dataDiskController = DiskControllerType.scsi.toString();
    }
    // Validate the controller types
    dataDiskController = DiskControllerType.getType(dataDiskController).toString();
    rootDiskController = DiskControllerType.getType(rootDiskController).toString();
    if (DiskControllerType.getType(rootDiskController) == DiskControllerType.none) {
        throw new CloudRuntimeException("Invalid root disk controller detected : " + rootDiskController);
    }
    if (DiskControllerType.getType(dataDiskController) == DiskControllerType.none) {
        throw new CloudRuntimeException("Invalid data disk controller detected : " + dataDiskController);
    }
    Pair<String, String> controllerInfo = new Pair<String, String>(rootDiskController, dataDiskController);
    Boolean systemVm = vmSpec.getType().isUsedBySystem();
    // Thus, vmInternalCSName always holds i-x-y, the cloudstack generated internal VM name.
    VmwareContext context = getServiceContext();
    DatacenterMO dcMo = null;
    try {
        VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
        VmwareHypervisorHost hyperHost = getHyperHost(context);
        dcMo = new DatacenterMO(hyperHost.getContext(), hyperHost.getHyperHostDatacenter());
        // Validate VM name is unique in Datacenter
        VirtualMachineMO vmInVcenter = dcMo.checkIfVmAlreadyExistsInVcenter(vmNameOnVcenter, vmInternalCSName);
        if (vmInVcenter != null) {
            vmAlreadyExistsInVcenter = true;
            String msg = "VM with name: " + vmNameOnVcenter + " already exists in vCenter.";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        String guestOsId = translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs(), vmSpec.getPlatformEmulator()).value();
        DiskTO[] disks = validateDisks(vmSpec.getDisks());
        assert (disks.length > 0);
        NicTO[] nics = vmSpec.getNics();
        HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks, cmd);
        if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty())) {
            String msg = "Unable to locate datastore details of the volumes to be attached";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        DatastoreMO dsRootVolumeIsOn = getDatastoreThatRootDiskIsOn(dataStoresDetails, disks);
        if (dsRootVolumeIsOn == null) {
            String msg = "Unable to locate datastore details of root volume";
            s_logger.error(msg);
            throw new Exception(msg);
        }
        VirtualMachineDiskInfoBuilder diskInfoBuilder = null;
        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
        DiskControllerType systemVmScsiControllerType = DiskControllerType.lsilogic;
        int firstScsiControllerBusNum = 0;
        int numScsiControllerForSystemVm = 1;
        boolean hasSnapshot = false;
        if (vmMo != null) {
            s_logger.info("VM " + vmInternalCSName + " already exists, tear down devices for reconfiguration");
            if (getVmPowerState(vmMo) != PowerState.PowerOff)
                vmMo.safePowerOff(_shutdownWaitMs);
            // retrieve disk information before we tear down
            diskInfoBuilder = vmMo.getDiskInfoBuilder();
            hasSnapshot = vmMo.hasSnapshot();
            if (!hasSnapshot)
                vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class });
            else
                vmMo.tearDownDevices(new Class<?>[] { VirtualEthernetCard.class });
            if (systemVm) {
                ensureScsiDiskControllers(vmMo, systemVmScsiControllerType.toString(), numScsiControllerForSystemVm, firstScsiControllerBusNum);
            } else {
                ensureDiskControllers(vmMo, controllerInfo);
            }
        } else {
            ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
            assert (morDc != null);
            vmMo = hyperHost.findVmOnPeerHyperHost(vmInternalCSName);
            if (vmMo != null) {
                if (s_logger.isInfoEnabled()) {
                    s_logger.info("Found vm " + vmInternalCSName + " at other host, relocate to " + hyperHost.getHyperHostName());
                }
                takeVmFromOtherHyperHost(hyperHost, vmInternalCSName);
                if (getVmPowerState(vmMo) != PowerState.PowerOff)
                    vmMo.safePowerOff(_shutdownWaitMs);
                diskInfoBuilder = vmMo.getDiskInfoBuilder();
                hasSnapshot = vmMo.hasSnapshot();
                if (!hasSnapshot)
                    vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class });
                else
                    vmMo.tearDownDevices(new Class<?>[] { VirtualEthernetCard.class });
                if (systemVm) {
                    // System volumes doesn't require more than 1 SCSI controller as there is no requirement for data volumes.
                    ensureScsiDiskControllers(vmMo, systemVmScsiControllerType.toString(), numScsiControllerForSystemVm, firstScsiControllerBusNum);
                } else {
                    ensureDiskControllers(vmMo, controllerInfo);
                }
            } else {
                // If a VM with the same name is found in a different cluster in the DC, unregister the old VM and configure a new VM (cold-migration).
                VirtualMachineMO existingVmInDc = dcMo.findVm(vmInternalCSName);
                if (existingVmInDc != null) {
                    s_logger.debug("Found VM: " + vmInternalCSName + " on a host in a different cluster. Unregistering the exisitng VM.");
                    existingVmName = existingVmInDc.getName();
                    existingVmFileInfo = existingVmInDc.getFileInfo();
                    existingVmFileLayout = existingVmInDc.getFileLayout();
                    existingVmInDc.unregisterVm();
                }
                Pair<ManagedObjectReference, DatastoreMO> rootDiskDataStoreDetails = null;
                for (DiskTO vol : disks) {
                    if (vol.getType() == Volume.Type.ROOT) {
                        Map<String, String> details = vol.getDetails();
                        boolean managed = false;
                        if (details != null) {
                            managed = Boolean.parseBoolean(details.get(DiskTO.MANAGED));
                        }
                        if (managed) {
                            String datastoreName = VmwareResource.getDatastoreName(details.get(DiskTO.IQN));
                            rootDiskDataStoreDetails = dataStoresDetails.get(datastoreName);
                        } else {
                            DataStoreTO primaryStore = vol.getData().getDataStore();
                            rootDiskDataStoreDetails = dataStoresDetails.get(primaryStore.getUuid());
                        }
                    }
                }
                assert (vmSpec.getMinSpeed() != null) && (rootDiskDataStoreDetails != null);
                boolean vmFolderExists = rootDiskDataStoreDetails.second().folderExists(String.format("[%s]", rootDiskDataStoreDetails.second().getName()), vmNameOnVcenter);
                String vmxFileFullPath = dsRootVolumeIsOn.searchFileInSubFolders(vmNameOnVcenter + ".vmx", false);
                if (vmFolderExists && vmxFileFullPath != null) {
                    // VM can be registered only if .vmx is present.
                    registerVm(vmNameOnVcenter, dsRootVolumeIsOn);
                    vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
                    if (vmMo != null) {
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Found registered vm " + vmInternalCSName + " at host " + hyperHost.getHyperHostName());
                        }
                    }
                    tearDownVm(vmMo);
                } else if (!hyperHost.createBlankVm(vmNameOnVcenter, vmInternalCSName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), getReservedCpuMHZ(vmSpec), vmSpec.getLimitCpuUse(), (int) (vmSpec.getMaxRam() / (1024 * 1024)), getReservedMemoryMb(vmSpec), guestOsId, rootDiskDataStoreDetails.first(), false, controllerInfo, systemVm)) {
                    throw new Exception("Failed to create VM. vmName: " + vmInternalCSName);
                }
            }
            vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
            if (vmMo == null) {
                throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmInternalCSName);
            }
        }
        int totalChangeDevices = disks.length + nics.length;
        DiskTO volIso = null;
        if (vmSpec.getType() != VirtualMachine.Type.User) {
            // system VM needs a patch ISO
            totalChangeDevices++;
        } else {
            volIso = getIsoDiskTO(disks);
            if (volIso == null)
                totalChangeDevices++;
        }
        VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
        VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), getReservedCpuMHZ(vmSpec), (int) (vmSpec.getMaxRam() / (1024 * 1024)), getReservedMemoryMb(vmSpec), guestOsId, vmSpec.getLimitCpuUse());
        // Check for multi-cores per socket settings
        int numCoresPerSocket = 1;
        String coresPerSocket = vmSpec.getDetails().get("cpu.corespersocket");
        if (coresPerSocket != null) {
            String apiVersion = HypervisorHostHelper.getVcenterApiVersion(vmMo.getContext());
            // Property 'numCoresPerSocket' is supported since vSphere API 5.0
            if (apiVersion.compareTo("5.0") >= 0) {
                numCoresPerSocket = NumbersUtil.parseInt(coresPerSocket, 1);
                vmConfigSpec.setNumCoresPerSocket(numCoresPerSocket);
            }
        }
        // Check for hotadd settings
        vmConfigSpec.setMemoryHotAddEnabled(vmMo.isMemoryHotAddSupported(guestOsId));
        String hostApiVersion = ((HostMO) hyperHost).getHostAboutInfo().getApiVersion();
        if (numCoresPerSocket > 1 && hostApiVersion.compareTo("5.0") < 0) {
            s_logger.warn("Dynamic scaling of CPU is not supported for Virtual Machines with multi-core vCPUs in case of ESXi hosts 4.1 and prior. Hence CpuHotAdd will not be" + " enabled for Virtual Machine: " + vmInternalCSName);
            vmConfigSpec.setCpuHotAddEnabled(false);
        } else {
            vmConfigSpec.setCpuHotAddEnabled(vmMo.isCpuHotAddSupported(guestOsId));
        }
        configNestedHVSupport(vmMo, vmSpec, vmConfigSpec);
        VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices];
        int i = 0;
        int ideUnitNumber = 0;
        int scsiUnitNumber = 0;
        int nicUnitNumber = 0;
        int ideControllerKey = vmMo.getIDEDeviceControllerKey();
        int scsiControllerKey = vmMo.getGenericScsiDeviceControllerKeyNoException();
        int controllerKey;
        // prepare systemvm patch ISO
        if (vmSpec.getType() != VirtualMachine.Type.User) {
            // attach ISO (for patching of system VM)
            Pair<String, Long> secStoreUrlAndId = mgr.getSecondaryStorageStoreUrlAndId(Long.parseLong(_dcId));
            String secStoreUrl = secStoreUrlAndId.first();
            Long secStoreId = secStoreUrlAndId.second();
            if (secStoreUrl == null) {
                String msg = "secondary storage for dc " + _dcId + " is not ready yet?";
                throw new Exception(msg);
            }
            mgr.prepareSecondaryStorageStore(secStoreUrl, secStoreId);
            ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl);
            if (morSecDs == null) {
                String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl;
                throw new Exception(msg);
            }
            DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs);
            deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
            Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), true, true, ideUnitNumber++, i + 1);
            deviceConfigSpecArray[i].setDevice(isoInfo.first());
            if (isoInfo.second()) {
                if (s_logger.isDebugEnabled())
                    s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
                deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
            } else {
                if (s_logger.isDebugEnabled())
                    s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
                deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
            }
        } else {
            // Note: we will always plug a CDROM device
            if (volIso != null) {
                TemplateObjectTO iso = (TemplateObjectTO) volIso.getData();
                if (iso.getPath() != null && !iso.getPath().isEmpty()) {
                    DataStoreTO imageStore = iso.getDataStore();
                    if (!(imageStore instanceof NfsTO)) {
                        s_logger.debug("unsupported protocol");
                        throw new Exception("unsupported protocol");
                    }
                    NfsTO nfsImageStore = (NfsTO) imageStore;
                    String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath();
                    Pair<String, ManagedObjectReference> isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, isoPath);
                    assert (isoDatastoreInfo != null);
                    assert (isoDatastoreInfo.second() != null);
                    deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
                    Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, ideUnitNumber++, i + 1);
                    deviceConfigSpecArray[i].setDevice(isoInfo.first());
                    if (isoInfo.second()) {
                        if (s_logger.isDebugEnabled())
                            s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
                        deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
                    } else {
                        if (s_logger.isDebugEnabled())
                            s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
                        deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
                    }
                }
            } else {
                deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
                Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, ideUnitNumber++, i + 1);
                deviceConfigSpecArray[i].setDevice(isoInfo.first());
                if (isoInfo.second()) {
                    if (s_logger.isDebugEnabled())
                        s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
                    deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
                } else {
                    if (s_logger.isDebugEnabled())
                        s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
                    deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
                }
            }
        }
        i++;
        //
        // Setup ROOT/DATA disk devices
        //
        DiskTO[] sortedDisks = sortVolumesByDeviceId(disks);
        for (DiskTO vol : sortedDisks) {
            if (vol.getType() == Volume.Type.ISO)
                continue;
            VirtualMachineDiskInfo matchingExistingDisk = getMatchingExistingDisk(diskInfoBuilder, vol, hyperHost, context);
            controllerKey = getDiskController(matchingExistingDisk, vol, vmSpec, ideControllerKey, scsiControllerKey);
            String diskController = getDiskController(vmMo, matchingExistingDisk, vol, new Pair<String, String>(rootDiskController, dataDiskController));
            if (DiskControllerType.getType(diskController) == DiskControllerType.osdefault) {
                diskController = vmMo.getRecommendedDiskController(null);
            }
            if (DiskControllerType.getType(diskController) == DiskControllerType.ide) {
                controllerKey = vmMo.getIDEControllerKey(ideUnitNumber);
                if (vol.getType() == Volume.Type.DATADISK) {
                    // Ensure maximum of 2 data volumes over IDE controller, 3 includeing root volume
                    if (vmMo.getNumberOfVirtualDisks() > 3) {
                        throw new CloudRuntimeException("Found more than 3 virtual disks attached to this VM [" + vmMo.getVmName() + "]. Unable to implement the disks over " + diskController + " controller, as maximum number of devices supported over IDE controller is 4 includeing CDROM device.");
                    }
                }
            } else {
                controllerKey = vmMo.getScsiDiskControllerKeyNoException(diskController);
                if (controllerKey == -1) {
                    // This may happen for ROOT legacy VMs which doesn't have recommended disk controller when global configuration parameter 'vmware.root.disk.controller' is set to "osdefault"
                    // Retrieve existing controller and use.
                    Ternary<Integer, Integer, DiskControllerType> vmScsiControllerInfo = vmMo.getScsiControllerInfo();
                    DiskControllerType existingControllerType = vmScsiControllerInfo.third();
                    controllerKey = vmMo.getScsiDiskControllerKeyNoException(existingControllerType.toString());
                }
            }
            if (!hasSnapshot) {
                deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
                VolumeObjectTO volumeTO = (VolumeObjectTO) vol.getData();
                DataStoreTO primaryStore = volumeTO.getDataStore();
                Map<String, String> details = vol.getDetails();
                boolean managed = false;
                String iScsiName = null;
                if (details != null) {
                    managed = Boolean.parseBoolean(details.get(DiskTO.MANAGED));
                    iScsiName = details.get(DiskTO.IQN);
                }
                // if the storage is managed, iScsiName should not be null
                String datastoreName = managed ? VmwareResource.getDatastoreName(iScsiName) : primaryStore.getUuid();
                Pair<ManagedObjectReference, DatastoreMO> volumeDsDetails = dataStoresDetails.get(datastoreName);
                assert (volumeDsDetails != null);
                String[] diskChain = syncDiskChain(dcMo, vmMo, vmSpec, vol, matchingExistingDisk, dataStoresDetails);
                if (controllerKey == scsiControllerKey && VmwareHelper.isReservedScsiDeviceNumber(scsiUnitNumber))
                    scsiUnitNumber++;
                VirtualDevice device = VmwareHelper.prepareDiskDevice(vmMo, null, controllerKey, diskChain, volumeDsDetails.first(), (controllerKey == vmMo.getIDEControllerKey(ideUnitNumber)) ? ((ideUnitNumber++) % VmwareHelper.MAX_IDE_CONTROLLER_COUNT) : scsiUnitNumber++, i + 1);
                if (vol.getType() == Volume.Type.ROOT)
                    rootDiskTO = vol;
                deviceConfigSpecArray[i].setDevice(device);
                deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
                if (s_logger.isDebugEnabled())
                    s_logger.debug("Prepare volume at new device " + _gson.toJson(device));
                i++;
            } else {
                if (controllerKey == scsiControllerKey && VmwareHelper.isReservedScsiDeviceNumber(scsiUnitNumber))
                    scsiUnitNumber++;
                if (controllerKey == vmMo.getIDEControllerKey(ideUnitNumber))
                    ideUnitNumber++;
                else
                    scsiUnitNumber++;
            }
        }
        //
        if (guestOsId.startsWith("darwin")) {
            //Mac OS
            VirtualDevice[] devices = vmMo.getMatchedDevices(new Class<?>[] { VirtualUSBController.class });
            if (devices.length == 0) {
                s_logger.debug("No USB Controller device on VM Start. Add USB Controller device for Mac OS VM " + vmInternalCSName);
                //For Mac OS X systems, the EHCI+UHCI controller is enabled by default and is required for USB mouse and keyboard access.
                VirtualDevice usbControllerDevice = VmwareHelper.prepareUSBControllerDevice();
                deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
                deviceConfigSpecArray[i].setDevice(usbControllerDevice);
                deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
                if (s_logger.isDebugEnabled())
                    s_logger.debug("Prepare USB controller at new device " + _gson.toJson(deviceConfigSpecArray[i]));
                i++;
            } else {
                s_logger.debug("USB Controller device exists on VM Start for Mac OS VM " + vmInternalCSName);
            }
        }
        //
        // Setup NIC devices
        //
        VirtualDevice nic;
        int nicMask = 0;
        int nicCount = 0;
        VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.valueOf(vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER));
        if (s_logger.isDebugEnabled())
            s_logger.debug("VM " + vmInternalCSName + " will be started with NIC device type: " + nicDeviceType);
        NiciraNvpApiVersion.logNiciraApiVersion();
        Map<String, String> nicUuidToDvSwitchUuid = new HashMap<String, String>();
        for (NicTO nicTo : sortNicsByDeviceId(nics)) {
            s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo));
            boolean configureVServiceInNexus = (nicTo.getType() == TrafficType.Guest) && (vmSpec.getDetails().containsKey("ConfigureVServiceInNexus"));
            VirtualMachine.Type vmType = cmd.getVirtualMachine().getType();
            Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, configureVServiceInNexus, vmType);
            if ((nicTo.getBroadcastType() != BroadcastDomainType.Lswitch) || (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch && NiciraNvpApiVersion.isApiVersionLowerThan("4.2"))) {
                if (VmwareHelper.isDvPortGroup(networkInfo.first())) {
                    String dvSwitchUuid;
                    ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
                    DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);
                    ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first());
                    dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor);
                    s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid);
                    nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), nicUnitNumber++, i + 1, true, true);
                    if (nicTo.getUuid() != null) {
                        nicUuidToDvSwitchUuid.put(nicTo.getUuid(), dvSwitchUuid);
                    }
                } else {
                    s_logger.info("Preparing NIC device on network " + networkInfo.second());
                    nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), nicUnitNumber++, i + 1, true, true);
                }
            } else {
                //if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
                nic = VmwareHelper.prepareNicOpaque(vmMo, nicDeviceType, networkInfo.second(), nicTo.getMac(), nicUnitNumber++, i + 1, true, true);
            }
            deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
            deviceConfigSpecArray[i].setDevice(nic);
            deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
            if (s_logger.isDebugEnabled())
                s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i]));
            // this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3
            if (nicCount < 3)
                nicMask |= (1 << nicCount);
            i++;
            nicCount++;
        }
        for (int j = 0; j < i; j++) vmConfigSpec.getDeviceChange().add(deviceConfigSpecArray[j]);
        //
        // Setup VM options
        //
        // pass boot arguments through machine.id & perform customized options to VMX
        ArrayList<OptionValue> extraOptions = new ArrayList<OptionValue>();
        configBasicExtraOption(extraOptions, vmSpec);
        configNvpExtraOption(extraOptions, vmSpec, nicUuidToDvSwitchUuid);
        configCustomExtraOption(extraOptions, vmSpec);
        // config VNC
        String keyboardLayout = null;
        if (vmSpec.getDetails() != null)
            keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD);
        vmConfigSpec.getExtraConfig().addAll(Arrays.asList(configureVnc(extraOptions.toArray(new OptionValue[0]), hyperHost, vmInternalCSName, vmSpec.getVncPassword(), keyboardLayout)));
        // config video card
        configureVideoCard(vmMo, vmSpec, vmConfigSpec);
        //
        if (!vmMo.configureVm(vmConfigSpec)) {
            throw new Exception("Failed to configure VM before start. vmName: " + vmInternalCSName);
        }
        if (vmSpec.getType() == VirtualMachine.Type.DomainRouter) {
            hyperHost.setRestartPriorityForVM(vmMo, DasVmPriority.HIGH.value());
        }
        //For resizing root disk.
        if (rootDiskTO != null && !hasSnapshot) {
            resizeRootDisk(vmMo, rootDiskTO, hyperHost, context);
        }
        //
        // Post Configuration
        //
        vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask));
        postNvpConfigBeforeStart(vmMo, vmSpec);
        Map<String, String> iqnToPath = new HashMap<String, String>();
        postDiskConfigBeforeStart(vmMo, vmSpec, sortedDisks, ideControllerKey, scsiControllerKey, iqnToPath, hyperHost, context);
        //
        if (!vmMo.powerOn()) {
            throw new Exception("Failed to start VM. vmName: " + vmInternalCSName + " with hostname " + vmNameOnVcenter);
        }
        StartAnswer startAnswer = new StartAnswer(cmd);
        startAnswer.setIqnToPath(iqnToPath);
        // Since VM was successfully powered-on, if there was an existing VM in a different cluster that was unregistered, delete all the files associated with it.
        if (existingVmName != null && existingVmFileLayout != null) {
            deleteUnregisteredVmFiles(existingVmFileLayout, dcMo, true);
        }
        return startAnswer;
    } catch (Throwable e) {
        if (e instanceof RemoteException) {
            s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
            invalidateServiceContext();
        }
        String msg = "StartCommand failed due to " + VmwareHelper.getExceptionMessage(e);
        s_logger.warn(msg, e);
        StartAnswer startAnswer = new StartAnswer(cmd, msg);
        if (vmAlreadyExistsInVcenter) {
            startAnswer.setContextParam("stopRetry", "true");
        }
        // Since VM start failed, if there was an existing VM in a different cluster that was unregistered, register it back.
        if (existingVmName != null && existingVmFileInfo != null) {
            s_logger.debug("Since VM start failed, registering back an existing VM: " + existingVmName + " that was unregistered");
            try {
                DatastoreFile fileInDatastore = new DatastoreFile(existingVmFileInfo.getVmPathName());
                DatastoreMO existingVmDsMo = new DatastoreMO(dcMo.getContext(), dcMo.findDatastore(fileInDatastore.getDatastoreName()));
                registerVm(existingVmName, existingVmDsMo);
            } catch (Exception ex) {
                String message = "Failed to register an existing VM: " + existingVmName + " due to " + VmwareHelper.getExceptionMessage(ex);
                s_logger.warn(message, ex);
            }
        }
        return startAnswer;
    } finally {
    }
}
Also used : StartAnswer(com.cloud.agent.api.StartAnswer) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) DatastoreFile(com.cloud.hypervisor.vmware.mo.DatastoreFile) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) VirtualMachineFileLayoutEx(com.vmware.vim25.VirtualMachineFileLayoutEx) NicTO(com.cloud.agent.api.to.NicTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) VmwareManager(com.cloud.hypervisor.vmware.manager.VmwareManager) VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VirtualDevice(com.vmware.vim25.VirtualDevice) VirtualMachineDiskInfoBuilder(com.cloud.hypervisor.vmware.mo.VirtualMachineDiskInfoBuilder) NfsTO(com.cloud.agent.api.to.NfsTO) DatastoreMO(com.cloud.hypervisor.vmware.mo.DatastoreMO) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) DatacenterMO(com.cloud.hypervisor.vmware.mo.DatacenterMO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) VirtualMachine(com.cloud.vm.VirtualMachine) VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) DiskControllerType(com.cloud.hypervisor.vmware.mo.DiskControllerType) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) OptionValue(com.vmware.vim25.OptionValue) VirtualEthernetCard(com.vmware.vim25.VirtualEthernetCard) Pair(com.cloud.utils.Pair) VirtualEthernetCardType(com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) VirtualDisk(com.vmware.vim25.VirtualDisk) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) RemoteException(java.rmi.RemoteException) VirtualMachineFileInfo(com.vmware.vim25.VirtualMachineFileInfo) DiskTO(com.cloud.agent.api.to.DiskTO)

Aggregations

DatastoreFile (com.cloud.hypervisor.vmware.mo.DatastoreFile)8 DatastoreMO (com.cloud.hypervisor.vmware.mo.DatastoreMO)6 VolumeObjectTO (org.apache.cloudstack.storage.to.VolumeObjectTO)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)4 ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 RemoteException (java.rmi.RemoteException)4 DataStoreTO (com.cloud.agent.api.to.DataStoreTO)3 CloudException (com.cloud.exception.CloudException)3 InternalErrorException (com.cloud.exception.InternalErrorException)3 IOException (java.io.IOException)3 ConnectException (java.net.ConnectException)3 PrimaryDataStoreTO (org.apache.cloudstack.storage.to.PrimaryDataStoreTO)3 VirtualMachineDiskInfo (org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo)3 DiskTO (com.cloud.agent.api.to.DiskTO)2 NfsTO (com.cloud.agent.api.to.NfsTO)2 VirtualMachineDiskInfoBuilder (com.cloud.hypervisor.vmware.mo.VirtualMachineDiskInfoBuilder)2 VirtualMachineMO (com.cloud.hypervisor.vmware.mo.VirtualMachineMO)2 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)2 VmwareContext (com.cloud.hypervisor.vmware.util.VmwareContext)2