Search in sources :

Example 1 with VmwareViJavaAccess

use of org.opennms.protocols.vmware.VmwareViJavaAccess in project opennms by OpenNMS.

the class VmwareViJavaAccessTest method setUp.

@Before
public void setUp() throws Exception {
    // setup required objects
    managedObjectReferenceManagedEntity = new ManagedObjectReference();
    managedObjectReferenceManagedEntity.setType("ManagedEntity");
    managedObjectReferenceManagedEntity.setVal("moIdMe");
    managedObjectReferenceVirtualMachine = new ManagedObjectReference();
    managedObjectReferenceVirtualMachine.setType("VirtualMachine");
    managedObjectReferenceVirtualMachine.setVal("moIdVm");
    managedObjectReferenceHostSystem = new ManagedObjectReference();
    managedObjectReferenceHostSystem.setType("HostSystem");
    managedObjectReferenceHostSystem.setVal("moIdHs");
    // setup VmwareViJavaAccess
    vmwareViJavaAccess = new VmwareViJavaAccess("hostname", "username", "password") {

        @Override
        protected void relax() {
        }
    };
    // setup PerformanceManager
    mockPerformanceManager = createMock(PerformanceManager.class);
    // setup ServiceInstance mock
    mockServiceInstance = createMock(ServiceInstance.class);
    // setup ServerConnection
    mockServerConnection = new ServerConnection(new URL("https://hostname/sdk"), new VimPortType(new WSClient("https://hostname/sdk") {

        @Override
        protected SSLSocketFactory getTrustAllSocketFactory(boolean ignoreCert) throws RemoteException {
            return null;
        }
    }), mockServiceInstance);
    // setup AboutInfo
    mockAboutInfo = createMock(AboutInfo.class);
    expectNew(ServiceInstance.class, new Class<?>[] { URL.class, String.class, String.class }, new URL("https://hostname/sdk"), "username", "password").andReturn(mockServiceInstance).anyTimes();
    expect(mockServiceInstance.getServerConnection()).andReturn(mockServerConnection).anyTimes();
    expect(mockServiceInstance.getPerformanceManager()).andReturn(mockPerformanceManager).anyTimes();
    expect(mockServiceInstance.getAboutInfo()).andReturn(mockAboutInfo).anyTimes();
    managedEntity = new ManagedEntity(null, managedObjectReferenceManagedEntity);
    virtualMachine = new VirtualMachine(null, managedObjectReferenceVirtualMachine);
    hostSystem = new HostSystem(null, managedObjectReferenceHostSystem);
    // setup MorUtil
    mockStatic(MorUtil.class);
    expect(MorUtil.createExactManagedEntity(mockServerConnection, managedObjectReferenceManagedEntity)).andReturn(managedEntity).anyTimes();
    expect(MorUtil.createExactManagedEntity(mockServerConnection, managedObjectReferenceVirtualMachine)).andReturn(virtualMachine).anyTimes();
    expect(MorUtil.createExactManagedEntity(mockServerConnection, managedObjectReferenceHostSystem)).andReturn(hostSystem).anyTimes();
    // setup about info
    expect(mockAboutInfo.getApiVersion()).andReturn("2.x");
    expect(mockAboutInfo.getApiVersion()).andReturn("3.x");
    expect(mockAboutInfo.getApiVersion()).andReturn("4.x");
    expect(mockAboutInfo.getApiVersion()).andReturn("5.x");
    expect(mockAboutInfo.getApiVersion()).andReturn("6.x");
    expect(mockAboutInfo.getApiVersion()).andReturn("x");
    // setup performance data
    int refreshRate = 100;
    int metricCount = 15;
    int instanceModifier = 5;
    perfQuerySpec = new PerfQuerySpec();
    perfQuerySpec.setEntity(managedEntity.getMOR());
    perfQuerySpec.setMaxSample(new Integer(1));
    perfQuerySpec.setIntervalId(refreshRate);
    perfEntityMetricBases = new PerfEntityMetricBase[metricCount];
    perfCounterInfos = new PerfCounterInfo[metricCount];
    for (int i = 0; i < metricCount; i++) {
        ElementDescription groupInfo = new ElementDescription();
        groupInfo.setKey("key" + i);
        ElementDescription nameInfo = new ElementDescription();
        nameInfo.setKey("name" + i);
        perfCounterInfos[i] = new PerfCounterInfo();
        perfCounterInfos[i].setKey(i);
        perfCounterInfos[i].setGroupInfo(groupInfo);
        perfCounterInfos[i].setNameInfo(nameInfo);
        perfCounterInfos[i].setRollupType(PerfSummaryType.average);
        perfEntityMetricBases[i] = new PerfEntityMetric();
        PerfMetricIntSeries[] perfMetricIntSeries;
        int instanceCount = (i % instanceModifier) + 1;
        perfMetricIntSeries = new PerfMetricIntSeries[instanceCount];
        for (int b = 0; b < instanceCount; b++) {
            PerfMetricId perfMetricId = new PerfMetricId();
            perfMetricId.setCounterId(i);
            if (instanceCount == 1) {
                perfMetricId.setInstance(null);
            } else {
                perfMetricId.setInstance("instance" + b);
            }
            perfMetricIntSeries[b] = new PerfMetricIntSeries();
            perfMetricIntSeries[b].setValue(new long[] { (long) 42 });
            perfMetricIntSeries[b].setId(perfMetricId);
        }
        ((PerfEntityMetric) perfEntityMetricBases[i]).setValue(perfMetricIntSeries);
    }
    // setup PerfProviderSummary
    mockPerfProviderSummary = createMock(PerfProviderSummary.class);
    expect(mockPerformanceManager.queryPerfProviderSummary(managedEntity)).andReturn(mockPerfProviderSummary).anyTimes();
    expect(mockPerfProviderSummary.getRefreshRate()).andReturn(refreshRate).anyTimes();
    expect(mockPerformanceManager.getPerfCounter()).andReturn(perfCounterInfos).anyTimes();
    expect(mockPerformanceManager.queryPerf(anyObject(PerfQuerySpec[].class))).andReturn(perfEntityMetricBases).anyTimes();
    // setup network info
    HostNetworkInfo hostNetworkInfo = new HostNetworkInfo();
    int numberOfVnics = 3;
    HostVirtualNic[] hostVirtualNics = new HostVirtualNic[numberOfVnics];
    for (int i = 0; i < numberOfVnics; i++) {
        HostVirtualNicSpec hostVirtualNicSpec = new HostVirtualNicSpec();
        HostIpConfig hostIpConfig = new HostIpConfig();
        hostIpConfig.setIpAddress("192.168.1." + (i + 1));
        hostVirtualNicSpec.setIp(hostIpConfig);
        hostVirtualNics[i] = new HostVirtualNic();
        hostVirtualNics[i].setSpec(hostVirtualNicSpec);
    }
    hostNetworkInfo.setVnic(hostVirtualNics);
    HostVirtualNic[] hostVirtualConsoleNics = new HostVirtualNic[numberOfVnics];
    for (int i = 0; i < numberOfVnics; i++) {
        HostVirtualNicSpec hostVirtualNicSpec = new HostVirtualNicSpec();
        HostIpConfig hostIpConfig = new HostIpConfig();
        hostIpConfig.setIpAddress("192.168.2." + (i + 1));
        hostVirtualNicSpec.setIp(hostIpConfig);
        hostVirtualConsoleNics[i] = new HostVirtualNic();
        hostVirtualConsoleNics[i].setSpec(hostVirtualNicSpec);
    }
    hostNetworkInfo.setConsoleVnic(hostVirtualConsoleNics);
    HostServiceTicket hostServiceTicket = new HostServiceTicket();
    hostServiceTicket.setSessionId("sessionId");
    // setup HostSystem
    mockHostSystem = createMock(HostSystem.class);
    // setup HostNetworkSystem
    mockHostNetworkSystem = createMock(HostNetworkSystem.class);
    // setup CIMClient
    mockCIMClient = createPartialMock(CIMClient.class, "enumerateInstances", "getSessionProperties");
    // setup the cim objects
    cimObjects = new ArrayList<>();
    int cimObjectCount = 5;
    for (int i = 0; i < cimObjectCount; i++) {
        CIMInstance cimInstance = new CIMInstance();
        cimInstance.setName("cimInstance" + i);
        cimObjects.add(cimInstance);
    }
    expect(mockHostSystem.getName()).andReturn("mockesxi01.local").anyTimes();
    expect(mockHostSystem.getHostNetworkSystem()).andReturn(mockHostNetworkSystem).anyTimes();
    expect(mockHostSystem.acquireCimServicesTicket()).andReturn(hostServiceTicket).anyTimes();
    expect(mockHostNetworkSystem.getNetworkInfo()).andReturn(hostNetworkInfo).anyTimes();
    expectNew(CIMClient.class, new Class<?>[] { CIMNameSpace.class, Principal.class, Object.class }, anyObject(), anyObject(), anyObject()).andReturn(mockCIMClient).anyTimes();
    suppress(method(CIMClient.class, "useMPost"));
    expect(mockCIMClient.enumerateInstances(new CIMObjectPath("cimClass"))).andReturn(Collections.enumeration(cimObjects)).anyTimes();
    SessionProperties sessionProperties = new SessionProperties();
    expect(mockCIMClient.getSessionProperties()).andReturn(sessionProperties).anyTimes();
}
Also used : HostVirtualNic(com.vmware.vim25.HostVirtualNic) PerfCounterInfo(com.vmware.vim25.PerfCounterInfo) CIMClient(org.sblim.wbem.client.CIMClient) HostIpConfig(com.vmware.vim25.HostIpConfig) HostVirtualNicSpec(com.vmware.vim25.HostVirtualNicSpec) ServiceInstance(com.vmware.vim25.mo.ServiceInstance) URL(java.net.URL) CIMInstance(org.sblim.wbem.cim.CIMInstance) PerfMetricIntSeries(com.vmware.vim25.PerfMetricIntSeries) PerformanceManager(com.vmware.vim25.mo.PerformanceManager) HostSystem(com.vmware.vim25.mo.HostSystem) HostServiceTicket(com.vmware.vim25.HostServiceTicket) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess) ElementDescription(com.vmware.vim25.ElementDescription) HostNetworkSystem(com.vmware.vim25.mo.HostNetworkSystem) ManagedEntity(com.vmware.vim25.mo.ManagedEntity) HostNetworkInfo(com.vmware.vim25.HostNetworkInfo) WSClient(com.vmware.vim25.ws.WSClient) PerfMetricId(com.vmware.vim25.PerfMetricId) AboutInfo(com.vmware.vim25.AboutInfo) CIMObjectPath(org.sblim.wbem.cim.CIMObjectPath) ServerConnection(com.vmware.vim25.mo.ServerConnection) VimPortType(com.vmware.vim25.VimPortType) SessionProperties(org.sblim.wbem.util.SessionProperties) PerfProviderSummary(com.vmware.vim25.PerfProviderSummary) PerfQuerySpec(com.vmware.vim25.PerfQuerySpec) RemoteException(java.rmi.RemoteException) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) VirtualMachine(com.vmware.vim25.mo.VirtualMachine) PerfEntityMetric(com.vmware.vim25.PerfEntityMetric) Before(org.junit.Before)

