Search in sources :

Example 1 with NsclientPacket

use of org.opennms.protocols.nsclient.NsclientPacket in project opennms by OpenNMS.

the class NsclientMonitor method poll.

/**
     * {@inheritDoc}
     *
     * Poll the specified address for service availability. During the poll an
     * attempt is made to connect on the specified port. If the connection
     * request is successful, the parameters are parsed and turned into
     * <code>NsclientCheckParams</code> and a check is performed against the
     * remote NSClient service. If the <code>NsclientManager</code> responds
     * with a <code>NsclientPacket</code> containing a result code of
     * <code>NsclientPacket.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(MonitoredService svc, Map<String, Object> parameters) {
    // Holds the response reason.
    String reason = null;
    // Used to exit the retry loop early, if possible.
    int serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
    // This will hold the data the server sends back.
    NsclientPacket response = null;
    // Used to track how long the request took.
    Double responseTime = null;
    // NSClient related parameters.
    String command = ParameterMap.getKeyedString(parameters, "command", NsclientManager.convertTypeToString(NsclientManager.CHECK_CLIENTVERSION));
    int port = ParameterMap.getKeyedInteger(parameters, "port", NsclientManager.DEFAULT_PORT);
    String password = ParameterMap.getKeyedString(parameters, "password", NSClientAgentConfig.DEFAULT_PASSWORD);
    String params = ParameterMap.getKeyedString(parameters, "parameter", null);
    int critPerc = ParameterMap.getKeyedInteger(parameters, "criticalPercent", 0);
    int warnPerc = ParameterMap.getKeyedInteger(parameters, "warningPercent", 0);
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Get the address we're going to poll.
    InetAddress ipAddr = svc.getAddress();
    for (tracker.reset(); tracker.shouldRetry() && serviceStatus != PollStatus.SERVICE_AVAILABLE; tracker.nextAttempt()) {
        try {
            tracker.startAttempt();
            // Create a client, set up details and connect.
            NsclientManager client = new NsclientManager(InetAddressUtils.str(ipAddr), port, password);
            client.setTimeout(tracker.getSoTimeout());
            client.setPassword(password);
            client.init();
            // Set up the parameters the client will use to validate the
            // response.
            NsclientCheckParams clientParams = new NsclientCheckParams(critPerc, warnPerc, params);
            // Send the request to the server and receive the response.
            response = client.processCheckCommand(NsclientManager.convertStringToType(command), clientParams);
            // Now save the time it took to process the check command.
            responseTime = tracker.elapsedTimeInMillis();
            if (response == null) {
                continue;
            }
            if (response.getResultCode() == NsclientPacket.RES_STATE_OK) {
                serviceStatus = PollStatus.SERVICE_AVAILABLE;
                reason = response.getResponse();
            } else if (response.getResultCode() == NsclientPacket.RES_STATE_CRIT) {
                serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
                reason = response.getResponse();
                // set this to null so we don't try to save data when the node is down
                responseTime = null;
            }
        } catch (NsclientException e) {
            LOG.debug("Nsclient Poller received exception from client", e);
            reason = "NsclientException: " + e.getMessage();
        }
    }
    // end for(;;)
    return PollStatus.get(serviceStatus, reason, responseTime);
}
Also used : NsclientPacket(org.opennms.protocols.nsclient.NsclientPacket) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) NsclientCheckParams(org.opennms.protocols.nsclient.NsclientCheckParams) NsclientException(org.opennms.protocols.nsclient.NsclientException) NsclientManager(org.opennms.protocols.nsclient.NsclientManager) InetAddress(java.net.InetAddress)

Example 2 with NsclientPacket

use of org.opennms.protocols.nsclient.NsclientPacket in project opennms by OpenNMS.

the class NsclientClient method sendRequest.

@Override
public NsclientPacket sendRequest(NsclientRequest request) throws IOException, Exception {
    boolean isAServer = false;
    NsclientPacket response = null;
    for (int attempts = 0; attempts <= request.getRetries() && !isAServer; attempts++) {
        try {
            response = client.processCheckCommand(request.getFormattedCommand(), request.getCheckParams());
            LOG.debug("sendRequest: {}: {}", request.getFormattedCommand(), response.getResponse());
            isAServer = true;
        } catch (NsclientException e) {
            StringBuffer message = new StringBuffer();
            message.append("sendRequest: Check failed... NsclientManager returned exception: ");
            message.append(e.getMessage());
            message.append(" : ");
            message.append((e.getCause() == null ? "" : e.getCause().getMessage()));
            LOG.info(message.toString());
            isAServer = false;
        }
    }
    return response;
}
Also used : NsclientPacket(org.opennms.protocols.nsclient.NsclientPacket) NsclientException(org.opennms.protocols.nsclient.NsclientException)

Example 3 with NsclientPacket

use of org.opennms.protocols.nsclient.NsclientPacket in project opennms by OpenNMS.

the class NSClientCollector method collect.

/** {@inheritDoc} */
@Override
public CollectionSet collect(CollectionAgent agent, Map<String, Object> parameters) {
    CollectionSetBuilder builder = new CollectionSetBuilder(agent);
    builder.withStatus(CollectionStatus.FAILED);
    // Find attributes to collect - check groups in configuration. For each,
    // check scheduled nodes to see if that group should be collected
    NsclientCollection collection = (NsclientCollection) parameters.get(NSCLIENT_COLLECTION_KEY);
    NSClientAgentConfig agentConfig = (NSClientAgentConfig) parameters.get(NSCLIENT_AGENT_CONFIG_KEY);
    NSClientAgentState agentState = new NSClientAgentState(agent.getAddress(), parameters, agentConfig);
    if (collection.getWpms().getWpm().size() < 1) {
        LOG.info("No groups to collect.");
        builder.withStatus(CollectionStatus.SUCCEEDED);
        return builder.build();
    }
    // All node resources for NSClient; nothing of interface or "indexed resource" type
    NodeLevelResource nodeResource = new NodeLevelResource(agent.getNodeId());
    for (Wpm wpm : collection.getWpms().getWpm()) {
        // A wpm consists of a list of attributes, identified by name
        if (agentState.shouldCheckAvailability(wpm.getName(), wpm.getRecheckInterval())) {
            LOG.debug("Checking availability of group {}", wpm.getName());
            NsclientManager manager = null;
            try {
                manager = agentState.getManager();
                manager.init();
                NsclientCheckParams params = new NsclientCheckParams(wpm.getKeyvalue());
                NsclientPacket result = manager.processCheckCommand(NsclientManager.CHECK_COUNTER, params);
                manager.close();
                boolean isAvailable = (result.getResultCode() == NsclientPacket.RES_STATE_OK);
                agentState.setGroupIsAvailable(wpm.getName(), isAvailable);
                LOG.debug("Group {} is {}available ", wpm.getName(), (isAvailable ? "" : "not"));
            } catch (NsclientException e) {
                LOG.error("Error checking group ({}) availability", wpm.getName(), e);
                agentState.setGroupIsAvailable(wpm.getName(), false);
            } finally {
                if (manager != null) {
                    manager.close();
                }
            }
        }
        if (agentState.groupIsAvailable(wpm.getName())) {
            // Collect the data
            try {
                NsclientManager manager = agentState.getManager();
                // Open the connection, then do each
                manager.init();
                for (Attrib attrib : wpm.getAttrib()) {
                    NsclientPacket result = null;
                    try {
                        NsclientCheckParams params = new NsclientCheckParams(attrib.getName());
                        result = manager.processCheckCommand(NsclientManager.CHECK_COUNTER, params);
                    } catch (NsclientException e) {
                        LOG.info("unable to collect params for attribute '{}'", attrib.getName(), e);
                    }
                    if (result != null) {
                        if (result.getResultCode() != NsclientPacket.RES_STATE_OK) {
                            LOG.info("not writing parameters for attribute '{}', state is not 'OK'", attrib.getName());
                        } else {
                            // Only numeric data comes back from NSClient in data collection
                            builder.withNumericAttribute(nodeResource, wpm.getName(), attrib.getAlias(), NumericAttributeUtils.parseNumericValue(result.getResponse()), attrib.getType());
                        }
                    }
                }
                builder.withStatus(CollectionStatus.SUCCEEDED);
                // Only close once all the attribs have
                manager.close();
            // been done (optimizing as much as
            // possible with NSClient)
            } catch (NsclientException e) {
                LOG.error("Error collecting data", e);
            }
        }
    }
    return builder.build();
}
Also used : NSClientAgentConfig(org.opennms.protocols.nsclient.NSClientAgentConfig) NsclientPacket(org.opennms.protocols.nsclient.NsclientPacket) CollectionSetBuilder(org.opennms.netmgt.collection.support.builder.CollectionSetBuilder) Wpm(org.opennms.netmgt.config.datacollction.nsclient.Wpm) NsclientCheckParams(org.opennms.protocols.nsclient.NsclientCheckParams) NsclientException(org.opennms.protocols.nsclient.NsclientException) NsclientCollection(org.opennms.netmgt.config.datacollction.nsclient.NsclientCollection) NodeLevelResource(org.opennms.netmgt.collection.support.builder.NodeLevelResource) NsclientManager(org.opennms.protocols.nsclient.NsclientManager) Attrib(org.opennms.netmgt.config.datacollction.nsclient.Attrib)

Aggregations

NsclientException (org.opennms.protocols.nsclient.NsclientException)3 NsclientPacket (org.opennms.protocols.nsclient.NsclientPacket)3 NsclientCheckParams (org.opennms.protocols.nsclient.NsclientCheckParams)2 NsclientManager (org.opennms.protocols.nsclient.NsclientManager)2 InetAddress (java.net.InetAddress)1 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)1 CollectionSetBuilder (org.opennms.netmgt.collection.support.builder.CollectionSetBuilder)1 NodeLevelResource (org.opennms.netmgt.collection.support.builder.NodeLevelResource)1 Attrib (org.opennms.netmgt.config.datacollction.nsclient.Attrib)1 NsclientCollection (org.opennms.netmgt.config.datacollction.nsclient.NsclientCollection)1 Wpm (org.opennms.netmgt.config.datacollction.nsclient.Wpm)1 NSClientAgentConfig (org.opennms.protocols.nsclient.NSClientAgentConfig)1