Java Code Examples for com.vmware.vim25.VirtualDeviceConfigSpec#setDevice()

The following examples show how to use com.vmware.vim25.VirtualDeviceConfigSpec#setDevice() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkManager.java    From development with Apache License 2.0 6 votes vote down vote up
private static void replaceNetworkAdapter(
        VirtualMachineConfigSpec vmConfigSpec, VirtualDevice oldNIC,
        ManagedObjectReference newNetworkRef, String newNetworkName)
        throws Exception {
    logger.debug("new network: " + newNetworkName);
    VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();
    nicBacking.setDeviceName(newNetworkName);
    nicBacking.setNetwork(newNetworkRef);
    nicBacking.setUseAutoDetect(true);
    oldNIC.setBacking(nicBacking);

    VirtualDeviceConnectInfo info = new VirtualDeviceConnectInfo();
    info.setConnected(true);
    info.setStartConnected(true);
    info.setAllowGuestControl(true);
    oldNIC.setConnectable(info);
    // oldNIC.getConnectable().setConnected(true);
    // oldNIC.getConnectable().setStartConnected(true);
    VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
    vmDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
    vmDeviceSpec.setDevice(oldNIC);
    vmConfigSpec.getDeviceChange().add(vmDeviceSpec);
}
 
Example 2
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public void ensureLsiLogicDeviceControllers(int count, int availableBusNum) throws Exception {
    int scsiControllerKey = getLsiLogicDeviceControllerKeyNoException();
    if (scsiControllerKey < 0) {
        VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();

        int busNum = availableBusNum;
        while (busNum < count) {
            VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
            scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
            scsiController.setBusNumber(busNum);
            scsiController.setKey(busNum - VmwareHelper.MAX_SCSI_CONTROLLER_COUNT);
            VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
            scsiControllerSpec.setDevice(scsiController);
            scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

            vmConfig.getDeviceChange().add(scsiControllerSpec);
            busNum++;
        }
        if (configureVm(vmConfig)) {
            throw new Exception("Unable to add Lsi Logic controllers to the VM " + getName());
        } else {
            s_logger.info("Successfully added " + count + " LsiLogic Parallel SCSI controllers.");
        }
    }
}
 
Example 3
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public void ensurePvScsiDeviceController(int requiredNumScsiControllers, int availableBusNum) throws Exception {
    VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();

    int busNum = availableBusNum;
    while (busNum < requiredNumScsiControllers) {
        ParaVirtualSCSIController scsiController = new ParaVirtualSCSIController();

        scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
        scsiController.setBusNumber(busNum);
        scsiController.setKey(busNum - VmwareHelper.MAX_SCSI_CONTROLLER_COUNT);
        VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
        scsiControllerSpec.setDevice(scsiController);
        scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

        vmConfig.getDeviceChange().add(scsiControllerSpec);
        busNum++;
    }

    if (configureVm(vmConfig)) {
        throw new Exception("Unable to add Scsi controllers to the VM " + getName());
    } else {
        s_logger.info("Successfully added " + requiredNumScsiControllers + " SCSI controllers.");
    }
}
 
Example 4
Source File: NetworkManager.java    From development with Apache License 2.0 5 votes vote down vote up
private static void connectNIC(VirtualMachineConfigSpec vmConfigSpec,
        VirtualDevice oldNIC, String vmNetworkName) throws Exception {

    logger.debug("networkName: " + vmNetworkName);

    VirtualDeviceConnectInfo info = new VirtualDeviceConnectInfo();
    info.setConnected(true);
    info.setStartConnected(true);
    info.setAllowGuestControl(true);
    oldNIC.setConnectable(info);
    VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
    vmDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
    vmDeviceSpec.setDevice(oldNIC);
    vmConfigSpec.getDeviceChange().add(vmDeviceSpec);
}
 
Example 5
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void plugDevice(VirtualDevice device) throws Exception {
    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
    VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
    deviceConfigSpec.setDevice(device);
    deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

    vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
    if (!configureVm(vmConfigSpec)) {
        throw new Exception("Failed to add devices");
    }
}
 
