Search in sources :

Example 6 with VimPortType

use of com.vmware.vim25.VimPortType in project cloudstack by apache.

the class VMwareUtil method retrievePropertiesAllObjects.

private static List<ObjectContent> retrievePropertiesAllObjects(List<PropertyFilterSpec> lstPfs, VimPortType vimPortType, ManagedObjectReference propCollectorRef) throws Exception {
    List<ObjectContent> lstObjectContent = new ArrayList<>();
    RetrieveOptions retrieveOptions = new RetrieveOptions();
    RetrieveResult rslts = vimPortType.retrievePropertiesEx(propCollectorRef, lstPfs, retrieveOptions);
    if (rslts != null && rslts.getObjects() != null && rslts.getObjects().size() > 0) {
        List<ObjectContent> lstOc = new ArrayList<>();
        for (ObjectContent oc : rslts.getObjects()) {
            lstOc.add(oc);
        }
        lstObjectContent.addAll(lstOc);
    }
    String token = null;
    if (rslts != null && rslts.getToken() != null) {
        token = rslts.getToken();
    }
    while (token != null && !token.isEmpty()) {
        rslts = vimPortType.continueRetrievePropertiesEx(propCollectorRef, token);
        token = null;
        if (rslts != null) {
            token = rslts.getToken();
            if (rslts.getObjects() != null && rslts.getObjects().size() > 0) {
                List<ObjectContent> lstOc = new ArrayList<>();
                for (ObjectContent oc : rslts.getObjects()) {
                    lstOc.add(oc);
                }
                lstObjectContent.addAll(lstOc);
            }
        }
    }
    return lstObjectContent;
}
Also used : ObjectContent(com.vmware.vim25.ObjectContent) ArrayList(java.util.ArrayList) RetrieveOptions(com.vmware.vim25.RetrieveOptions) RetrieveResult(com.vmware.vim25.RetrieveResult)

Example 7 with VimPortType

use of com.vmware.vim25.VimPortType in project opennms by OpenNMS.

the class VmwareViJavaAccess method setTimeout.

/**
 * Sets the timeout for server connections.
 *
 * @param timeout the timeout to be used for connecting
 * @return true, if the operation was successful
 */
