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); }
/** * Reconfigures VMware system disks and data disks. */ public void reconfigureDisks(VirtualMachineConfigSpec vmConfigSpec, ManagedObjectReference vmwInstance) throws Exception { logger.debug(""); long systemDiskMB = (long) paramHandler.getConfigDiskSpaceMB(); VirtualMachineConfigInfo configSpec = (VirtualMachineConfigInfo) vmw .getServiceUtil().getDynamicProperty(vmwInstance, "config"); List<VirtualDevice> devices = configSpec.getHardware().getDevice(); VirtualDisk vdSystemDisk = getVMSystemDisk(devices, configSpec.getName()); configureSystemDisk(vmConfigSpec, systemDiskMB, vdSystemDisk); configureDataDisks(vmConfigSpec, devices, vdSystemDisk); }
public void detachDiskFromVM() throws Exception { ArrayOfVirtualDevice devices = this.get .entityProp(this.vm, VimPath.vm_config_hardware_device); VirtualDisk vd = (VirtualDisk) findMatchingVirtualDevice(getListOfVirtualDisk(devices)); if (vd == null) { throw new IllegalStateException( String.format( "Matching Virtual Disk is not for disk %s.", this.diskState.documentSelfLink)); } // Detach the disk from VM. VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); deviceConfigSpec.setDevice(vd); VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec(); spec.getDeviceChange().add(deviceConfigSpec); ManagedObjectReference reconfigureTask = getVimPort().reconfigVMTask(this.vm, spec); TaskInfo info = VimUtils.waitTaskEnd(this.connection, reconfigureTask); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } }
VirtualMachineConfigSpec getPopulatedVmConfigSpec(VirtualMachineConfigSpec vmConfigSpec, VmInputs vmInputs, String name) { vmConfigSpec.setName(name); vmConfigSpec.setNumCPUs(vmInputs.getIntNumCPUs()); vmConfigSpec.setMemoryMB(vmInputs.getLongVmMemorySize()); vmConfigSpec.setAnnotation(vmInputs.getDescription()); if (vmInputs.getCoresPerSocket() != null) { vmConfigSpec.setNumCoresPerSocket(InputUtils.getIntInput(vmInputs.getCoresPerSocket(), DEFAULT_CORES_PER_SOCKET)); } if (vmInputs.getGuestOsId() != null) { vmConfigSpec.setGuestId(vmInputs.getGuestOsId()); } return vmConfigSpec; }
/** * Method used to connect to specified data center and create a virtual machine using the inputs provided. * * @param httpInputs Object that has all the inputs necessary to made a connection to data center * @param vmInputs Object that has all the specific inputs necessary to create a new virtual machine * @return Map with String as key and value that contains returnCode of the operation, success message with task id * of the execution or failure message and the exception if there is one * @throws Exception */ public Map<String, String> createVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception { ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs); try { VmUtils utils = new VmUtils(); ManagedObjectReference vmFolderMor = utils.getMorFolder(vmInputs.getFolderName(), connectionResources); ManagedObjectReference resourcePoolMor = utils.getMorResourcePool(vmInputs.getResourcePool(), connectionResources); ManagedObjectReference hostMor = utils.getMorHost(vmInputs.getHostname(), connectionResources, null); VirtualMachineConfigSpec vmConfigSpec = new VmConfigSpecs().getVmConfigSpec(vmInputs, connectionResources); ManagedObjectReference task = connectionResources.getVimPortType() .createVMTask(vmFolderMor, vmConfigSpec, resourcePoolMor, hostMor); return new ResponseHelper(connectionResources, task).getResultsMap("Success: Created [" + vmInputs.getVirtualMachineName() + "] VM. The taskId is: " + task.getValue(), "Failure: Could not create [" + vmInputs.getVirtualMachineName() + "] VM"); } catch (Exception ex) { return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE); } finally { if (httpInputs.isCloseSession()) { connectionResources.getConnection().disconnect(); clearConnectionFromContext(httpInputs.getGlobalSessionObject()); } } }
@Override public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception { assert (vmSpec != null); DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); ManagedObjectReference morTask = _context.getService().createVMTask(dcMo.getVmFolder(), vmSpec, morPool, _mor); boolean result = _context.getVimClient().waitForTask(morTask); if (result) { _context.waitForTaskProgressDone(morTask); return true; } else { s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } return false; }
public void tearDownDevices(Class<?>[] deviceClasses) throws Exception { VirtualDevice[] devices = getMatchedDevices(deviceClasses); if (devices.length > 0) { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[devices.length]; for (int i = 0; i < devices.length; i++) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(devices[i]); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.REMOVE); vmConfigSpec.getDeviceChange().add(deviceConfigSpecArray[i]); } if (!configureVm(vmConfigSpec)) { throw new Exception("Failed to detach devices"); } } }
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."); } }
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."); } } }
public void ensureScsiDeviceController() throws Exception { int scsiControllerKey = getScsiDeviceControllerKeyNoException(); if (scsiControllerKey < 0) { VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); vmConfig.getDeviceChange().add(scsiControllerSpec); if (configureVm(vmConfig)) { throw new Exception("Unable to add Scsi controller"); } } }
public void ensureScsiDeviceControllers(int count, int availableBusNum) throws Exception { int scsiControllerKey = getScsiDeviceControllerKeyNoException(); 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 Scsi controllers to the VM " + getName()); } else { s_logger.info("Successfully added " + count + " SCSI controllers."); } } }
public void ensureLsiLogicSasDeviceControllers(int count, int availableBusNum) throws Exception { int scsiControllerKey = getLsiLogicSasDeviceControllerKeyNoException(); if (scsiControllerKey < 0) { VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); int busNum = availableBusNum; while (busNum < count) { VirtualLsiLogicSASController scsiController = new VirtualLsiLogicSASController(); 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 controller of type LsiLogic SAS."); } } }
@Override public boolean createVm(VirtualMachineConfigSpec vmSpec) throws Exception { if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createVM_Task(). target MOR: " + _mor.getValue() + ", VirtualMachineConfigSpec: " + new Gson().toJson(vmSpec)); assert (vmSpec != null); DatacenterMO dcMo = new DatacenterMO(_context, getHyperHostDatacenter()); ManagedObjectReference morPool = getHyperHostOwnerResourcePool(); ManagedObjectReference morTask = _context.getService().createVMTask(dcMo.getVmFolder(), vmSpec, morPool, null); boolean result = _context.getVimClient().waitForTask(morTask); if (result) { _context.waitForTaskProgressDone(morTask); if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createVM_Task() done(successfully)"); return true; } else { s_logger.error("VMware createVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } if (s_logger.isTraceEnabled()) s_logger.trace("vCenter API trace - createVM_Task() done(failed)"); return false; }
public static void setVmScaleUpConfig(VirtualMachineConfigSpec vmConfig, int cpuCount, int cpuSpeedMHz, int cpuReservedMhz, int memoryMB, int memoryReserveMB, boolean limitCpuUse) { // VM config for scaling up vmConfig.setMemoryMB((long)memoryMB); vmConfig.setNumCPUs(cpuCount); ResourceAllocationInfo cpuInfo = new ResourceAllocationInfo(); if (limitCpuUse) { cpuInfo.setLimit((long)(cpuSpeedMHz * cpuCount)); } else { cpuInfo.setLimit(-1L); } cpuInfo.setReservation((long)cpuReservedMhz); vmConfig.setCpuAllocation(cpuInfo); ResourceAllocationInfo memInfo = new ResourceAllocationInfo(); memInfo.setLimit((long)memoryMB); memInfo.setReservation((long)memoryReserveMB); vmConfig.setMemoryAllocation(memInfo); }
protected void configNestedHVSupport(VirtualMachineMO vmMo, VirtualMachineTO vmSpec, VirtualMachineConfigSpec vmConfigSpec) throws Exception { VmwareContext context = vmMo.getContext(); if ("true".equals(vmSpec.getDetails().get(VmDetailConstants.NESTED_VIRTUALIZATION_FLAG))) { if (s_logger.isDebugEnabled()) s_logger.debug("Nested Virtualization enabled in configuration, checking hypervisor capability"); ManagedObjectReference hostMor = vmMo.getRunningHost().getMor(); ManagedObjectReference computeMor = context.getVimClient().getMoRefProp(hostMor, "parent"); ManagedObjectReference environmentBrowser = context.getVimClient().getMoRefProp(computeMor, "environmentBrowser"); HostCapability hostCapability = context.getService().queryTargetCapabilities(environmentBrowser, hostMor); Boolean nestedHvSupported = hostCapability.isNestedHVSupported(); if (nestedHvSupported == null) { // nestedHvEnabled property is supported only since VMware 5.1. It's not defined for earlier versions. s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName()); } else if (nestedHvSupported.booleanValue()) { s_logger.debug("Hypervisor supports nested virtualization, enabling for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(true); } else { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(false); } } }
/** * Replaces the NICs in the given VM. * * @param vmw * connected VMware client entity * @param paramHandler * entity which holds all properties of the instance * @param vmwInstance * the virtual machine that gets reconfigured */ public static void configureNetworkAdapter(VMwareClient vmw, VirtualMachineConfigSpec vmConfigSpec, VMPropertyHandler paramHandler, ManagedObjectReference vmwInstance) throws Exception { logger.debug(""); VirtualMachineConfigInfo configInfo = (VirtualMachineConfigInfo) vmw .getServiceUtil().getDynamicProperty(vmwInstance, "config"); List<VirtualEthernetCard> vmNics = getNetworkAdapter(configInfo); int numberOfNICs = Integer.parseInt(paramHandler .getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS)); if (numberOfNICs != vmNics.size()) { throw new Exception( "the number of NICs in virtual machine does not match the service parameter. VM: " + configInfo.getName() + " NICs: " + vmNics.size() + " " + VMPropertyHandler.TS_NUMBER_OF_NICS + ": " + numberOfNICs); } for (int i = 1; i <= numberOfNICs; i++) { String newNetworkName = paramHandler.getNetworkAdapter(i); VirtualEthernetCard vmNic = vmNics.get(i - 1); String vmNetworkName = getNetworkName(vmw, vmwInstance, i); if (newNetworkName != null && newNetworkName.length() > 0 && !newNetworkName.equals(vmNetworkName)) { ManagedObjectReference newNetworkRef = getNetworkFromHost(vmw, vmwInstance, newNetworkName); replaceNetworkAdapter(vmConfigSpec, vmNic, newNetworkRef, newNetworkName); } else { connectNIC(vmConfigSpec, vmNic, vmNetworkName); } } }
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); }
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"); } } }
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."); } }
/** * Reconfigures VMware instance. Memory, CPU, disk space and network * adapter. The VM has been created and must be stopped to reconfigure the * hardware. */ public TaskInfo reconfigureVirtualMachine(VMPropertyHandler paramHandler) throws Exception { LOG.debug("instanceName: " + instanceName); VimPortType service = vmw.getConnection().getService(); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec .setMemoryMB(Long.valueOf(paramHandler.getConfigMemoryMB())); vmConfigSpec.setNumCPUs(Integer.valueOf(paramHandler.getConfigCPUs())); String reqUser = paramHandler .getServiceSetting(VMPropertyHandler.REQUESTING_USER); String comment = Messages.get(paramHandler.getLocale(), "vm_comment", new Object[] { paramHandler.getSettings().getOrganizationName(), paramHandler.getSettings().getSubscriptionId(), reqUser }); String annotation = vmConfigSpec.getAnnotation(); comment = updateComment(comment, annotation); vmConfigSpec.setAnnotation(comment); DiskManager diskManager = new DiskManager(vmw, paramHandler); diskManager.reconfigureDisks(vmConfigSpec, vmInstance); NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmInstance); LOG.debug("Call vSphere API: reconfigVMTask()"); ManagedObjectReference reconfigureTask = service .reconfigVMTask(vmInstance, vmConfigSpec); return (TaskInfo) vmw.getServiceUtil() .getDynamicProperty(reconfigureTask, "info"); }
public TaskInfo updateCommentField(String comment) throws Exception { LOG.debug("instanceName: " + instanceName + " comment: " + comment); VimPortType service = vmw.getConnection().getService(); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); String annotation = vmConfigSpec.getAnnotation(); comment = updateComment(comment, annotation); vmConfigSpec.setAnnotation(comment); LOG.debug("Call vSphere API: reconfigVMTask()"); ManagedObjectReference reconfigureTask = service .reconfigVMTask(vmInstance, vmConfigSpec); return (TaskInfo) vmw.getServiceUtil() .getDynamicProperty(reconfigureTask, "info"); }
/** * Reconfigure image disk with the customizations */ private void reconfigureBootDisk(ManagedObjectReference vmMoref, List<VirtualDeviceConfigSpec> deviceConfigSpecs) throws Exception { if (deviceConfigSpecs != null && !deviceConfigSpecs.isEmpty()) { VirtualMachineConfigSpec bootDiskSpec = new VirtualMachineConfigSpec(); bootDiskSpec.getDeviceChange().addAll(deviceConfigSpecs); ManagedObjectReference task = getVimPort().reconfigVMTask(vmMoref, bootDiskSpec); TaskInfo info = waitTaskEnd(task); if (info.getState() == TaskInfoState.ERROR) { VimUtils.rethrow(info.getError()); } } }
/** * Creates a spec used to create the VM. * * @param datastoreName * @return * @throws InvalidPropertyFaultMsg * @throws FinderException * @throws RuntimeFaultFaultMsg */ private VirtualMachineConfigSpec buildVirtualMachineConfigSpec(String datastoreName) throws InvalidPropertyFaultMsg, FinderException, RuntimeFaultFaultMsg { String displayName = this.ctx.child.name; VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec(); spec.setName(displayName); spec.setNumCPUs((int) this.ctx.child.description.cpuCount); spec.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST_64.value()); spec.setMemoryMB(toMemoryMb(this.ctx.child.description.totalMemoryBytes)); VirtualMachineFileInfo files = new VirtualMachineFileInfo(); // Use a full path to the config file to avoid creating a VM with the same name String path = String.format("[%s] %s/%s.vmx", datastoreName, displayName, displayName); files.setVmPathName(path); spec.setFiles(files); for (NetworkInterfaceStateWithDetails ni : this.ctx.nics) { VirtualDevice nic = createNic(ni, null); addDeviceToVm(spec, nic); } VirtualDevice scsi = createScsiController(); addDeviceToVm(spec, scsi); return spec; }
public void createHardDisk(int diskSizeMB, VirtualDiskType type, VirtualDiskMode mode) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.setFileName(""); diskfileBacking.setDiskMode(mode.toString()); diskfileBacking.setThinProvisioned(type==VirtualDiskType.thin); VirtualSCSIController scsiController = getFirstAvailableController(VirtualSCSIController.class); int unitNumber = getFirstFreeUnitNumberForController(scsiController); VirtualDisk disk = new VirtualDisk(); disk.setControllerKey(scsiController.key); disk.setUnitNumber(unitNumber); disk.setBacking(diskfileBacking); disk.setCapacityInKB(1024 * diskSizeMB); disk.setKey(-1); diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add); diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create); diskSpec.setDevice(disk); VirtualDeviceConfigSpec vdiskSpec = diskSpec; VirtualDeviceConfigSpec [] vdiskSpecArray = {vdiskSpec}; vmConfigSpec.setDeviceChange(vdiskSpecArray); Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100); }
public void addHardDisk(String diskFilePath, VirtualDiskMode diskMode) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualDeviceConfigSpec[] vdiskSpecArray = {diskSpec}; vmConfigSpec.setDeviceChange(vdiskSpecArray); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.setFileName(diskFilePath); diskfileBacking.setDiskMode(diskMode.toString()); VirtualSCSIController scsiController = getFirstAvailableController(VirtualSCSIController.class); int unitNumber = getFirstFreeUnitNumberForController(scsiController); VirtualDisk disk = new VirtualDisk(); disk.setControllerKey(scsiController.key); disk.setUnitNumber(unitNumber); disk.setBacking(diskfileBacking); //Unlike required by API ref, the capacityKB is optional. So skip setCapacityInKB() method. disk.setKey(-100); diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add); diskSpec.setDevice(disk); Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100); }
/** Create a new virtual network adapter on the VM * Your MAC address should start with 00:50:56 */ public void createNetworkAdapter(VirtualNetworkAdapterType type, String networkName, String macAddress, boolean wakeOnLan, boolean startConnected) throws InvalidProperty, RuntimeFault, RemoteException, InterruptedException { VirtualMachinePowerState powerState = vm.getRuntime().getPowerState(); String vmVerStr = vm.getConfig().getVersion(); int vmVer = Integer.parseInt(vmVerStr.substring(vmVerStr.length()-2)); if((powerState == VirtualMachinePowerState.suspended) || (powerState == VirtualMachinePowerState.suspended && vmVer < 7)) { throw new InvalidPowerState(); } HostSystem host = new HostSystem(vm.getServerConnection(), vm.getRuntime().getHost()); ComputeResource cr = (ComputeResource) host.getParent(); EnvironmentBrowser envBrowser = cr.getEnvironmentBrowser(); ConfigTarget configTarget = envBrowser.queryConfigTarget(host); VirtualMachineConfigOption vmCfgOpt = envBrowser.queryConfigOption(null, host); type = validateNicType(vmCfgOpt.getGuestOSDescriptor(), vm.getConfig().getGuestId(), type); VirtualDeviceConfigSpec nicSpec = createNicSpec(type, networkName, macAddress, wakeOnLan, startConnected, configTarget); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); vmConfigSpec.setDeviceChange(new VirtualDeviceConfigSpec []{nicSpec}); Task task = vm.reconfigVM_Task(vmConfigSpec); task.waitForTask(200, 100); }
public VirtualMachineConfigSpec getUpdateConfigSpec(VmInputs vmInputs, VirtualMachineConfigSpec vmConfigSpec, String device) throws Exception { if (!InputUtils.isUpdateOperation(vmInputs)) { throw new RuntimeException(ErrorMessages.CPU_OR_MEMORY_INVALID_OPERATION); } VmConfigSpecs specs = new VmConfigSpecs(); ResourceAllocationInfo resourceAllocationInfo = specs.getResourceAllocationInfo(vmInputs.getUpdateValue()); if (Constants.CPU.equalsIgnoreCase(device)) { vmConfigSpec.setCpuAllocation(resourceAllocationInfo); } else { vmConfigSpec.setMemoryAllocation(resourceAllocationInfo); } return vmConfigSpec; }
public VirtualMachineConfigSpec getAddOrRemoveSpecs(ConnectionResources connectionResources, ManagedObjectReference vmMor, VmInputs vmInputs, VirtualMachineConfigSpec vmConfigSpec, String device) throws Exception { VmConfigSpecs vmConfigSpecs = new VmConfigSpecs(); VirtualDeviceConfigSpec deviceConfigSpec; switch (device) { case DISK: InputUtils.checkValidOperation(vmInputs, device); InputUtils.validateDiskInputs(vmInputs); deviceConfigSpec = vmConfigSpecs.getDiskDeviceConfigSpec(connectionResources, vmMor, vmInputs); break; case CD: InputUtils.checkValidOperation(vmInputs, device); deviceConfigSpec = vmConfigSpecs.getCDDeviceConfigSpec(connectionResources, vmMor, vmInputs); break; case NIC: InputUtils.checkValidOperation(vmInputs, device); deviceConfigSpec = vmConfigSpecs.getNICDeviceConfigSpec(connectionResources, vmMor, vmInputs); break; default: throw new RuntimeException("Invalid operation specified for " + device + " device. " + "The " + device + " device can be only added or removed."); } List<VirtualDeviceConfigSpec> specs = new ArrayList<>(); specs.add(deviceConfigSpec); vmConfigSpec.getDeviceChange().addAll(specs); return vmConfigSpec; }
/** * Method used to connect to data center to update existing devices of a virtual machine identified by the inputs * provided. * * @param httpInputs Object that has all the inputs necessary to made a connection to data center * @param vmInputs Object that has all the specific inputs necessary to identify the targeted device * @return Map with String as key and value that contains returnCode of the operation, success message with task id * of the execution or failure message and the exception if there is one * @throws Exception */ public Map<String, String> updateVM(HttpInputs httpInputs, VmInputs vmInputs) throws Exception { ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs); try { ManagedObjectReference vmMor = new MorObjectHandler().getMor(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue(), vmInputs.getVirtualMachineName()); if (vmMor != null) { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); String device = Device.getValue(vmInputs.getDevice()).toLowerCase(); if (Constants.CPU.equalsIgnoreCase(device) || Constants.MEMORY.equalsIgnoreCase(device)) { vmConfigSpec = new VmUtils().getUpdateConfigSpec(vmInputs, vmConfigSpec, device); } else { vmConfigSpec = new VmUtils().getAddOrRemoveSpecs(connectionResources, vmMor, vmInputs, vmConfigSpec, device); } ManagedObjectReference task = connectionResources.getVimPortType().reconfigVMTask(vmMor, vmConfigSpec); return new ResponseHelper(connectionResources, task).getResultsMap("Success: The [" + vmInputs.getVirtualMachineName() + "] VM was successfully reconfigured. The taskId is: " + task.getValue(), "Failure: The [" + vmInputs.getVirtualMachineName() + "] VM could not be reconfigured."); } else { return ResponseUtils.getVmNotFoundResultsMap(vmInputs); } } catch (Exception ex) { return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE); } finally { if (httpInputs.isCloseSession()) { connectionResources.getConnection().disconnect(); clearConnectionFromContext(httpInputs.getGlobalSessionObject()); } } }
public static String getOVFParamValue(VirtualMachineConfigSpec config) { String paramVal = ""; List<OptionValue> options = config.getExtraConfig(); for (OptionValue option : options) { if (OVA_OPTION_KEY_BOOTDISK.equalsIgnoreCase(option.getKey())) { paramVal = (String)option.getValue(); break; } } return paramVal; }
public boolean setVncConfigInfo(boolean enableVnc, String vncPassword, int vncPort, String keyboard) throws Exception { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); OptionValue[] vncOptions = VmwareHelper.composeVncOptions(null, enableVnc, vncPassword, vncPort, keyboard); vmConfigSpec.getExtraConfig().addAll(Arrays.asList(vncOptions)); ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, vmConfigSpec); 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; }
public boolean configureVm(VirtualMachineConfigSpec vmConfigSpec) throws Exception { ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, vmConfigSpec); 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; }