Example 6
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void ensureBusLogicDeviceControllers(int count, int availableBusNum) throws Exception {
    int scsiControllerKey = getBusLogicDeviceControllerKeyNoException();
    if (scsiControllerKey < 0) {
        VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();

        int busNum = availableBusNum;
        while (busNum < count) {
            VirtualBusLogicController scsiController = new VirtualBusLogicController();

            scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
            scsiController.setBusNumber(busNum);
            scsiController.setKey(busNum - VmwareHelper.MAX_SCSI_CONTROLLER_COUNT);
            VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
            scsiControllerSpec.setDevice(scsiController);
            scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

            vmConfig.getDeviceChange().add(scsiControllerSpec);
            busNum++;
        }

        if (configureVm(vmConfig)) {
            throw new Exception("Unable to add Scsi BusLogic controllers to the VM " + getName());
        } else {
            s_logger.info("Successfully added " + count + " SCSI BusLogic controllers.");
        }
    }
}
 
Example 7
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void attachDisk(Pair<String, ManagedObjectReference>[] vmdkDatastorePathChain, int controllerKey) throws Exception {

        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + new Gson().toJson(vmdkDatastorePathChain));

        synchronized (_mor.getValue().intern()) {
            VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, controllerKey, vmdkDatastorePathChain, -1, 1);
            VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
            VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();

            deviceConfigSpec.setDevice(newDisk);
            deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

            reConfigSpec.getDeviceChange().add(deviceConfigSpec);

            ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
            boolean result = _context.getVimClient().waitForTask(morTask);

            if (!result) {
                if (s_logger.isTraceEnabled())
                    s_logger.trace("vCenter API trace - attachDisk() done(failed)");
                throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
            }

            _context.waitForTaskProgressDone(morTask);
        }

        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
    }
 
Example 8
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void attachDisk(String[] vmdkDatastorePathChain, ManagedObjectReference morDs) throws Exception {

        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + new Gson().toJson(vmdkDatastorePathChain) +
                    ", datastore: " + morDs.getValue());

        synchronized (_mor.getValue().intern()) {
            VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, null, getScsiDeviceControllerKey(), vmdkDatastorePathChain, morDs, -1, 1);
            VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
            VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();

            deviceConfigSpec.setDevice(newDisk);
            deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

            reConfigSpec.getDeviceChange().add(deviceConfigSpec);

            ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
            boolean result = _context.getVimClient().waitForTask(morTask);

            if (!result) {
                if (s_logger.isTraceEnabled())
                    s_logger.trace("vCenter API trace - attachDisk() done(failed)");
                throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
            }

            _context.waitForTaskProgressDone(morTask);
        }

        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
    }
 
Example 9
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public boolean configureVm(Ternary<VirtualDevice, VirtualDeviceConfigSpecOperation, VirtualDeviceConfigSpecFileOperation>[] devices) throws Exception {

        assert (devices != null);

        VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[devices.length];
        int i = 0;
        for (Ternary<VirtualDevice, VirtualDeviceConfigSpecOperation, VirtualDeviceConfigSpecFileOperation> deviceTernary : devices) {
            VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
            deviceConfigSpec.setDevice(deviceTernary.first());
            deviceConfigSpec.setOperation(deviceTernary.second());
            deviceConfigSpec.setFileOperation(deviceTernary.third());
            deviceConfigSpecArray[i++] = deviceConfigSpec;
        }
        configSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray));

        ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, configSpec);

        boolean result = _context.getVimClient().waitForTask(morTask);
        if (result) {
            _context.waitForTaskProgressDone(morTask);
            return true;
        } else {
            s_logger.error("VMware reconfigVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask));
        }
        return false;
    }
 
Example 10
Source File: VmUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private VirtualDeviceConfigSpec getNicOpSpec(VirtualDeviceConfigSpec nicSpecs, VirtualDeviceConfigSpecOperation operation,
                                             VirtualEthernetCard nic) {
    nicSpecs.setOperation(operation);
    nicSpecs.setDevice(nic);

    return nicSpecs;
}
 
Example 11
Source File: VmUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private VirtualDeviceConfigSpec getCDSpec(VirtualDeviceConfigSpec cdSpecs, VirtualDeviceConfigSpecOperation operation,
                                          VirtualCdrom cdRom) {
    cdSpecs.setOperation(operation);
    cdSpecs.setDevice(cdRom);

    return cdSpecs;
}
 