Example 2 with VmwareViJavaAccess

use of org.opennms.protocols.vmware.VmwareViJavaAccess in project opennms by OpenNMS.

the class VmwareCimCollector method collect.

/**
 * This method collect the data for a given collection agent.
 *
 * @param agent      the collection agent
 * @param parameters the parameters map
 * @return the generated collection set
 * @throws CollectionException
 */
@Override
public CollectionSet collect(CollectionAgent agent, Map<String, Object> parameters) throws CollectionException {
    final VmwareCimCollection collection = (VmwareCimCollection) parameters.get(VMWARE_COLLECTION_KEY);
    final String vmwareManagementServer = (String) parameters.get(VMWARE_MGMT_SERVER_KEY);
    final String vmwareManagedObjectId = (String) parameters.get(VMWARE_MGED_OBJECT_ID_KEY);
    final VmwareServer vmwareServer = (VmwareServer) parameters.get(VMWARE_SERVER_KEY);
    CollectionSetBuilder builder = new CollectionSetBuilder(agent);
    builder.withStatus(CollectionStatus.FAILED);
    VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareServer);
    int timeout = ParameterMap.getKeyedInteger(parameters, "timeout", -1);
    if (timeout > 0) {
        if (!vmwareViJavaAccess.setTimeout(timeout)) {
            logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
        }
    }
    if (collection.getVmwareCimGroup().length < 1) {
        logger.info("No groups to collect. Returning empty collection set.");
        builder.withStatus(CollectionStatus.SUCCEEDED);
        return builder.build();
    }
    try {
        vmwareViJavaAccess.connect();
    } catch (MalformedURLException e) {
        logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
        return builder.build();
    } catch (RemoteException e) {
        logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
        return builder.build();
    }
    HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId);
    String powerState = null;
    if (hostSystem == null) {
        logger.debug("hostSystem=null");
    } else {
        HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
        if (hostRuntimeInfo == null) {
            logger.debug("hostRuntimeInfo=null");
        } else {
            HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
            if (hostSystemPowerState == null) {
                logger.debug("hostSystemPowerState=null");
            } else {
                powerState = hostSystemPowerState.toString();
            }
        }
    }
    logger.debug("The power state for host system '{}' is '{}'", vmwareManagedObjectId, powerState);
    if ("poweredOn".equals(powerState)) {
        HashMap<String, List<CIMObject>> cimObjects = new HashMap<String, List<CIMObject>>();
        for (final VmwareCimGroup vmwareCimGroup : collection.getVmwareCimGroup()) {
            String cimClass = vmwareCimGroup.getCimClass();
            if (!cimObjects.containsKey(cimClass)) {
                List<CIMObject> cimList = null;
                try {
                    cimList = vmwareViJavaAccess.queryCimObjects(hostSystem, cimClass, InetAddressUtils.str(agent.getAddress()));
                } catch (Exception e) {
                    logger.warn("Error retrieving CIM values from host system '{}'. Error message: '{}'", vmwareManagedObjectId, e.getMessage());
                    return builder.build();
                } finally {
                    vmwareViJavaAccess.disconnect();
                }
                cimObjects.put(cimClass, cimList);
            }
            final List<CIMObject> cimList = cimObjects.get(cimClass);
            if (cimList == null) {
                logger.warn("Error getting objects of CIM class '{}' from host system '{}'", cimClass, vmwareManagedObjectId);
                continue;
            }
            String keyAttribute = vmwareCimGroup.getKey();
            String attributeValue = vmwareCimGroup.getValue();
            String instanceAttribute = vmwareCimGroup.getInstance();
            for (CIMObject cimObject : cimList) {
                boolean addObject = false;
                if (keyAttribute != null && attributeValue != null) {
                    String cimObjectValue = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, keyAttribute);
                    if (attributeValue.equals(cimObjectValue)) {
                        addObject = true;
                    } else {
                        addObject = false;
                    }
                } else {
                    addObject = true;
                }
                if (addObject) {
                    final String instance = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, instanceAttribute);
                    final NodeLevelResource nodeResource = new NodeLevelResource(agent.getNodeId());
                    final Resource resource = new DeferredGenericTypeResource(nodeResource, vmwareCimGroup.getResourceType(), instance);
                    for (Attrib attrib : vmwareCimGroup.getAttrib()) {
                        final AttributeType type = attrib.getType();
                        String value = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, attrib.getName());
                        if (valueModifiers.containsKey(attrib.getName())) {
                            String modifiedValue = valueModifiers.get(attrib.getName()).modifyValue(attrib.getName(), value, cimObject, vmwareViJavaAccess);
                            logger.debug("Applying value modifier for instance value " + attrib.getName() + "[" + instance + "]='" + value + "' => '" + modifiedValue + "' for node " + agent.getNodeId());
                            value = modifiedValue;
                        }
                        builder.withAttribute(resource, vmwareCimGroup.getName(), attrib.getAlias(), value, type);
                    }
                }
            }
        }
        builder.withStatus(CollectionStatus.SUCCEEDED);
    }
    vmwareViJavaAccess.disconnect();
    return builder.build();
}
Also used : MalformedURLException(java.net.MalformedURLException) CIMObject(org.sblim.wbem.cim.CIMObject) CollectionSetBuilder(org.opennms.netmgt.collection.support.builder.CollectionSetBuilder) HostRuntimeInfo(com.vmware.vim25.HostRuntimeInfo) HashMap(java.util.HashMap) DeferredGenericTypeResource(org.opennms.netmgt.collection.support.builder.DeferredGenericTypeResource) Resource(org.opennms.netmgt.collection.support.builder.Resource) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) VmwareCimCollection(org.opennms.netmgt.config.vmware.cim.VmwareCimCollection) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) HostSystemPowerState(com.vmware.vim25.HostSystemPowerState) CollectionException(org.opennms.netmgt.collection.api.CollectionException) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) CollectionInitializationException(org.opennms.netmgt.collection.api.CollectionInitializationException) Attrib(org.opennms.netmgt.config.vmware.cim.Attrib) DeferredGenericTypeResource(org.opennms.netmgt.collection.support.builder.DeferredGenericTypeResource) VmwareServer(org.opennms.netmgt.config.vmware.VmwareServer) AttributeType(org.opennms.netmgt.collection.api.AttributeType) HostSystem(com.vmware.vim25.mo.HostSystem) List(java.util.List) VmwareCimGroup(org.opennms.netmgt.config.vmware.cim.VmwareCimGroup) RemoteException(java.rmi.RemoteException) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess)

