public static PowerState convertPowerState(VirtualMachinePowerState state) { if (state == null) { return null; } switch (state) { case POWERED_OFF: return PowerState.OFF; case POWERED_ON: return PowerState.ON; case SUSPENDED: return PowerState.SUSPEND; default: return PowerState.UNKNOWN; } }
@Override public void resumeNode(String vmName) { VirtualMachine virtualMachine = getNode(vmName); if (virtualMachine.getRuntime().getPowerState().equals(VirtualMachinePowerState.poweredOff)) { try { Task task = virtualMachine.powerOnVM_Task(null); if (task.waitForTask().equals(Task.SUCCESS)) logger.debug(virtualMachine.getName() + " resumed"); } catch (Exception e) { logger.error("Can't resume vm " + vmName, e); propagate(e); } } else logger.debug(vmName + " can't be resumed"); }
public void waitForStopped(String machineName) { VirtualMachine machine = getVirtualMachine(machineName); // 停止判定処理 while (true) { try { Thread.sleep(30 * 1000L); } catch (InterruptedException ignore) { } VirtualMachineRuntimeInfo runtimeInfo = machine.getRuntime(); if (runtimeInfo.getPowerState() == VirtualMachinePowerState.poweredOff) { break; } } }
@GET @Path("/powerstate/{vmname}") public String getVMPowerState(@PathParam("vmname") String vmName) throws VMWareException { Configuration conf = Configuration.getInstance(); VMWareHelper helper = VMWareHelper.getInstance(conf.getUserName(), conf.getPassword(), conf.getUrl()); VirtualMachinePowerState state = helper.getPowerState(vmName); if (state == null) { return null; // throw new VMWareException("Name of VM " + vmName + " not found!"); } return state.name(); }
public boolean isStopped() throws Exception { VirtualMachineRuntimeInfo vmRuntimeInfo = (VirtualMachineRuntimeInfo) vmw .getServiceUtil().getDynamicProperty(vmInstance, "runtime"); if (vmRuntimeInfo != null) { return VirtualMachinePowerState.POWERED_OFF .equals(vmRuntimeInfo.getPowerState()); } LOG.warn("Failed to retrieve runtime information from VM " + instanceName); return false; }
private void softPowerOff(ManagedObjectReference vm, long politenessDeadlineMicros) throws Exception { try { getVimPort().shutdownGuest(vm); } catch (ToolsUnavailableFaultMsg e) { // no vmtoools present, try harder hardPowerOff(vm); return; } // wait for guest to shutdown WaitForValues wait = new WaitForValues(this.connection); int timeout = (int) TimeUnit.MICROSECONDS .toSeconds(politenessDeadlineMicros - Utils.getNowMicrosUtc()); if (timeout <= 0) { // maybe try anyway? return; } Object[] currentPowerState = wait.wait(vm, new String[] { VimPath.vm_runtime_powerState }, new String[] { VimPath.vm_runtime_powerState }, new Object[][] { new Object[] { VirtualMachinePowerState.POWERED_OFF } }, timeout); if (currentPowerState == null || currentPowerState[0] != VirtualMachinePowerState.POWERED_OFF) { // vm not shutdown on time hardPowerOff(vm); } }
@Override public SshClient apply(final VirtualMachine vm) { SshClient client = null; String clientIpAddress = vm.getGuest().getIpAddress(); String sshPort = "22"; while (!vm.getGuest().getToolsStatus().equals(VirtualMachineToolsStatus.toolsOk) || clientIpAddress.isEmpty()) { int timeoutValue = 1000; int timeoutUnits = 500; Predicate<String> tester = Predicates2.retry( ipAddressTester, timeoutValue, timeoutUnits, TimeUnit.MILLISECONDS); boolean passed = false; while (vm.getRuntime().getPowerState() .equals(VirtualMachinePowerState.poweredOn) && !passed) { clientIpAddress = Strings.nullToEmpty(vm.getGuest() .getIpAddress()); passed = tester.apply(clientIpAddress); } } LoginCredentials loginCredentials = LoginCredentials.builder() .user("root").password(password) .build(); checkNotNull(clientIpAddress, "clientIpAddress"); client = sshClientFactory.create( HostAndPort.fromParts(clientIpAddress, Integer.parseInt(sshPort)), loginCredentials); checkNotNull(client); return client; }
@Inject public VirtualMachineToNodeMetadata(Map<VirtualMachinePowerState, NodeMetadata.Status> toPortableNodeStatus, Supplier<Map<String, CustomFieldDef>> customFields, Supplier<VSphereServiceInstance> serviceInstanceSupplier, Function<String, DistributedVirtualPortgroup> distributedVirtualPortgroupFunction, @Named(VSphereConstants.JCLOUDS_VSPHERE_VM_PASSWORD) String vmInitPassword) { this.toPortableNodeStatus = checkNotNull(toPortableNodeStatus, "PortableNodeStatus"); this.customFields = checkNotNull(customFields, "customFields"); this.serviceInstanceSupplier = checkNotNull(serviceInstanceSupplier, "serviceInstanceSupplier"); this.distributedVirtualPortgroupFunction = checkNotNull(distributedVirtualPortgroupFunction, "distributedVirtualPortgroupFunction"); this.vmInitPassword = vmInitPassword; }
public void shutdownGuest(String machineName) { // VirtualMachine VirtualMachine machine = getVirtualMachine(machineName); // パワーオフ状態の場合はスキップ VirtualMachineRuntimeInfo runtimeInfo = machine.getRuntime(); if (runtimeInfo.getPowerState() == VirtualMachinePowerState.poweredOff) { return; } // 仮想マシンのシャットダウン try { machine.shutdownGuest(); } catch (RemoteException e) { throw new AutoException("EPROCESS-000519", e, machineName); } if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100415", machineName)); } // シャットダウンが完了するまで待機 waitForStopped(machineName); if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100416", machineName)); } }
public VirtualMachineInfo(String uuid, String name, String hostName, String vrouterIpAddress, VirtualMachinePowerState powerState) { this.uuid = uuid; this.name = name; this.displayName = name; this.hostName = hostName; this.vrouterIpAddress = vrouterIpAddress; this.powerState = powerState; }
private void setContrailVmActiveState() { if (name.toLowerCase().contains(contrailVRouterVmNamePrefix.toLowerCase())) { // this is a Contrail VM if (!powerState.equals(VirtualMachinePowerState.poweredOn)) { VRouterNotifier.setVrouterActive(vrouterIpAddress, false); } else if (host != null) { if (host.getRuntime().isInMaintenanceMode()) { VRouterNotifier.setVrouterActive(vrouterIpAddress, false); } else { VRouterNotifier.setVrouterActive(vrouterIpAddress, true); } } } }
/** 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 Task checkMigrate_Task(VirtualMachine vm, HostSystem host, ResourcePool pool, VirtualMachinePowerState state, String[] testType) throws NoActiveHostInCluster, InvalidState, RuntimeFault, RemoteException { ManagedObjectReference taskMor = getVimService().checkMigrate_Task(getMOR(), vm.getMOR(), host==null?null : host.getMOR(), pool==null?null : pool.getMOR(), state, testType); return new Task(getServerConnection(), taskMor); }
private boolean powerOffNoCheck() throws Exception { ManagedObjectReference morTask = _context.getService().powerOffVMTask(_mor); boolean result = _context.getVimClient().waitForTask(morTask); if (result) { _context.waitForTaskProgressDone(morTask); // It seems that even if a power-off task is returned done, VM state may still not be marked, // wait up to 5 seconds to make sure to avoid race conditioning for immediate following on operations // that relies on a powered-off VM long startTick = System.currentTimeMillis(); while (getResetSafePowerState() != VirtualMachinePowerState.POWERED_OFF && System.currentTimeMillis() - startTick < 5000) { try { Thread.sleep(1000); } catch (InterruptedException e) { s_logger.debug("[ignored] interupted while powering of vm unconditionaly."); } } return true; } else { if (getResetSafePowerState() == VirtualMachinePowerState.POWERED_OFF) { // to help deal with possible race-condition s_logger.info("Current power-off task failed. However, VM has been switched to the state we are expecting for"); return true; } s_logger.error("VMware powerOffVM_Task failed due to " + TaskMO.getTaskFailureInfo(_context, morTask)); } return false; }
private static boolean migrateVM(ServiceInstance si, Folder rootFolder, HostSystem newHost, String targetVMName, String newHostName) throws Exception { log("Selected host [vm] for vMotion: " + newHostName + " [" + targetVMName + "]"); VirtualMachine vm = (VirtualMachine)new InventoryNavigator(rootFolder) .searchManagedEntity("VirtualMachine", targetVMName); if (vm == null) { log(WARNING, "Could not resolve VM " + targetVMName + ", vMotion of this VM cannot be performed."); return false; } ComputeResource cr = (ComputeResource)newHost.getParent(); String[] checks = new String[] { "cpu", "software" }; HostVMotionCompatibility[] vmcs = si.queryVMotionCompatibility(vm, new HostSystem[] { newHost }, checks); String[] comps = vmcs[0].getCompatibility(); if (checks.length != comps.length) { log(WARNING, "CPU/software NOT compatible, vMotion failed."); return false; } long start = System.currentTimeMillis(); Task task = vm.migrateVM_Task(cr.getResourcePool(), newHost, VirtualMachineMovePriority.highPriority, VirtualMachinePowerState.poweredOn); if (task.waitForMe() == Task.SUCCESS) { long end = System.currentTimeMillis(); log("vMotion of " + targetVMName + " to " + newHostName + " completed in " + (end - start) + "ms. Task result: " + task.getTaskInfo().getResult()); return true; } else { TaskInfo info = task.getTaskInfo(); log(WARNING, "vMotion of " + targetVMName + " to " + newHostName + " failed. Error details: " + info.getError().getFault()); return false; } }
public PowerState getPowerState() { return VSphereToPhotonMapping.convertPowerState( (VirtualMachinePowerState) getOrFail(VimPath.vm_runtime_powerState)); }
public PowerState getPowerState(ManagedObjectReference vm) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { VirtualMachinePowerState vmps = this.get.entityProp(vm, VimPath.vm_runtime_powerState); return VSphereToPhotonMapping.convertPowerState(vmps); }
@Singleton @Provides protected Map<VirtualMachinePowerState, NodeMetadata.Status> toPortableNodeStatus() { return toPortableNodeStatus; }
@Singleton @Provides protected Map<VirtualMachinePowerState, Image.Status> toPortableImageStatus() { return toPortableImageStatus; }
@Inject public VirtualMachineToImage(Map<VirtualMachinePowerState, Status> toPortableImageStatus, Map<OsFamily, Map<String, String>> osVersionMap) { this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap"); }
public VirtualMachinePowerState getPowerState() { return powerState; }
public void setPowerState(VirtualMachinePowerState powerState) { this.powerState = powerState; }
public boolean isPowerStateEqual(VirtualMachinePowerState powerState) { if (this.powerState == powerState) return true; else return false; }
public boolean isPoweredOnState() { if (powerState == VirtualMachinePowerState.poweredOn) return true; else return false; }
public static void main(String[] args) throws Exception { if(args.length!=5) { System.out.println("Usage: java MigrateVM <url> " + "<username> <password> <vmname> <newhost>"); System.exit(0); } String vmname = args[3]; String newHostName = args[4]; ServiceInstance si = new ServiceInstance( new URL(args[0]), args[1], args[2], true); Folder rootFolder = si.getRootFolder(); VirtualMachine vm = (VirtualMachine) new InventoryNavigator( rootFolder).searchManagedEntity( "VirtualMachine", vmname); HostSystem newHost = (HostSystem) new InventoryNavigator( rootFolder).searchManagedEntity( "HostSystem", newHostName); ComputeResource cr = (ComputeResource) newHost.getParent(); String[] checks = new String[] {"cpu", "software"}; HostVMotionCompatibility[] vmcs = si.queryVMotionCompatibility(vm, new HostSystem[] {newHost},checks ); String[] comps = vmcs[0].getCompatibility(); if(checks.length != comps.length) { System.out.println("CPU/software NOT compatible. Exit."); si.getServerConnection().logout(); return; } Task task = vm.migrateVM_Task(cr.getResourcePool(), newHost, VirtualMachineMovePriority.highPriority, VirtualMachinePowerState.poweredOn); if(task.waitForMe()==Task.SUCCESS) { System.out.println("VMotioned!"); } else { System.out.println("VMotion failed!"); TaskInfo info = task.getTaskInfo(); System.out.println(info.getError().getFault()); } si.getServerConnection().logout(); }
public boolean powerOff() throws Exception { if (getResetSafePowerState() == VirtualMachinePowerState.POWERED_OFF) return true; return powerOffNoCheck(); }
public VirtualMachinePowerState getPowerState() throws Exception { return (VirtualMachinePowerState)getContext().getVimClient().getDynamicProperty(_mor, "runtime.powerState"); }
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; }
private static PowerState convertPowerState(VirtualMachinePowerState powerState) { return s_powerStatesTable.get(powerState); }
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)"); }