Example 12
Source File: DiskManager.java    From development with Apache License 2.0 5 votes vote down vote up
private void configureSystemDisk(VirtualMachineConfigSpec vmConfigSpec,
        long systemDiskMB, VirtualDisk vdSystemDisk) throws Exception {
    if (systemDiskMB > 0) {
        long newDiskSpace = systemDiskMB * 1024;
        if (newDiskSpace < vdSystemDisk.getCapacityInKB()) {
            logger.error("Cannot reduce size of system disk \""
                    + vdSystemDisk.getDeviceInfo().getLabel() + "\"");
            logger.error("Current disk size: "
                    + vdSystemDisk.getCapacityInKB() + " new disk space: "
                    + newDiskSpace);

            throw new Exception(Messages
                    .getAll("error_invalid_diskspacereduction").get(0)
                    .getText());
        } else if (newDiskSpace > vdSystemDisk.getCapacityInKB()) {
            logger.info("reconfigureDisks() extend system disk space to "
                    + newDiskSpace + " ("
                    + vdSystemDisk.getDeviceInfo().getLabel() + ")");
            vdSystemDisk.setCapacityInKB(newDiskSpace);
            VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
            vmDeviceSpec
                    .setOperation(VirtualDeviceConfigSpecOperation.EDIT);
            vmDeviceSpec.setDevice(vdSystemDisk);
            vmConfigSpec.getDeviceChange().add(vmDeviceSpec);
        } else {
            logger.debug("System disk size has not been changed. "
                    + newDiskSpace + " KB");
        }
    } else {
        logger.error("Reconfiguration of system disk not possible because system disk size is not defined.");
    }
}
 
Example 13
Source File: DiskManager.java    From development with Apache License 2.0 5 votes vote down vote up
private VirtualDeviceConfigSpec createNewDataDisk(VirtualDisk vdSystemDisk,
        long newDiskSpace, int deviceKey, int unitNumber) throws Exception {

    logger.info("reconfigureDisks() create data disk space with "
            + newDiskSpace + " KB");

    ManagedObjectReference vmDatastore = ((VirtualDeviceFileBackingInfo) vdSystemDisk
            .getBacking()).getDatastore();
    String vmDatastoreName = (String) vmw.getServiceUtil()
            .getDynamicProperty(vmDatastore, "summary.name");

    VirtualDisk vdDataDisk = new VirtualDisk();
    VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo();
    diskfileBacking.setFileName("[" + vmDatastoreName + "]");
    diskfileBacking.setDiskMode("persistent");

    vdDataDisk.setKey(deviceKey);
    vdDataDisk.setControllerKey(vdSystemDisk.getControllerKey());
    vdDataDisk.setUnitNumber(new Integer(unitNumber));
    vdDataDisk.setBacking(diskfileBacking);
    vdDataDisk.setCapacityInKB(newDiskSpace);

    VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
    vmDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
    vmDeviceSpec
            .setFileOperation(VirtualDeviceConfigSpecFileOperation.CREATE);
    vmDeviceSpec.setDevice(vdDataDisk);

    return vmDeviceSpec;
}
 
Example 14
Source File: DiskManager.java    From development with Apache License 2.0 5 votes vote down vote up
private void updateDiskConfiguration(VirtualMachineConfigSpec vmConfigSpec,
        List<VirtualDevice> devices, int vdKey, long newDiskSpace)
        throws Exception {
    VirtualDisk vdDataDisk = findDataDisk(devices, vdKey);
    if (vdDataDisk != null && newDiskSpace > vdDataDisk.getCapacityInKB()) {

        logger.info("reconfigureDisks() extend data disk #" + vdKey
                + " space to " + newDiskSpace + " ("
                + vdDataDisk.getDeviceInfo().getLabel() + ")");

        if (newDiskSpace < vdDataDisk.getCapacityInKB()) {
            logger.error("Cannot reduce size of data disk "
                    + vdDataDisk.getDeviceInfo().getLabel());
            logger.error("Current disk space: "
                    + vdDataDisk.getCapacityInKB() + " new disk space: "
                    + newDiskSpace);
            throw new Exception(Messages
                    .getAll("error_invalid_diskspacereduction").get(0)
                    .getText());
        } else if (newDiskSpace > vdDataDisk.getCapacityInKB()) {
            vdDataDisk.setCapacityInKB(newDiskSpace);
            VirtualDeviceConfigSpec vmDeviceSpec = new VirtualDeviceConfigSpec();
            vmDeviceSpec
                    .setOperation(VirtualDeviceConfigSpecOperation.EDIT);
            vmDeviceSpec.setDevice(vdDataDisk);

            vmConfigSpec.getDeviceChange().add(vmDeviceSpec);
        } else {
            logger.debug("Data disk size has not been changed. "
                    + newDiskSpace + " KB");
        }
    }
}
 