Example 3 with VmwareViJavaAccess

use of org.opennms.protocols.vmware.VmwareViJavaAccess in project opennms by OpenNMS.

the class VmwareCollector method collect.

/**
 * This method collect the data for a given collection agent.
 *
 * @param agent      the collection agent
 * @param parameters the parameters map
 * @return the generated collection set
 * @throws CollectionException
 */
@Override
public CollectionSet collect(CollectionAgent agent, Map<String, Object> parameters) throws CollectionException {
    final VmwareCollection collection = (VmwareCollection) parameters.get(VMWARE_COLLECTION_KEY);
    final String vmwareManagementServer = (String) parameters.get(VMWARE_MGMT_SERVER_KEY);
    final String vmwareManagedObjectId = (String) parameters.get(VMWARE_MGED_OBJECT_ID_KEY);
    final VmwareServer vmwareServer = (VmwareServer) parameters.get(VMWARE_SERVER_KEY);
    CollectionSetBuilder builder = new CollectionSetBuilder(agent);
    builder.withStatus(CollectionStatus.FAILED);
    VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareServer);
    int timeout = ParameterMap.getKeyedInteger(parameters, "timeout", -1);
    if (timeout > 0) {
        if (!vmwareViJavaAccess.setTimeout(timeout)) {
            logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
        }
    }
    if (collection.getVmwareGroup().length < 1) {
        logger.info("No groups to collect. Returning empty collection set.");
        builder.withStatus(CollectionStatus.SUCCEEDED);
        return builder.build();
    }
    try {
        vmwareViJavaAccess.connect();
    } catch (MalformedURLException e) {
        logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
        return builder.build();
    } catch (RemoteException e) {
        logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
        return builder.build();
    }
    ManagedEntity managedEntity = vmwareViJavaAccess.getManagedEntityByManagedObjectId(vmwareManagedObjectId);
    VmwarePerformanceValues vmwarePerformanceValues = null;
    try {
        vmwarePerformanceValues = vmwareViJavaAccess.queryPerformanceValues(managedEntity);
    } catch (RemoteException e) {
        logger.warn("Error retrieving performance values from VMware management server '" + vmwareManagementServer + "' for managed object '" + vmwareManagedObjectId + "'", e.getMessage());
        vmwareViJavaAccess.disconnect();
        return builder.build();
    }
    for (final VmwareGroup vmwareGroup : collection.getVmwareGroup()) {
        final NodeLevelResource nodeResource = new NodeLevelResource(agent.getNodeId());
        if ("node".equalsIgnoreCase(vmwareGroup.getResourceType())) {
            for (Attrib attrib : vmwareGroup.getAttrib()) {
                if (!vmwarePerformanceValues.hasSingleValue(attrib.getName())) {
                    // warning
                    logger.debug("Warning! No single value for '{}' defined as single instance attribute for node {}", attrib.getName(), agent.getNodeId());
                } else {
                    final Long value = vmwarePerformanceValues.getValue(attrib.getName());
                    logger.debug("Storing single instance value {}='{}' for node {}", attrib.getName(), value, agent.getNodeId());
                    final AttributeType type = attrib.getType();
                    if (type.isNumeric()) {
                        builder.withNumericAttribute(nodeResource, vmwareGroup.getName(), attrib.getAlias(), value, type);
                    } else {
                        builder.withStringAttribute(nodeResource, vmwareGroup.getName(), attrib.getAlias(), String.valueOf(value));
                    }
                }
            }
        } else {
            // multi instance value
            final Set<String> instanceSet = new TreeSet<>();
            final HashMap<String, Resource> resources = new HashMap<>();
            for (Attrib attrib : vmwareGroup.getAttrib()) {
                if (!vmwarePerformanceValues.hasInstances(attrib.getName())) {
                    // warning
                    logger.debug("Warning! No multi instance value for '{}' defined as multi instance attribute for node {}", attrib.getName(), agent.getNodeId());
                } else {
                    Set<String> newInstances = vmwarePerformanceValues.getInstances(attrib.getName());
                    for (String instance : newInstances) {
                        if (!instanceSet.contains(instance)) {
                            resources.put(instance, new DeferredGenericTypeResource(nodeResource, vmwareGroup.getResourceType(), instance));
                            instanceSet.add(instance);
                        }
                        final AttributeType type = attrib.getType();
                        final Long value = vmwarePerformanceValues.getValue(attrib.getName(), instance);
                        logger.debug("Storing multi instance value {}[{}='{}' for node {}", attrib.getName(), instance, value, agent.getNodeId());
                        if (type.isNumeric()) {
                            builder.withNumericAttribute(resources.get(instance), vmwareGroup.getName(), attrib.getAlias(), value, type);
                        } else {
                            builder.withStringAttribute(resources.get(instance), vmwareGroup.getName(), attrib.getAlias(), Long.toString(value));
                        }
                    }
                }
            }
            for (String instance : instanceSet) {
                logger.debug("Storing multi instance value {}[{}='{}' for node {}", vmwareGroup.getResourceType() + "Name", instance, instance, agent.getNodeId());
                builder.withStringAttribute(resources.get(instance), vmwareGroup.getName(), vmwareGroup.getResourceType() + "Name", instance);
            }
        }
    }
    builder.withStatus(CollectionStatus.SUCCEEDED);
    vmwareViJavaAccess.disconnect();
    return builder.build();
}
Also used : ManagedEntity(com.vmware.vim25.mo.ManagedEntity) MalformedURLException(java.net.MalformedURLException) CollectionSetBuilder(org.opennms.netmgt.collection.support.builder.CollectionSetBuilder) HashMap(java.util.HashMap) DeferredGenericTypeResource(org.opennms.netmgt.collection.support.builder.DeferredGenericTypeResource) Resource(org.opennms.netmgt.collection.support.builder.Resource) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) Attrib(org.opennms.netmgt.config.vmware.vijava.Attrib) DeferredGenericTypeResource(org.opennms.netmgt.collection.support.builder.DeferredGenericTypeResource) VmwareGroup(org.opennms.netmgt.config.vmware.vijava.VmwareGroup) VmwareServer(org.opennms.netmgt.config.vmware.VmwareServer) AttributeType(org.opennms.netmgt.collection.api.AttributeType) TreeSet(java.util.TreeSet) VmwareCollection(org.opennms.netmgt.config.vmware.vijava.VmwareCollection) VmwarePerformanceValues(org.opennms.netmgt.collectd.vmware.vijava.VmwarePerformanceValues) RemoteException(java.rmi.RemoteException) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess)

