Search in sources :

Example 31 with Task

use of com.vmware.vim25.mo.Task in project cloudstack by apache.

the class VmwareStorageProcessor method addRemoveInternetScsiTargetsToAllHosts.

private void addRemoveInternetScsiTargetsToAllHosts(boolean add, List<HostInternetScsiHbaStaticTarget> targets, List<HostMO> hosts) throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(hosts.size());
    final List<Exception> exceptions = new ArrayList<>();
    for (HostMO host : hosts) {
        HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO();
        boolean iScsiHbaConfigured = false;
        for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) {
            if (hba instanceof HostInternetScsiHba && ((HostInternetScsiHba) hba).isIsSoftwareBased()) {
                iScsiHbaConfigured = true;
                final String iScsiHbaDevice = hba.getDevice();
                final HostStorageSystemMO hss = hostStorageSystem;
                executorService.submit(new Thread(() -> {
                    try {
                        if (add) {
                            hss.addInternetScsiStaticTargets(iScsiHbaDevice, targets);
                        } else {
                            hss.removeInternetScsiStaticTargets(iScsiHbaDevice, targets);
                        }
                    } catch (Exception ex) {
                        synchronized (exceptions) {
                            exceptions.add(ex);
                        }
                    }
                }));
            }
        }
        if (!iScsiHbaConfigured) {
            throw new Exception("An iSCSI HBA must be configured before a host can use iSCSI storage.");
        }
    }
    executorService.shutdown();
    if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES)) {
        throw new Exception("The system timed out before completing the task 'addRemoveInternetScsiTargetsToAllHosts'.");
    }
    if (exceptions.size() > 0) {
        throw new Exception(exceptions.get(0).getMessage());
    }
}
Also used : HostMO(com.cloud.hypervisor.vmware.mo.HostMO) HostInternetScsiHba(com.vmware.vim25.HostInternetScsiHba) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) HostStorageSystemMO(com.cloud.hypervisor.vmware.mo.HostStorageSystemMO) HostHostBusAdapter(com.vmware.vim25.HostHostBusAdapter) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RemoteException(java.rmi.RemoteException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 32 with Task

use of com.vmware.vim25.mo.Task in project cloudstack by apache.

the class VmwareStorageManagerImpl method execute.

@Override
public CreateVMSnapshotAnswer execute(VmwareHostService hostService, CreateVMSnapshotCommand cmd) {
    List<VolumeObjectTO> volumeTOs = cmd.getVolumeTOs();
    String vmName = cmd.getVmName();
    String vmSnapshotName = cmd.getTarget().getSnapshotName();
    String vmSnapshotDesc = cmd.getTarget().getDescription();
    boolean snapshotMemory = cmd.getTarget().getType() == VMSnapshot.Type.DiskAndMemory;
    boolean quiescevm = cmd.getTarget().getQuiescevm();
    VirtualMachineMO vmMo = null;
    VmwareContext context = hostService.getServiceContext(cmd);
    try {
        VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
        // wait if there are already VM snapshot task running
        ManagedObjectReference taskmgr = context.getServiceContent().getTaskManager();
        List<ManagedObjectReference> tasks = context.getVimClient().getDynamicProperty(taskmgr, "recentTask");
        for (ManagedObjectReference taskMor : tasks) {
            TaskInfo info = (TaskInfo) (context.getVimClient().getDynamicProperty(taskMor, "info"));
            if (info.getEntityName().equals(cmd.getVmName()) && org.apache.commons.lang3.StringUtils.isNotBlank(info.getName()) && info.getName().equalsIgnoreCase("CreateSnapshot_Task")) {
                if (!(info.getState().equals(TaskInfoState.SUCCESS) || info.getState().equals(TaskInfoState.ERROR))) {
                    s_logger.debug("There is already a VM snapshot task running, wait for it");
                    context.getVimClient().waitForTask(taskMor);
                }
            }
        }
        vmMo = hyperHost.findVmOnHyperHost(vmName);
        if (vmMo == null) {
            vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
        }
        if (vmMo == null) {
            String msg = "Unable to find VM for CreateVMSnapshotCommand";
            s_logger.info(msg);
            return new CreateVMSnapshotAnswer(cmd, false, msg);
        } else {
            if (vmMo.getSnapshotMor(vmSnapshotName) != null) {
                s_logger.info("VM snapshot " + vmSnapshotName + " already exists");
            } else if (!vmMo.createSnapshot(vmSnapshotName, vmSnapshotDesc, snapshotMemory, quiescevm)) {
                return new CreateVMSnapshotAnswer(cmd, false, "Unable to create snapshot due to esxi internal failed");
            }
            Map<String, String> mapNewDisk = getNewDiskMap(vmMo);
            setVolumeToPathAndSize(volumeTOs, mapNewDisk, context, hyperHost, cmd.getVmName());
            return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), volumeTOs);
        }
    } catch (Exception e) {
        String msg = e.getMessage();
        s_logger.error("failed to create snapshot for vm:" + vmName + " due to " + msg);
        try {
            if (vmMo.getSnapshotMor(vmSnapshotName) != null) {
                vmMo.removeSnapshot(vmSnapshotName, false);
            }
        } catch (Exception e1) {
            s_logger.info("[ignored]" + "error during snapshot remove: " + e1.getLocalizedMessage());
        }
        return new CreateVMSnapshotAnswer(cmd, false, e.getMessage());
    }
}
Also used : VirtualMachineMO(com.cloud.hypervisor.vmware.mo.VirtualMachineMO) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TaskInfo(com.vmware.vim25.TaskInfo) VmwareContext(com.cloud.hypervisor.vmware.util.VmwareContext) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 33 with Task