Example 15
Source File: HypervisorHostHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static boolean createBlankVm(VmwareHypervisorHost host, String vmName, String vmInternalCSName, int cpuCount, int cpuSpeedMHz, int cpuReservedMHz,
                                    boolean limitCpuUse, int memoryMB, int memoryReserveMB, String guestOsIdentifier, ManagedObjectReference morDs, boolean snapshotDirToParent,
                                    Pair<String, String> controllerInfo, Boolean systemVm) throws Exception {

    if (s_logger.isInfoEnabled())
        s_logger.info("Create blank VM. cpuCount: " + cpuCount + ", cpuSpeed(MHz): " + cpuSpeedMHz + ", mem(Mb): " + memoryMB);

    VirtualDeviceConfigSpec controllerSpec = null;
    // VM config basics
    VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();
    vmConfig.setName(vmName);
    if (vmInternalCSName == null)
        vmInternalCSName = vmName;

    VmwareHelper.setBasicVmConfig(vmConfig, cpuCount, cpuSpeedMHz, cpuReservedMHz, memoryMB, memoryReserveMB, guestOsIdentifier, limitCpuUse);

    String recommendedController = host.getRecommendedDiskController(guestOsIdentifier);
    String newRootDiskController = controllerInfo.first();
    String newDataDiskController = controllerInfo.second();
    if (DiskControllerType.getType(controllerInfo.first()) == DiskControllerType.osdefault) {
        newRootDiskController = recommendedController;
    }
    if (DiskControllerType.getType(controllerInfo.second()) == DiskControllerType.osdefault) {
        newDataDiskController = recommendedController;
    }

    Pair<String, String> updatedControllerInfo = new Pair<String, String>(newRootDiskController, newDataDiskController);
    String scsiDiskController = HypervisorHostHelper.getScsiController(updatedControllerInfo, recommendedController);
    // If there is requirement for a SCSI controller, ensure to create those.
    if (scsiDiskController != null) {
    int busNum = 0;
        int maxControllerCount = VmwareHelper.MAX_SCSI_CONTROLLER_COUNT;
        if (systemVm) {
            maxControllerCount = 1;
        }
        while (busNum < maxControllerCount) {
        VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
            scsiControllerSpec = getControllerSpec(DiskControllerType.getType(scsiDiskController).toString(), busNum);

        vmConfig.getDeviceChange().add(scsiControllerSpec);
        busNum++;
        }
    }

    if (guestOsIdentifier.startsWith("darwin")) { //Mac OS
        s_logger.debug("Add USB Controller device for blank Mac OS VM " + vmName);

        //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();
        VirtualDeviceConfigSpec usbControllerSpec = new VirtualDeviceConfigSpec();
        usbControllerSpec.setDevice(usbControllerDevice);
        usbControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

        vmConfig.getDeviceChange().add(usbControllerSpec);
    }

    VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
    DatastoreMO dsMo = new DatastoreMO(host.getContext(), morDs);
    fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
    vmConfig.setFiles(fileInfo);

    VirtualMachineVideoCard videoCard = new VirtualMachineVideoCard();
    videoCard.setControllerKey(100);
    videoCard.setUseAutoDetect(true);

    VirtualDeviceConfigSpec videoDeviceSpec = new VirtualDeviceConfigSpec();
    videoDeviceSpec.setDevice(videoCard);
    videoDeviceSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

    vmConfig.getDeviceChange().add(videoDeviceSpec);

    if (host.createVm(vmConfig)) {
        // Here, when attempting to find the VM, we need to use the name
        // with which we created it. This is the only such place where
        // we need to do this. At all other places, we always use the
        // VM's internal cloudstack generated name. Here, we cannot use
        // the internal name because we can set the internal name into the
        // VM's custom field CLOUD_VM_INTERNAL_NAME only after we create
        // the VM.
        VirtualMachineMO vmMo = host.findVmOnHyperHost(vmName);
        assert (vmMo != null);

        vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_VM_INTERNAL_NAME, vmInternalCSName);

        int ideControllerKey = -1;
        while (ideControllerKey < 0) {
            ideControllerKey = vmMo.tryGetIDEDeviceControllerKey();
            if (ideControllerKey >= 0)
                break;

            s_logger.info("Waiting for IDE controller be ready in VM: " + vmInternalCSName);
            Thread.sleep(1000);
        }

        return true;
    }
    return false;
}
 
