Search in sources :

Example 6 with WmiManager

use of org.opennms.protocols.wmi.WmiManager in project opennms by OpenNMS.

the class WmiMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for service availability. During the poll an
 * attempt is made to connect the WMI agent on the specified host. If the
 * connection request is successful, the parameters are parsed and turned
 * into <code>WmiParams</code> and a check is performed against the
 * remote WMI service. If the <code>WmiManager</code> responds
 * with a <code>WmiResult</code> containing a result code of
 * <code>WmiResult.RES_STATE_OK</code> then we have determined that
 * we are talking to a valid service and we set the service status to
 * SERVICE_AVAILABLE and return.
 */
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
    // Holds the response reason.
    String reason = null;
    // Used to exit the retry loop early, if possible.
    int serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
    // This will hold the data the server sends back.
    WmiResult response = null;
    // Used to track how long the request took.
    Double responseTime = null;
    final InetAddress ipAddr = svc.getAddress();
    final WmiAgentConfig agentConfig = WmiPeerFactory.getInstance().getAgentConfig(ipAddr);
    String matchType = DEFAULT_WMI_MATCH_TYPE;
    String compVal = DEFAULT_WMI_COMP_VAL;
    String compOp = DEFAULT_WMI_COMP_OP;
    String wmiClass = DEFAULT_WMI_CLASS;
    String wmiObject = DEFAULT_WMI_OBJECT;
    String wmiWqlStr = DEFAULT_WMI_WQL;
    String wmiNamespace = DEFAULT_WMI_NAMESPACE;
    if (parameters != null) {
        if (parameters.get("timeout") != null) {
            int timeout = ParameterMap.getKeyedInteger(parameters, "timeout", agentConfig.getTimeout());
            agentConfig.setTimeout(timeout);
        }
        if (parameters.get("retry") != null) {
            int retries = ParameterMap.getKeyedInteger(parameters, "retry", agentConfig.getRetries());
            agentConfig.setRetries(retries);
        }
        if (parameters.get("username") != null) {
            String user = ParameterMap.getKeyedString(parameters, "username", agentConfig.getUsername());
            agentConfig.setUsername(user);
        }
        if (parameters.get("password") != null) {
            String pass = ParameterMap.getKeyedString(parameters, "password", agentConfig.getPassword());
            agentConfig.setUsername(pass);
        }
        if (parameters.get("domain") != null) {
            String domain = ParameterMap.getKeyedString(parameters, "domain", agentConfig.getDomain());
            agentConfig.setUsername(domain);
        }
        if (parameters.get("namespace") != null) {
            wmiNamespace = ParameterMap.getKeyedString(parameters, "wmiNamespace", ParameterMap.getKeyedString(parameters, "namespace", DEFAULT_WMI_NAMESPACE));
        }
        matchType = ParameterMap.getKeyedString(parameters, "matchType", DEFAULT_WMI_MATCH_TYPE);
        compVal = ParameterMap.getKeyedString(parameters, "compareValue", DEFAULT_WMI_COMP_VAL);
        compOp = ParameterMap.getKeyedString(parameters, "compareOp", DEFAULT_WMI_COMP_OP);
        wmiWqlStr = ParameterMap.getKeyedString(parameters, "wql", DEFAULT_WMI_WQL);
        wmiClass = ParameterMap.getKeyedString(parameters, "wmiClass", DEFAULT_WMI_CLASS);
        wmiObject = ParameterMap.getKeyedString(parameters, "wmiObject", DEFAULT_WMI_OBJECT);
    }
    final TimeoutTracker tracker = new TimeoutTracker(parameters, agentConfig.getRetries(), agentConfig.getTimeout());
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, user = {}, {}", hostAddress, agentConfig.getUsername(), tracker);
    WmiManager mgr = null;
    for (tracker.reset(); tracker.shouldRetry() && serviceStatus != PollStatus.SERVICE_AVAILABLE; tracker.nextAttempt()) {
        try {
            tracker.startAttempt();
            LOG.debug("poll: creating WmiManager object.");
            // Create a client, set up details and connect.
            mgr = new WmiManager(hostAddress, agentConfig.getUsername(), agentConfig.getPassword(), agentConfig.getDomain(), matchType);
            mgr.setTimeout(tracker.getSoTimeout());
            mgr.setNamespace(wmiNamespace);
            mgr.init();
            LOG.debug("Completed initializing WmiManager object.");
            // We are connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
            // Set up the parameters the client will use to validate the response.
            // Note: We will check and see if we were provided with a WQL string.
            WmiParams clientParams = null;
            if (DEFAULT_WMI_WQL.equals(wmiWqlStr)) {
                clientParams = new WmiParams(WmiParams.WMI_OPERATION_INSTANCEOF, compVal, compOp, wmiClass, wmiObject);
                LOG.debug("Attempting to perform operation: \\\\{}\\{}", wmiClass, wmiObject);
            } else {
                // Create parameters to run a WQL query.
                clientParams = new WmiParams(WmiParams.WMI_OPERATION_WQL, compVal, compOp, wmiWqlStr, wmiObject);
                LOG.debug("Attempting to perform operation: {}", wmiWqlStr);
            }
            // Send the request to the server and receive the response..
            response = mgr.performOp(clientParams);
            LOG.debug("Received result: {}", response);
            // Now save the time it took to process the check command.
            responseTime = tracker.elapsedTimeInMillis();
            if (response == null) {
                continue;
            }
            final List<Object> wmiObjects = response.getResponse();
            final StringBuilder reasonBuffer = new StringBuilder();
            reasonBuffer.append("Constraint '").append(matchType).append(" ").append(clientParams.getCompareOperation()).append(" ").append(clientParams.getCompareValue()).append("' failed for value of ");
            // If there's no WQL string then use the class\object name as the result message
            if (DEFAULT_WMI_WQL.equals(wmiWqlStr)) {
                reasonBuffer.append(wmiClass).append("\\").append(wmiObject);
            } else {
                // Otherwise, print the WQL statement in the result message
                reasonBuffer.append("\"").append(wmiWqlStr).append("\"");
            }
            if (response.getResultCode() == WmiResult.RES_STATE_OK) {
                serviceStatus = PollStatus.SERVICE_AVAILABLE;
                reasonBuffer.append(": ").append(wmiObjects.get(0));
            } else if (response.getResultCode() == WmiResult.RES_STATE_CRIT) {
                serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
                // set this to null so we don't try to save data when the node is down
                responseTime = null;
            }
            reason = reasonBuffer.toString();
        } catch (final WmiException e) {
            LOG.debug("WMI Poller received exception from client.", e);
            reason = "WmiException: " + e.getMessage();
        } finally {
            if (mgr != null) {
                try {
                    mgr.close();
                } catch (WmiException e) {
                    LOG.warn("An error occurred closing the WMI Manager.", e);
                }
            }
        }
    }
    // end for(;;)
    return PollStatus.get(serviceStatus, reason, responseTime);
}
Also used : WmiAgentConfig(org.opennms.netmgt.config.wmi.WmiAgentConfig) WmiManager(org.opennms.protocols.wmi.WmiManager) WmiResult(org.opennms.protocols.wmi.WmiResult) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) WmiParams(org.opennms.protocols.wmi.WmiParams) WmiException(org.opennms.protocols.wmi.WmiException) InetAddress(java.net.InetAddress)