public boolean setTimeout(int timeout) {
    if (m_serviceInstance != null) {
        ServerConnection serverConnection = m_serviceInstance.getServerConnection();
        if (serverConnection != null) {
            VimPortType vimService = serverConnection.getVimService();
            if (vimService != null) {
                Client client = vimService.getWsc();
                if (client != null) {
                    client.setConnectTimeout(timeout);
                    client.setReadTimeout(timeout);
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : ServerConnection(com.vmware.vim25.mo.ServerConnection) Client(com.vmware.vim25.ws.Client) CIMClient(org.sblim.wbem.client.CIMClient) VimPortType(com.vmware.vim25.VimPortType)

Example 8 with VimPortType

use of com.vmware.vim25.VimPortType in project photon-model by vmware.

the class WaitForValues method wait.

/**
 * Handle Updates for a single object. waits till expected values of
 * properties to check are reached Destroys the ObjectFilter when done.
 * The matching properties will be added to the list of properties to fetch.
 *
 * @param moRef       MOR of the Object to wait for
 * @param fetchProps  Properties list to filter
 * @param propsToMatch Properties list to check for expected values these be properties
 *                     of a property in the filter properties list
 * @param propsMatchValues values for properties to end the wait
 * @param maxWaitSeconds how long to wait for the condition to be met, use null to wait forever
 * @return the requested properties or null if expected values not reached within timeout
 * @throws RuntimeFaultFaultMsg
 * @throws InvalidPropertyFaultMsg
 * @throws InvalidCollectorVersionFaultMsg
 */
public Object[] wait(ManagedObjectReference moRef, String[] fetchProps, String[] propsToMatch, Object[][] propsMatchValues, Integer maxWaitSeconds) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg {
    VimPortType vimPort;
    ManagedObjectReference filterSpecRef = null;
    ServiceContent serviceContent;
    try {
        vimPort = this.connection.getVimPort();
        serviceContent = this.connection.getServiceContent();
    } catch (Throwable cause) {
        throw new BaseHelper.HelperException(cause);
    }
    // version string is initially null
    String version = "";
    Object[] endVals = new Object[propsToMatch.length];
    String stateVal = null;
    PropertyFilterSpec spec = propertyFilterSpec(moRef, fetchProps, propsToMatch);
    filterSpecRef = vimPort.createFilter(serviceContent.getPropertyCollector(), spec, true);
    boolean reached = false;
    UpdateSet updateset;
    List<PropertyFilterUpdate> filtupary;
    List<ObjectUpdate> objupary;
    List<PropertyChange> propchgary;
    // override maxWaitSeconds to give the timeout a chance to be hit earlier
    WaitOptions waitOptions = new WaitOptions();
    waitOptions.setMaxWaitSeconds(DEFAULT_MAX_WAIT_SECONDS);
    long timeout = -1;
    if (maxWaitSeconds != null) {
        timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(maxWaitSeconds);
    }
    while (!reached && shouldContinue(timeout)) {
        updateset = vimPort.waitForUpdatesEx(serviceContent.getPropertyCollector(), version, waitOptions);
        if (updateset == null || updateset.getFilterSet() == null) {
            continue;
        }
        version = updateset.getVersion();
        // Make this code more general purpose when PropCol changes later.
        filtupary = updateset.getFilterSet();
        for (PropertyFilterUpdate filtup : filtupary) {
            objupary = filtup.getObjectSet();
            for (ObjectUpdate objup : objupary) {
                propchgary = objup.getChangeSet();
                for (PropertyChange propchg : propchgary) {
                    updateValues(propsToMatch, endVals, propchg);
                }
            }
        }
        // Also exit the WaitForUpdates loop if this is the case.
        for (int chgi = 0; chgi < endVals.length && !reached; chgi++) {
            for (int vali = 0; vali < propsMatchValues[chgi].length && !reached; vali++) {
                Object expectedValue = propsMatchValues[chgi][vali];
                Object endVal = endVals[chgi];
                if (endVal == null) {
                // Do Nothing
                } else if (endVal.toString().contains("val: null")) {
                    // Due to some issue in JAX-WS De-serialization getting the information from
                    // the nodes
                    Element stateElement = (Element) endVal;
                    if (stateElement.getFirstChild() != null) {
                        stateVal = stateElement.getFirstChild().getTextContent();
                        reached = expectedValue.toString().equalsIgnoreCase(stateVal) || reached;
                    }
                } else {
                    expectedValue = propsMatchValues[chgi][vali];
                    reached = expectedValue.equals(endVal) || reached;
                    stateVal = "filtervals";
                }
            }
        }
    }
    if (!reached) {
        // got here but condition not reached; timeout
        return null;
    }
    Object[] retVal = null;
    // Destroy the filter when we are done.
    try {
        vimPort.destroyPropertyFilter(filterSpecRef);
    } catch (RuntimeFaultFaultMsg e) {
        e.printStackTrace();
    }
    if (stateVal != null) {
        if (stateVal.equalsIgnoreCase("ready")) {
            retVal = new Object[] { HttpNfcLeaseState.READY };
        }
        if (stateVal.equalsIgnoreCase("error")) {
            retVal = new Object[] { HttpNfcLeaseState.ERROR };
        }
        if (stateVal.equals("filtervals")) {
            retVal = fetchFinalValues(moRef, fetchProps);
        }
    } else {
        retVal = new Object[] { HttpNfcLeaseState.ERROR };
    }
    return retVal;
}
Also used : PropertyFilterSpec(com.vmware.vim25.PropertyFilterSpec) PropertyFilterUpdate(com.vmware.vim25.PropertyFilterUpdate) PropertyChange(com.vmware.vim25.PropertyChange) Element(org.w3c.dom.Element) RuntimeFaultFaultMsg(com.vmware.vim25.RuntimeFaultFaultMsg) WaitOptions(com.vmware.vim25.WaitOptions) VimPortType(com.vmware.vim25.VimPortType) ServiceContent(com.vmware.vim25.ServiceContent) UpdateSet(com.vmware.vim25.UpdateSet) ObjectUpdate(com.vmware.vim25.ObjectUpdate) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 9 with VimPortType

use of com.vmware.vim25.VimPortType in project photon-model by vmware.

the class ClientUtils method powerOffVM.

/**
 * Power off virtual machine
 */
public static void powerOffVM(final Connection connection, final VimPortType vimPort, final ManagedObjectReference vm) throws Exception {
    ManagedObjectReference powerTask = vimPort.powerOffVMTask(vm);
    TaskInfo info = VimUtils.waitTaskEnd(connection, powerTask);
    if (info.getState() == TaskInfoState.ERROR) {
        VimUtils.rethrow(info.getError());
    }
}
Also used : TaskInfo(com.vmware.vim25.TaskInfo) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference)

Example 10 with VimPortType

use of com.vmware.vim25.VimPortType in project cloudstack by apache.

the class VmwareResource method getVmStats.

private HashMap<String, VmStatsEntry> getVmStats(List<String> vmNames) throws Exception {
    VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext());
    HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>();
    ManagedObjectReference perfMgr = getServiceContext().getServiceContent().getPerfManager();
    VimPortType service = getServiceContext().getService();
    PerfCounterInfo rxPerfCounterInfo = null;
    PerfCounterInfo txPerfCounterInfo = null;
    PerfCounterInfo diskReadIOPerfCounterInfo = null;
    PerfCounterInfo diskWriteIOPerfCounterInfo = null;
    PerfCounterInfo diskReadKbsPerfCounterInfo = null;
    PerfCounterInfo diskWriteKbsPerfCounterInfo = null;
    Integer windowInterval = getVmwareWindowTimeInterval();
    final XMLGregorianCalendar startTime = VmwareHelper.getXMLGregorianCalendar(new Date(), windowInterval);
    final XMLGregorianCalendar endTime = VmwareHelper.getXMLGregorianCalendar(new Date(), 0);
    List<PerfCounterInfo> cInfo = getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter");
    for (PerfCounterInfo info : cInfo) {
        if ("net".equalsIgnoreCase(info.getGroupInfo().getKey()) && "average".equalsIgnoreCase(info.getRollupType().value())) {
            if ("transmitted".equalsIgnoreCase(info.getNameInfo().getKey())) {
                txPerfCounterInfo = info;
            }
            if ("received".equalsIgnoreCase(info.getNameInfo().getKey())) {
                rxPerfCounterInfo = info;
            }
        }
        if ("virtualdisk".equalsIgnoreCase(info.getGroupInfo().getKey())) {
            if ("numberReadAveraged".equalsIgnoreCase(info.getNameInfo().getKey())) {
                diskReadIOPerfCounterInfo = info;
            }
            if ("numberWriteAveraged".equalsIgnoreCase(info.getNameInfo().getKey())) {
                diskWriteIOPerfCounterInfo = info;
            }
            if ("read".equalsIgnoreCase(info.getNameInfo().getKey())) {
                diskReadKbsPerfCounterInfo = info;
            }
            if ("write".equalsIgnoreCase(info.getNameInfo().getKey())) {
                diskWriteKbsPerfCounterInfo = info;
            }
        }
    }
    int key = ((HostMO) hyperHost).getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_VM_INTERNAL_NAME);
    if (key == 0) {
        s_logger.warn("Custom field " + CustomFieldConstants.CLOUD_VM_INTERNAL_NAME + " is not registered ?!");
    }
    String instanceNameCustomField = "value[" + key + "]";
    final String numCpuStr = "summary.config.numCpu";
    final String cpuUseStr = "summary.quickStats.overallCpuUsage";
    final String guestMemUseStr = "summary.quickStats.guestMemoryUsage";
    final String memLimitStr = "resourceConfig.memoryAllocation.limit";
    final String memMbStr = "config.hardware.memoryMB";
    final String allocatedCpuStr = "summary.runtime.maxCpuUsage";
    ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", numCpuStr, cpuUseStr, guestMemUseStr, memLimitStr, memMbStr, allocatedCpuStr, instanceNameCustomField });
    if (ocs != null && ocs.length > 0) {
        for (ObjectContent oc : ocs) {
            List<DynamicProperty> objProps = oc.getPropSet();
            if (objProps != null) {
                String name = null;
                String numberCPUs = null;
                double maxCpuUsage = 0;
                String memlimit = null;
                String memkb = null;
                String guestMemusage = null;
                String vmNameOnVcenter = null;
                String vmInternalCSName = null;
                double allocatedCpu = 0;
                for (DynamicProperty objProp : objProps) {
                    if (objProp.getName().equals("name")) {
                        vmNameOnVcenter = objProp.getVal().toString();
                    } else if (objProp.getName().contains(instanceNameCustomField)) {
                        if (objProp.getVal() != null)
                            vmInternalCSName = ((CustomFieldStringValue) objProp.getVal()).getValue();
                    } else if (objProp.getName().equals(guestMemUseStr)) {
                        guestMemusage = objProp.getVal().toString();
                    } else if (objProp.getName().equals(numCpuStr)) {
                        numberCPUs = objProp.getVal().toString();
                    } else if (objProp.getName().equals(cpuUseStr)) {
                        maxCpuUsage = NumberUtils.toDouble(objProp.getVal().toString());
                    } else if (objProp.getName().equals(memLimitStr)) {
                        memlimit = objProp.getVal().toString();
                    } else if (objProp.getName().equals(memMbStr)) {
                        memkb = objProp.getVal().toString();
                    } else if (objProp.getName().equals(allocatedCpuStr)) {
                        allocatedCpu = NumberUtils.toDouble(objProp.getVal().toString());
                    }
                }
                maxCpuUsage = (maxCpuUsage / allocatedCpu) * 100;
                if (vmInternalCSName != null) {
                    name = vmInternalCSName;
                } else {
                    name = vmNameOnVcenter;
                }
                if (!vmNames.contains(name)) {
                    continue;
                }
                ManagedObjectReference vmMor = hyperHost.findVmOnHyperHost(name).getMor();
                assert (vmMor != null);
                double networkReadKBs = 0;
                double networkWriteKBs = 0;
                double diskReadIops = 0;
                double diskWriteIops = 0;
                double diskReadKbs = 0;
                double diskWriteKbs = 0;
                final ArrayList<PerfMetricId> perfMetricsIds = new ArrayList<PerfMetricId>();
                if (rxPerfCounterInfo != null) {
                    perfMetricsIds.add(VmwareHelper.createPerfMetricId(rxPerfCounterInfo, ""));
                }
                if (txPerfCounterInfo != null) {
                    perfMetricsIds.add(VmwareHelper.createPerfMetricId(txPerfCounterInfo, ""));
                }
                if (diskReadIOPerfCounterInfo != null) {
                    perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskReadIOPerfCounterInfo, "*"));
                }
                if (diskWriteIOPerfCounterInfo != null) {
                    perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskWriteIOPerfCounterInfo, "*"));
                }
                if (diskReadKbsPerfCounterInfo != null) {
                    perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskReadKbsPerfCounterInfo, ""));
                }
                if (diskWriteKbsPerfCounterInfo != null) {
                    perfMetricsIds.add(VmwareHelper.createPerfMetricId(diskWriteKbsPerfCounterInfo, ""));
                }
                if (perfMetricsIds.size() > 0) {
                    try {
                        final PerfQuerySpec qSpec = new PerfQuerySpec();
                        qSpec.setEntity(vmMor);
                        qSpec.setFormat("normal");
                        qSpec.setIntervalId(windowInterval);
                        qSpec.setStartTime(startTime);
                        qSpec.setEndTime(endTime);
                        qSpec.getMetricId().addAll(perfMetricsIds);
                        final List<PerfEntityMetricBase> perfValues = service.queryPerf(perfMgr, Collections.singletonList(qSpec));
                        for (final PerfEntityMetricBase perfValue : perfValues) {
                            if (!(perfValue instanceof PerfEntityMetric)) {
                                continue;
                            }
                            final List<PerfMetricSeries> seriesList = ((PerfEntityMetric) perfValue).getValue();
                            for (final PerfMetricSeries series : seriesList) {
                                if (!(series instanceof PerfMetricIntSeries)) {
                                    continue;
                                }
                                final List<Long> values = ((PerfMetricIntSeries) series).getValue();
                                double sum = 0;
                                for (final Long value : values) {
                                    sum += value;
                                }
                                double avg = sum / (values.size() * 1f);
                                if (series.getId().getCounterId() == rxPerfCounterInfo.getKey()) {
                                    networkReadKBs = avg;
                                }
                                if (series.getId().getCounterId() == txPerfCounterInfo.getKey()) {
                                    networkWriteKBs = avg;
                                }
                                if (series.getId().getCounterId() == diskReadIOPerfCounterInfo.getKey()) {
                                    diskReadIops += avg;
                                }
                                if (series.getId().getCounterId() == diskWriteIOPerfCounterInfo.getKey()) {
                                    diskWriteIops += avg;
                                }
                                if (series.getId().getCounterId() == diskReadKbsPerfCounterInfo.getKey()) {
                                    diskReadKbs = avg;
                                }
                                if (series.getId().getCounterId() == diskWriteKbsPerfCounterInfo.getKey()) {
                                    diskWriteKbs = avg;
                                }
                            }
                        }
                    } catch (Exception e) {
                        s_logger.error(String.format("Unable to execute PerfQuerySpec due to: [%s]. The window interval is enabled in vCenter?", VmwareHelper.getExceptionMessage(e)), e);
                    }
                }
                final VmStatsEntry vmStats = new VmStatsEntry(NumberUtils.toDouble(memkb) * 1024, NumberUtils.toDouble(guestMemusage) * 1024, NumberUtils.toDouble(memlimit) * 1024, maxCpuUsage, networkReadKBs, networkWriteKBs, NumberUtils.toInt(numberCPUs), "vm");
                vmStats.setDiskReadIOs(diskReadIops);
                vmStats.setDiskWriteIOs(diskWriteIops);
                vmStats.setDiskReadKBs(diskReadKbs);
                vmStats.setDiskWriteKBs(diskWriteKbs);
                vmResponseMap.put(name, vmStats);
            }
        }
    }
    return vmResponseMap;
}
Also used : PerfCounterInfo(com.vmware.vim25.PerfCounterInfo) DynamicProperty(com.vmware.vim25.DynamicProperty) HashMap(java.util.HashMap) HostMO(com.cloud.hypervisor.vmware.mo.HostMO) ArrayList(java.util.ArrayList) VmStatsEntry(com.cloud.agent.api.VmStatsEntry) PerfEntityMetricBase(com.vmware.vim25.PerfEntityMetricBase) ObjectContent(com.vmware.vim25.ObjectContent) PerfMetricIntSeries(com.vmware.vim25.PerfMetricIntSeries) PerfMetricSeries(com.vmware.vim25.PerfMetricSeries) PerfMetricId(com.vmware.vim25.PerfMetricId) VmwareHypervisorHost(com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost) VimPortType(com.vmware.vim25.VimPortType) Date(java.util.Date) 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) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) PerfQuerySpec(com.vmware.vim25.PerfQuerySpec) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) PerfEntityMetric(com.vmware.vim25.PerfEntityMetric)