Example 16
Source File: SiocManagerImpl.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private ResultWrapper updateSiocInfoForWorkerVM(VMwareUtil.VMwareConnection connection, ManagedObjectReference morVm, String datastoreName,
                                                int limitIopsPerGB) throws Exception {
    int limitIopsTotal = 0;
    List<ManagedObjectReference> tasks = new ArrayList<>();

    VirtualMachineConfigInfo vmci = (VirtualMachineConfigInfo)VMwareUtil.getEntityProps(connection, morVm,
            new String[] { "config" }).get("config");
    List<VirtualDevice> devices = vmci.getHardware().getDevice();

    for (VirtualDevice device : devices) {
        if (device instanceof VirtualDisk) {
            VirtualDisk disk = (VirtualDisk)device;

            if (disk.getBacking() instanceof VirtualDeviceFileBackingInfo) {
                VirtualDeviceFileBackingInfo backingInfo = (VirtualDeviceFileBackingInfo)disk.getBacking();

                if (backingInfo.getFileName().contains(datastoreName)) {
                    boolean diskUpdated = false;

                    StorageIOAllocationInfo sioai = disk.getStorageIOAllocation();

                    long currentLimitIops = sioai.getLimit() !=  null ? sioai.getLimit() : Long.MIN_VALUE;
                    long newLimitIops = getNewLimitIopsBasedOnVolumeSize(disk.getCapacityInBytes(), limitIopsPerGB);

                    limitIopsTotal += newLimitIops;

                    if (currentLimitIops != newLimitIops) {
                        sioai.setLimit(newLimitIops);

                        diskUpdated = true;
                    }

                    if (diskUpdated) {
                        VirtualDeviceConfigSpec vdcs = new VirtualDeviceConfigSpec();

                        vdcs.setDevice(disk);
                        vdcs.setOperation(VirtualDeviceConfigSpecOperation.EDIT);

                        VirtualMachineConfigSpec vmcs = new VirtualMachineConfigSpec();

                        vmcs.getDeviceChange().add(vdcs);

                        try {
                            ManagedObjectReference task = VMwareUtil.reconfigureVm(connection, morVm, vmcs);

                            tasks.add(task);

                            LOGGER.info(getInfoMsgForWorkerVm(newLimitIops));
                        } catch (Exception ex) {
                            throw new Exception("Error: " + ex.getMessage());
                        }
                    }
                }
            }
        }
    }

    return new ResultWrapper(limitIopsTotal, tasks);
}
 
Example 17
Source File: HypervisorHostHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static void createOvfFile(VmwareHypervisorHost host, String diskFileName, String ovfName, String datastorePath, String templatePath, long diskCapacity, long fileSize,
        ManagedObjectReference morDs) throws Exception {
    VmwareContext context = host.getContext();
    ManagedObjectReference morOvf = context.getServiceContent().getOvfManager();
    VirtualMachineMO workerVmMo = HypervisorHostHelper.createWorkerVM(host, new DatastoreMO(context, morDs), ovfName);
    if (workerVmMo == null)
        throw new Exception("Unable to find just-created worker VM");

    String[] disks = {datastorePath + File.separator + diskFileName};
    try {
        VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();

        // Reconfigure worker VM with datadisk
        VirtualDevice device = VmwareHelper.prepareDiskDevice(workerVmMo, null, -1, disks, morDs, -1, 1);
        deviceConfigSpec.setDevice(device);
        deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
        vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
        workerVmMo.configureVm(vmConfigSpec);

        // Write OVF descriptor file
        OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
        String deviceId = File.separator + workerVmMo.getMor().getValue() + File.separator + "VirtualIDEController0:0";
        OvfFile ovfFile = new OvfFile();
        ovfFile.setPath(diskFileName);
        ovfFile.setDeviceId(deviceId);
        ovfFile.setSize(fileSize);
        ovfFile.setCapacity(diskCapacity);
        ovfDescParams.getOvfFiles().add(ovfFile);
        OvfCreateDescriptorResult ovfCreateDescriptorResult = context.getService().createDescriptor(morOvf, workerVmMo.getMor(), ovfDescParams);

        String ovfPath = templatePath + File.separator + ovfName + ".ovf";
        try {
            FileWriter out = new FileWriter(ovfPath);
            out.write(ovfCreateDescriptorResult.getOvfDescriptor());
            out.close();
        } catch (Exception e) {
            throw e;
        }
    } finally {
        workerVmMo.detachAllDisks();
        workerVmMo.destroy();
    }
}
 