Example 7 with WmiManager

use of org.opennms.protocols.wmi.WmiManager in project opennms by OpenNMS.

the class WmiDetector method isServer.

private WmiResult isServer(InetAddress host, String user, String pass, String domain, String namespace, String matchType, int retries, int timeout, WmiParams params) {
    boolean isAServer = false;
    WmiResult result = null;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
        WmiManager mgr = null;
        try {
            mgr = new WmiManager(InetAddressUtils.str(host), user, pass, domain, matchType);
            mgr.setNamespace(namespace);
            // Connect to the WMI server.
            mgr.init();
            // Perform the operation specified in the parameters.
            result = mgr.performOp(params);
            if (params.getWmiOperation().equals(WmiParams.WMI_OPERATION_WQL)) {
                LOG.debug("WmiPlugin: {} : {}", params.getWql(), WmiResult.convertStateToString(result.getResultCode()));
            } else {
                LOG.debug("WmiPlugin: \\\\{}\\{} : {}", params.getWmiClass(), params.getWmiObject(), WmiResult.convertStateToString(result.getResultCode()));
            }
            isAServer = true;
        } catch (WmiException e) {
            final StringBuilder message = new StringBuilder();
            message.append("WmiPlugin: Check failed... : ");
            message.append(e.getMessage());
            message.append(" : ");
            message.append((e.getCause() == null ? "" : e.getCause().getMessage()));
            LOG.info(message.toString());
            isAServer = false;
        } finally {
            if (mgr != null) {
                try {
                    mgr.close();
                } catch (WmiException e) {
                    LOG.warn("an error occurred closing the WMI Manager", e);
                }
            }
        }
    }
    return result;
}
Also used : WmiResult(org.opennms.protocols.wmi.WmiResult) WmiException(org.opennms.protocols.wmi.WmiException) WmiManager(org.opennms.protocols.wmi.WmiManager)

Example 8 with WmiManager

use of org.opennms.protocols.wmi.WmiManager in project opennms by OpenNMS.

the class WmiManagerTest method testCloseWithInvalidSession.

/**
 * Test an attempt to close the client before the client has been
 * initialized. This should throw a new exception stating that WmiClient
 * hasn't been properly initialized.
 *
 * Test method for {@link org.opennms.protocols.wmi.WmiManager#close()}.
 *
 * @throws WmiException if there is a problem with the mock object.
 */