Aggregations

ManagedObjectReference (com.vmware.vim25.ManagedObjectReference)10 VimPortType (com.vmware.vim25.VimPortType)9 ArrayList (java.util.ArrayList)5 TaskInfo (com.vmware.vim25.TaskInfo)4 HashMap (java.util.HashMap)3 CloudException (com.cloud.exception.CloudException)2 InternalErrorException (com.cloud.exception.InternalErrorException)2 VmwareHypervisorHost (com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 DynamicProperty (com.vmware.vim25.DynamicProperty)2 ObjectContent (com.vmware.vim25.ObjectContent)2 PerfCounterInfo (com.vmware.vim25.PerfCounterInfo)2 PerfEntityMetric (com.vmware.vim25.PerfEntityMetric)2 PerfEntityMetricBase (com.vmware.vim25.PerfEntityMetricBase)2 PerfMetricId (com.vmware.vim25.PerfMetricId)2 PerfMetricIntSeries (com.vmware.vim25.PerfMetricIntSeries)2 PerfMetricSeries (com.vmware.vim25.PerfMetricSeries)2 PerfQuerySpec (com.vmware.vim25.PerfQuerySpec)2 PropertyFilterSpec (com.vmware.vim25.PropertyFilterSpec)2 ServiceContent (com.vmware.vim25.ServiceContent)2