use of com.vmware.vim25.mo.Task in project cloudstack by apache.

the class VmwareResource method postNvpConfigBeforeStart.

private static void postNvpConfigBeforeStart(VirtualMachineMO vmMo, VirtualMachineTO vmSpec) throws Exception {
    /**
     * We need to configure the port on the DV switch after the host is
     * connected. So make this happen between the configure and start of
     * the VM
     */
    int nicIndex = 0;
    for (NicTO nicTo : sortNicsByDeviceId(vmSpec.getNics())) {
        if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) {
            // We need to create a port with a unique vlan and pass the key to the nic device
            s_logger.trace("Nic " + nicTo.toString() + " is connected to an NVP logicalswitch");
            VirtualDevice nicVirtualDevice = vmMo.getNicDeviceByIndex(nicIndex);
            if (nicVirtualDevice == null) {
                // FIXME Generic exceptions are bad
                throw new Exception("Failed to find a VirtualDevice for nic " + nicIndex);
            }
            VirtualDeviceBackingInfo backing = nicVirtualDevice.getBacking();
            if (backing instanceof VirtualEthernetCardDistributedVirtualPortBackingInfo) {
                // This NIC is connected to a Distributed Virtual Switch
                VirtualEthernetCardDistributedVirtualPortBackingInfo portInfo = (VirtualEthernetCardDistributedVirtualPortBackingInfo) backing;
                DistributedVirtualSwitchPortConnection port = portInfo.getPort();
                String portKey = port.getPortKey();
                String portGroupKey = port.getPortgroupKey();
                String dvSwitchUuid = port.getSwitchUuid();
                s_logger.debug("NIC " + nicTo.toString() + " is connected to dvSwitch " + dvSwitchUuid + " pg " + portGroupKey + " port " + portKey);
                ManagedObjectReference dvSwitchManager = vmMo.getContext().getVimClient().getServiceContent().getDvSwitchManager();
                ManagedObjectReference dvSwitch = vmMo.getContext().getVimClient().getService().queryDvsByUuid(dvSwitchManager, dvSwitchUuid);
                // Get all ports
                DistributedVirtualSwitchPortCriteria criteria = new DistributedVirtualSwitchPortCriteria();
                criteria.setInside(true);
                criteria.getPortgroupKey().add(portGroupKey);
                List<DistributedVirtualPort> dvPorts = vmMo.getContext().getVimClient().getService().fetchDVPorts(dvSwitch, criteria);
                DistributedVirtualPort vmDvPort = null;
                List<Integer> usedVlans = new ArrayList<Integer>();
                for (DistributedVirtualPort dvPort : dvPorts) {
                    // Find the port for this NIC by portkey
                    if (portKey.equals(dvPort.getKey())) {
                        vmDvPort = dvPort;
                    }
                    VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPort.getConfig().getSetting();
                    VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings.getVlan();
                    s_logger.trace("Found port " + dvPort.getKey() + " with vlan " + vlanId.getVlanId());
                    if (vlanId.getVlanId() > 0 && vlanId.getVlanId() < 4095) {
                        usedVlans.add(vlanId.getVlanId());
                    }
                }
                if (vmDvPort == null) {
                    throw new Exception("Empty port list from dvSwitch for nic " + nicTo.toString());
                }
                DVPortConfigInfo dvPortConfigInfo = vmDvPort.getConfig();
                VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPortConfigInfo.getSetting();
                VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings.getVlan();
                BoolPolicy blocked = settings.getBlocked();
                if (blocked.isValue() == Boolean.TRUE) {
                    s_logger.trace("Port is blocked, set a vlanid and unblock");
                    DVPortConfigSpec dvPortConfigSpec = new DVPortConfigSpec();
                    VMwareDVSPortSetting edittedSettings = new VMwareDVSPortSetting();
                    // Unblock
                    blocked.setValue(Boolean.FALSE);
                    blocked.setInherited(Boolean.FALSE);
                    edittedSettings.setBlocked(blocked);
                    // Set vlan
                    int i;
                    for (i = 1; i < 4095; i++) {
                        if (!usedVlans.contains(i))
                            break;
                    }
                    // FIXME should be a determined
                    vlanId.setVlanId(i);
                    // based on usage
                    vlanId.setInherited(false);
                    edittedSettings.setVlan(vlanId);
                    dvPortConfigSpec.setSetting(edittedSettings);
                    dvPortConfigSpec.setOperation("edit");
                    dvPortConfigSpec.setKey(portKey);
                    List<DVPortConfigSpec> dvPortConfigSpecs = new ArrayList<DVPortConfigSpec>();
                    dvPortConfigSpecs.add(dvPortConfigSpec);
                    ManagedObjectReference task = vmMo.getContext().getVimClient().getService().reconfigureDVPortTask(dvSwitch, dvPortConfigSpecs);
                    if (!vmMo.getContext().getVimClient().waitForTask(task)) {
                        throw new Exception("Failed to configure the dvSwitch port for nic " + nicTo.toString());
                    }
                    s_logger.debug("NIC " + nicTo.toString() + " connected to vlan " + i);
                } else {
                    s_logger.trace("Port already configured and set to vlan " + vlanId.getVlanId());
                }
            } else if (backing instanceof VirtualEthernetCardNetworkBackingInfo) {
            // This NIC is connected to a Virtual Switch
            // Nothing to do
            } else if (backing instanceof VirtualEthernetCardOpaqueNetworkBackingInfo) {
            // if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
            // OK, connected to OpaqueNetwork
            } else {
                s_logger.error("nic device backing is of type " + backing.getClass().getName());
                // FIXME Generic exceptions are bad
                throw new Exception("Incompatible backing for a VirtualDevice for nic " + nicIndex);
            }
        }
        nicIndex++;
    }
}
Also used : DVPortConfigSpec(com.vmware.vim25.DVPortConfigSpec) VMwareDVSPortSetting(com.vmware.vim25.VMwareDVSPortSetting) VirtualEthernetCardDistributedVirtualPortBackingInfo(com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo) VirtualEthernetCardNetworkBackingInfo(com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo) VirtualEthernetCardOpaqueNetworkBackingInfo(com.vmware.vim25.VirtualEthernetCardOpaqueNetworkBackingInfo) DistributedVirtualPort(com.vmware.vim25.DistributedVirtualPort) VirtualDevice(com.vmware.vim25.VirtualDevice) ArrayList(java.util.ArrayList) VirtualDeviceBackingInfo(com.vmware.vim25.VirtualDeviceBackingInfo) DistributedVirtualSwitchPortConnection(com.vmware.vim25.DistributedVirtualSwitchPortConnection) BoolPolicy(com.vmware.vim25.BoolPolicy) ConnectException(java.net.ConnectException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) InternalErrorException(com.cloud.exception.InternalErrorException) CloudException(com.cloud.exception.CloudException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) DVPortConfigInfo(com.vmware.vim25.DVPortConfigInfo) DistributedVirtualSwitchPortCriteria(com.vmware.vim25.DistributedVirtualSwitchPortCriteria) VmwareDistributedVirtualSwitchVlanIdSpec(com.vmware.vim25.VmwareDistributedVirtualSwitchVlanIdSpec) NicTO(com.cloud.agent.api.to.NicTO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 34 with Task

use of com.vmware.vim25.mo.Task in project cloudstack by apache.

the class ResultWrapper method updateSiocInfoForWorkerVM.

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);
}
Also used : VirtualDeviceFileBackingInfo(com.vmware.vim25.VirtualDeviceFileBackingInfo) VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) ArrayList(java.util.ArrayList) VirtualDevice(com.vmware.vim25.VirtualDevice) VirtualMachineConfigInfo(com.vmware.vim25.VirtualMachineConfigInfo) VirtualDisk(com.vmware.vim25.VirtualDisk) StorageIOAllocationInfo(com.vmware.vim25.StorageIOAllocationInfo) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 35 with Task