public final void testCloseWithInvalidSession() throws WmiException {
    // Set up WMI mock client.
    replay(m_WmiMock);
    try {
        // Create a manager.
        WmiManager wmiManager = new WmiManager("127.0.0.1", "Administrator", "password");
        // Disconnect without initializing/connecting.
        wmiManager.close();
    } catch (WmiException e) {
        assertTrue("Exception missing message: WmiClient was not initialized: " + e, e.getMessage().contains("WmiClient was not initialized"));
    }
    verify(m_WmiMock);
    reset(m_WmiMock);
}
Also used : WmiException(org.opennms.protocols.wmi.WmiException) WmiManager(org.opennms.protocols.wmi.WmiManager)

Example 9 with WmiManager

use of org.opennms.protocols.wmi.WmiManager in project opennms by OpenNMS.

the class WmiManagerTest method testPerformOpInvalidClass.

/**
 * Test the performOp method with an invalid WMI class and valid WMI object.
 *
 * Test method for
 * {@link org.opennms.protocols.wmi.WmiManager#performOp(org.opennms.protocols.wmi.WmiParams)}.
 *
 * @throws WmiException if there is a problem with the mock object.
 */
public final void testPerformOpInvalidClass() throws WmiException {
    // Create parameter holder.
    WmiParams params = new WmiParams(WmiParams.WMI_OPERATION_INSTANCEOF, "2/12/2004 00:00:00", "EQ", "Win32_BISO", "ReleaseDate");
    // Set up WMI mock client.
    // 1) Expect a call to connect() with a bad hostname.
    // 2) Throw a new WmiException indictating a bad hostname.
    m_WmiMock.connect("127.0.0.1", "Administrator", "password", WmiParams.WMI_DEFAULT_NAMESPACE);
    m_WmiMock.performInstanceOf("Win32_BISO");
    expectLastCall().andThrow(new WmiException("Failed to perform WMI operation: Exception occurred.  [0x80020009] ==> Message from Server: SWbemServicesEx Invalid class"));
    replay(m_WmiMock);
    try {
        // Create a manager.
        WmiManager wmiManager = new WmiManager("127.0.0.1", "Administrator", "password");
        // Initialize
        wmiManager.init(m_WmiMock);
        // Perform an operation.
        wmiManager.performOp(params);
    } catch (WmiException e) {
        assertTrue("Exception missing message: SWbemServicesEx Invalid class: " + e, e.getMessage().contains("SWbemServicesEx Invalid class"));
    }
    verify(m_WmiMock);
    reset(m_WmiMock);
}
Also used : WmiParams(org.opennms.protocols.wmi.WmiParams) WmiException(org.opennms.protocols.wmi.WmiException) WmiManager(org.opennms.protocols.wmi.WmiManager)

Example 10 with WmiManager

use of org.opennms.protocols.wmi.WmiManager in project opennms by OpenNMS.

the class WmiManagerTest method testInit.

/**
 * Test a standard client connect.
 *
 * Test method for {@link org.opennms.protocols.wmi.WmiManager#init()}.
 *
 * @throws WmiException if there are any problems with the WmiManager
 */
public final void testInit() throws WmiException {
    // Set up WMI mock client.
    m_WmiMock.connect("127.0.0.1", "Administrator", "password", WmiParams.WMI_DEFAULT_NAMESPACE);
    replay(m_WmiMock);
    // Create a manager.
    WmiManager wmiManager = new WmiManager("127.0.0.1", "Administrator", "password");
    // Initialize
    wmiManager.init(m_WmiMock);
    reset(m_WmiMock);
}
Also used : WmiManager(org.opennms.protocols.wmi.WmiManager)

Aggregations

WmiManager (org.opennms.protocols.wmi.WmiManager)11 WmiException (org.opennms.protocols.wmi.WmiException)9 WmiParams (org.opennms.protocols.wmi.WmiParams)5 WmiResult (org.opennms.protocols.wmi.WmiResult)3 OnmsWbemObjectBiosStub (org.opennms.protocols.wmi.test.stubs.OnmsWbemObjectBiosStub)2 OnmsWbemObjectSetBiosStub (org.opennms.protocols.wmi.test.stubs.OnmsWbemObjectSetBiosStub)2 OnmsWbemPropBiosStub (org.opennms.protocols.wmi.test.stubs.OnmsWbemPropBiosStub)2 OnmsWbemPropSetBiosStub (org.opennms.protocols.wmi.test.stubs.OnmsWbemPropSetBiosStub)2 OnmsWbemObjectSet (org.opennms.protocols.wmi.wbem.OnmsWbemObjectSet)2 InetAddress (java.net.InetAddress)1 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)1 WmiAgentConfig (org.opennms.netmgt.config.wmi.WmiAgentConfig)1