Example 18
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void attachDisk(String[] vmdkDatastorePathChain, ManagedObjectReference morDs, String diskController) throws Exception {

        if(s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - attachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: "
                            + new Gson().toJson(vmdkDatastorePathChain) + ", datastore: " + morDs.getValue());
        int controllerKey = 0;
        int unitNumber = 0;

        if (DiskControllerType.getType(diskController) == DiskControllerType.ide) {
            // IDE virtual disk cannot be added if VM is running
            if (getPowerState() == VirtualMachinePowerState.POWERED_ON) {
                throw new Exception("Adding a virtual disk over IDE controller is not supported while VM is running in VMware hypervisor. Please re-try when VM is not running.");
            }
            // Get next available unit number and controller key
            int ideDeviceCount = getNumberOfIDEDevices();
            if (ideDeviceCount >= VmwareHelper.MAX_IDE_CONTROLLER_COUNT * VmwareHelper.MAX_ALLOWED_DEVICES_IDE_CONTROLLER) {
                throw new Exception("Maximum limit of  devices supported on IDE controllers [" + VmwareHelper.MAX_IDE_CONTROLLER_COUNT
                        * VmwareHelper.MAX_ALLOWED_DEVICES_IDE_CONTROLLER + "] is reached.");
            }
            controllerKey = getIDEControllerKey(ideDeviceCount);
            unitNumber = getFreeUnitNumberOnIDEController(controllerKey);
        } else {
            controllerKey = getScsiDiskControllerKey(diskController);
            unitNumber = -1;
        }
        synchronized (_mor.getValue().intern()) {
            VirtualDevice newDisk = VmwareHelper.prepareDiskDevice(this, null, controllerKey, vmdkDatastorePathChain, morDs, unitNumber, 1);
            controllerKey = newDisk.getControllerKey();
            unitNumber = newDisk.getUnitNumber();
            VirtualDiskFlatVer2BackingInfo backingInfo = (VirtualDiskFlatVer2BackingInfo)newDisk.getBacking();
            String vmdkFileName = backingInfo.getFileName();
            DiskControllerType diskControllerType = DiskControllerType.getType(diskController);
            VmdkAdapterType vmdkAdapterType = VmdkAdapterType.getAdapterType(diskControllerType);
            if (vmdkAdapterType == VmdkAdapterType.none) {
                String message = "Failed to attach disk due to invalid vmdk adapter type for vmdk file [" +
                    vmdkFileName + "] with controller : " + diskControllerType;
                s_logger.debug(message);
                throw new Exception(message);
            }
            updateVmdkAdapter(vmdkFileName, vmdkAdapterType.toString());
            VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
            VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();

            deviceConfigSpec.setDevice(newDisk);
            deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);

            reConfigSpec.getDeviceChange().add(deviceConfigSpec);

            ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
            boolean result = _context.getVimClient().waitForTask(morTask);

            if (!result) {
                if (s_logger.isTraceEnabled())
                    s_logger.trace("vCenter API trace - attachDisk() done(failed)");
                throw new Exception("Failed to attach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
            }

            _context.waitForTaskProgressDone(morTask);
        }

        if(s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - attachDisk() done(successfully)");
    }
 
Example 19
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public List<String> detachAllDisksExcept(String vmdkBaseName, String deviceBusName) throws Exception {
    List<VirtualDevice> devices = _context.getVimClient().getDynamicProperty(_mor, "config.hardware.device");

    VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
    List<String> detachedDiskFiles = new ArrayList<String>();

    for (VirtualDevice device : devices) {
        if (device instanceof VirtualDisk) {
            VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();

            VirtualDiskFlatVer2BackingInfo diskBackingInfo = (VirtualDiskFlatVer2BackingInfo)device.getBacking();

            DatastoreFile dsBackingFile = new DatastoreFile(diskBackingInfo.getFileName());
            String backingBaseName = dsBackingFile.getFileBaseName();
            String deviceNumbering = getDeviceBusName(devices, device);
            if (backingBaseName.equalsIgnoreCase(vmdkBaseName) || (deviceBusName != null && deviceBusName.equals(deviceNumbering))) {
                continue;
            } else {
                s_logger.info("Detach " + diskBackingInfo.getFileName() + " from " + getName());

                detachedDiskFiles.add(diskBackingInfo.getFileName());

                deviceConfigSpec.setDevice(device);
                deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);

                reConfigSpec.getDeviceChange().add(deviceConfigSpec);
            }
        }
    }

    if (detachedDiskFiles.size() > 0) {
        ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
        boolean result = _context.getVimClient().waitForTask(morTask);
        if (result) {
            _context.waitForTaskProgressDone(morTask);
        } else {
            s_logger.warn("Unable to reconfigure the VM to detach disks");
            throw new Exception("Unable to reconfigure the VM to detach disks");
        }
    }

    return detachedDiskFiles;
}
 