use of com.vmware.vim25.mo.Task in project cloudstack by apache.

the class ResultWrapper method updateSiocInfo.

private ResultWrapper updateSiocInfo(VMwareUtil.VMwareConnection connection, Map<String, ManagedObjectReference> nameToVm, Long instanceId, StoragePoolVO storagePool, int sharesPerGB, int limitIopsPerGB) throws Exception {
    int limitIopsTotal = 0;
    List<ManagedObjectReference> tasks = new ArrayList<>();
    VMInstanceVO vmInstance = vmInstanceDao.findById(instanceId);
    if (vmInstance == null) {
        String errMsg = "Error: The VM with ID " + instanceId + " could not be located.";
        throw new Exception(errMsg);
    }
    String vmName = vmInstance.getInstanceName();
    ManagedObjectReference morVm = nameToVm.get(vmName);
    if (morVm == null) {
        String errMsg = "Error: The VM with ID " + instanceId + " could not be located (ManagedObjectReference).";
        throw new Exception(errMsg);
    }
    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;
            VolumeVO volumeVO = getVolumeFromVirtualDisk(vmInstance, storagePool.getId(), devices, disk);
            if (volumeVO != null) {
                boolean diskUpdated = false;
                StorageIOAllocationInfo sioai = disk.getStorageIOAllocation();
                SharesInfo sharesInfo = sioai.getShares();
                int currentShares = sharesInfo.getShares();
                int newShares = getNewSharesBasedOnVolumeSize(volumeVO, sharesPerGB);
                if (currentShares != newShares) {
                    sharesInfo.setLevel(SharesLevel.CUSTOM);
                    sharesInfo.setShares(newShares);
                    diskUpdated = true;
                }
                long currentLimitIops = sioai.getLimit() != null ? sioai.getLimit() : Long.MIN_VALUE;
                long newLimitIops = getNewLimitIopsBasedOnVolumeSize(volumeVO, 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(getInfoMsg(volumeVO, newShares, newLimitIops));
                    } catch (Exception ex) {
                        throw new Exception("Error: " + ex.getMessage());
                    }
                }
            }
        }
    }
    return new ResultWrapper(limitIopsTotal, tasks);
}
Also used : SharesInfo(com.vmware.vim25.SharesInfo) VirtualDeviceConfigSpec(com.vmware.vim25.VirtualDeviceConfigSpec) ArrayList(java.util.ArrayList) VirtualDevice(com.vmware.vim25.VirtualDevice) VMInstanceVO(com.cloud.vm.VMInstanceVO) VirtualMachineConfigInfo(com.vmware.vim25.VirtualMachineConfigInfo) VirtualDisk(com.vmware.vim25.VirtualDisk) StorageIOAllocationInfo(com.vmware.vim25.StorageIOAllocationInfo) VirtualMachineConfigSpec(com.vmware.vim25.VirtualMachineConfigSpec) VolumeVO(com.cloud.storage.VolumeVO) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Aggregations

ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)48 Task (com.vmware.vim25.mo.Task)27 TaskInfo (com.vmware.vim25.TaskInfo)23 ArrayList (java.util.ArrayList)21 RemoteException (java.rmi.RemoteException)18 QueryTask (com.vmware.xenon.services.common.QueryTask)14 Operation (com.vmware.xenon.common.Operation)13 List (java.util.List)13 PhotonModelUriUtils (com.vmware.photon.controller.model.util.PhotonModelUriUtils)11 ArrayOfManagedObjectReference (com.vmware.vim25.ArrayOfManagedObjectReference)11 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)10 QueryUtils (com.vmware.photon.controller.model.query.QueryUtils)10 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)10 ComputeDescriptionService (com.vmware.photon.controller.model.resources.ComputeDescriptionService)9 DiskService (com.vmware.photon.controller.model.resources.DiskService)9 TaskInfoState (com.vmware.vim25.TaskInfoState)9 ComputeService (com.vmware.photon.controller.model.resources.ComputeService)8 RuntimeFaultFaultMsg (com.vmware.vim25.RuntimeFaultFaultMsg)8 ComputeProperties (com.vmware.photon.controller.model.ComputeProperties)7 InvalidPropertyFaultMsg (com.vmware.vim25.InvalidPropertyFaultMsg)7