com.vmware.vim25.VirtualMachinePowerState Java Examples

The following examples show how to use com.vmware.vim25.VirtualMachinePowerState. 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: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
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;
        }
    }
}
 
Example #2
Source File: VM.java    From development with Apache License 2.0 5 votes vote down vote up
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;

}
 
Example #3
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
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));
    }
}
 
Example #4
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #5
Source File: VMotionTrigger.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
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;
  }
}
 
Example #6
Source File: VMotionTrigger.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
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;
  }
}
 
Example #7
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public boolean powerOff() throws Exception {
    if (getResetSafePowerState() == VirtualMachinePowerState.POWERED_OFF)
        return true;

    return powerOffNoCheck();
}
 
Example #8
Source File: VirtualMachineMO.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public VirtualMachinePowerState getPowerState() throws Exception {
    return (VirtualMachinePowerState)getContext().getVimClient().getDynamicProperty(_mor, "runtime.powerState");
}
 
Example #9
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 #10
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;
    }