Example 20
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public List<Pair<String, ManagedObjectReference>> detachDisk(String vmdkDatastorePath, boolean deleteBackingFile) throws Exception {

        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - detachDisk(). target MOR: " + _mor.getValue() + ", vmdkDatastorePath: " + vmdkDatastorePath + ", deleteBacking: " +
                    deleteBackingFile);

        // Note: if VM has been taken snapshot, original backing file will be renamed, therefore, when we try to find the matching
        // VirtualDisk, we only perform prefix matching
        Pair<VirtualDisk, String> deviceInfo = getDiskDevice(vmdkDatastorePath);
        if (deviceInfo == null) {
            s_logger.warn("vCenter API trace - detachDisk() done (failed)");
            throw new Exception("No such disk device: " + vmdkDatastorePath);
        }

        // IDE virtual disk cannot be detached if VM is running
        if (deviceInfo.second() != null && deviceInfo.second().contains("ide")) {
            if (getPowerState() == VirtualMachinePowerState.POWERED_ON) {
                throw new Exception("Removing a virtual disk over IDE controller is not supported while VM is running in VMware hypervisor. " +
                        "Please re-try when VM is not running.");
            }
        }

        List<Pair<String, ManagedObjectReference>> chain = getDiskDatastorePathChain(deviceInfo.first(), true);

        VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
        VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();

        deviceConfigSpec.setDevice(deviceInfo.first());
        if (deleteBackingFile) {
            deviceConfigSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.DESTROY);
        }
        deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE);

        reConfigSpec.getDeviceChange().add(deviceConfigSpec);

        ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
        boolean result = _context.getVimClient().waitForTask(morTask);

        if (!result) {
            if (s_logger.isTraceEnabled())
                s_logger.trace("vCenter API trace - detachDisk() done (failed)");

            throw new Exception("Failed to detach disk due to " + TaskMO.getTaskFailureInfo(_context, morTask));
        }
        _context.waitForTaskProgressDone(morTask);

        // VMware does not update snapshot references to the detached disk, we have to work around it
        SnapshotDescriptor snapshotDescriptor = null;
        try {
            snapshotDescriptor = getSnapshotDescriptor();
        } catch (Exception e) {
            s_logger.info("Unable to retrieve snapshot descriptor, will skip updating snapshot reference");
        }

        if (snapshotDescriptor != null) {
            for (Pair<String, ManagedObjectReference> pair : chain) {
                DatastoreFile dsFile = new DatastoreFile(pair.first());
                snapshotDescriptor.removeDiskReferenceFromSnapshot(dsFile.getFileName());
            }

            Pair<DatacenterMO, String> dcPair = getOwnerDatacenter();
            String dsPath = getSnapshotDescriptorDatastorePath();
            assert (dsPath != null);
            String url = getContext().composeDatastoreBrowseUrl(dcPair.second(), dsPath);
            getContext().uploadResourceContent(url, snapshotDescriptor.getVmsdContent());
        }

        if (s_logger.isTraceEnabled())
            s_logger.trace("vCenter API trace - detachDisk() done (successfully)");
        return chain;
    }