Example 4 with VmwareViJavaAccess

use of org.opennms.protocols.vmware.VmwareViJavaAccess in project opennms by OpenNMS.

the class VmwareCimMonitor method poll.

/**
 * This method queries the Vmware hypervisor for sensor data.
 *
 * @param svc        the monitored service
 * @param parameters the parameter map
 * @return the poll status for this system
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    final boolean ignoreStandBy = getKeyedBoolean(parameters, "ignoreStandBy", false);
    final String vmwareManagementServer = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_KEY, null);
    final String vmwareManagedObjectId = getKeyedString(parameters, VMWARE_MANAGED_OBJECT_ID_KEY, null);
    final String vmwareMangementServerUsername = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_USERNAME_KEY, null);
    final String vmwareMangementServerPassword = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_PASSWORD_KEY, null);
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    PollStatus serviceStatus = PollStatus.unknown();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        final VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer, vmwareMangementServerUsername, vmwareMangementServerPassword);
        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
            return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
        } catch (RemoteException e) {
            logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
            return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
        }
        if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) {
            logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
        }
        HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId);
        String powerState = null;
        if (hostSystem == null) {
            return PollStatus.unknown("hostSystem=null");
        } else {
            HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
            if (hostRuntimeInfo == null) {
                return PollStatus.unknown("hostRuntimeInfo=null");
            } else {
                HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
                if (hostSystemPowerState == null) {
                    return PollStatus.unknown("hostSystemPowerState=null");
                } else {
                    powerState = hostSystemPowerState.toString();
                }
            }
        }
        if ("poweredOn".equals(powerState)) {
            List<CIMObject> cimObjects = null;
            try {
                cimObjects = vmwareViJavaAccess.queryCimObjects(hostSystem, "CIM_NumericSensor", svc.getIpAddr());
            } catch (Exception e) {
                logger.warn("Error retrieving CIM values from host system '{}'", vmwareManagedObjectId, e.getMessage());
                vmwareViJavaAccess.disconnect();
                return PollStatus.unavailable("Error retrieving cim values from host system '" + vmwareManagedObjectId + "'");
            }
            boolean success = true;
            final StringBuilder reason = new StringBuilder("VMware CIM query returned: ");
            for (CIMObject cimObject : cimObjects) {
                String healthState = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, "HealthState");
                String cimObjectName = vmwareViJavaAccess.getPropertyOfCimObject(cimObject, "Name");
                if (healthState != null) {
                    int healthStateInt = Integer.valueOf(healthState).intValue();
                    if (healthStateInt != 5) {
                        if (!success) {
                            reason.append(", ");
                        }
                        success = false;
                        reason.append(cimObjectName + " ");
                        if (m_healthStates.containsKey(healthStateInt)) {
                            reason.append("(" + m_healthStates.get(healthStateInt) + ")");
                        } else {
                            reason.append("(" + healthStateInt + ")");
                        }
                    }
                }
            }
            if (success) {
                serviceStatus = PollStatus.available();
            } else {
                serviceStatus = PollStatus.unavailable(reason.toString());
            }
        } else {
            if (ignoreStandBy && "standBy".equals(powerState)) {
                serviceStatus = PollStatus.up();
            } else {
                serviceStatus = PollStatus.unresponsive("Host system's power state is '" + powerState + "'");
            }
        }
        vmwareViJavaAccess.disconnect();
    }
    return serviceStatus;
}
Also used : MalformedURLException(java.net.MalformedURLException) CIMObject(org.sblim.wbem.cim.CIMObject) PollStatus(org.opennms.netmgt.poller.PollStatus) HostRuntimeInfo(com.vmware.vim25.HostRuntimeInfo) HostSystemPowerState(com.vmware.vim25.HostSystemPowerState) MalformedURLException(java.net.MalformedURLException) RemoteException(java.rmi.RemoteException) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) HostSystem(com.vmware.vim25.mo.HostSystem) RemoteException(java.rmi.RemoteException) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess)

Example 5 with VmwareViJavaAccess

use of org.opennms.protocols.vmware.VmwareViJavaAccess in project opennms by OpenNMS.

the class VmwareMonitor method poll.

/**
 * This method queries the Vmware vCenter server for sensor data.
 *
 * @param svc        the monitored service
 * @param parameters the parameter map
 * @return the poll status for this system
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    final boolean ignoreStandBy = getKeyedBoolean(parameters, "ignoreStandBy", false);
    final String vmwareManagementServer = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_KEY, null);
    final String vmwareManagedEntityType = getKeyedString(parameters, VMWARE_MANAGED_ENTITY_TYPE_KEY, null);
    final String vmwareManagedObjectId = getKeyedString(parameters, VMWARE_MANAGED_OBJECT_ID_KEY, null);
    final String vmwareMangementServerUsername = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_USERNAME_KEY, null);
    final String vmwareMangementServerPassword = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_PASSWORD_KEY, null);
    final TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    PollStatus serviceStatus = PollStatus.unknown();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        final VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer, vmwareMangementServerUsername, vmwareMangementServerPassword);
        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
            return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
        } catch (RemoteException e) {
            logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
            return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
        }
        if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) {
            logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
        }
        String powerState = "unknown";
        if ("HostSystem".equals(vmwareManagedEntityType)) {
            HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId);
            if (hostSystem == null) {
                return PollStatus.unknown("hostSystem=null");
            } else {
                HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
                if (hostRuntimeInfo == null) {
                    return PollStatus.unknown("hostRuntimeInfo=null");
                } else {
                    HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
                    if (hostSystemPowerState == null) {
                        return PollStatus.unknown("hostSystemPowerState=null");
                    } else {
                        powerState = hostSystemPowerState.toString();
                    }
                }
            }
        } else {
            if ("VirtualMachine".equals(vmwareManagedEntityType)) {
                VirtualMachine virtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId(vmwareManagedObjectId);
                if (virtualMachine == null) {
                    return PollStatus.unknown("virtualMachine=null");
                } else {
                    VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();
                    if (virtualMachineRuntimeInfo == null) {
                        return PollStatus.unknown("virtualMachineRuntimeInfo=null");
                    } else {
                        VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
                        if (virtualMachinePowerState == null) {
                            return PollStatus.unknown("virtualMachinePowerState=null");
                        } else {
                            powerState = virtualMachinePowerState.toString();
                        }
                    }
                }
            } else {
                logger.warn("Error getting '{}' for '{}'", vmwareManagedEntityType, vmwareManagedObjectId);
                vmwareViJavaAccess.disconnect();
                return serviceStatus;
            }
        }
        if ("poweredOn".equals(powerState)) {
            serviceStatus = PollStatus.available();
        } else {
            if (ignoreStandBy && "standBy".equals(powerState)) {
                serviceStatus = PollStatus.up();
            } else {
                serviceStatus = PollStatus.unavailable("The system's state is '" + powerState + "'");
            }
        }
        vmwareViJavaAccess.disconnect();
    }
    return serviceStatus;
}
Also used : MalformedURLException(java.net.MalformedURLException) PollStatus(org.opennms.netmgt.poller.PollStatus) HostRuntimeInfo(com.vmware.vim25.HostRuntimeInfo) VirtualMachineRuntimeInfo(com.vmware.vim25.VirtualMachineRuntimeInfo) HostSystemPowerState(com.vmware.vim25.HostSystemPowerState) VirtualMachinePowerState(com.vmware.vim25.VirtualMachinePowerState) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) HostSystem(com.vmware.vim25.mo.HostSystem) RemoteException(java.rmi.RemoteException) VmwareViJavaAccess(org.opennms.protocols.vmware.VmwareViJavaAccess) VirtualMachine(com.vmware.vim25.mo.VirtualMachine)

Aggregations

RemoteException (java.rmi.RemoteException)8 VmwareViJavaAccess (org.opennms.protocols.vmware.VmwareViJavaAccess)8 MalformedURLException (java.net.MalformedURLException)7 HostSystem (com.vmware.vim25.mo.HostSystem)6 HostRuntimeInfo (com.vmware.vim25.HostRuntimeInfo)5 HostSystemPowerState (com.vmware.vim25.HostSystemPowerState)5 ManagedEntity (com.vmware.vim25.mo.ManagedEntity)4 VirtualMachine (com.vmware.vim25.mo.VirtualMachine)4 HashMap (java.util.HashMap)4 VirtualMachinePowerState (com.vmware.vim25.VirtualMachinePowerState)3 VirtualMachineRuntimeInfo (com.vmware.vim25.VirtualMachineRuntimeInfo)3 IOException (java.io.IOException)3 List (java.util.List)3 TreeSet (java.util.TreeSet)3 Requisition (org.opennms.netmgt.provision.persist.requisition.Requisition)3 CIMObject (org.sblim.wbem.cim.CIMObject)3 CustomFieldDef (com.vmware.vim25.CustomFieldDef)2 CustomFieldStringValue (com.vmware.vim25.CustomFieldStringValue)2 CustomFieldValue (com.vmware.vim25.CustomFieldValue)2 Datastore (com.vmware.vim25.mo.Datastore)2