Search in sources :

Example 91 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class FtpMonitor method poll.

// read()
/**
     * {@inheritDoc}
     *
     * Poll the specified address for FTP service availability.
     *
     * During the poll an attempt is made to connect on the specified port (by
     * default TCP port 21). If the connection request is successful, the banner
     * line generated by the interface is parsed and if the extracted return
     * code indicates that we are talking to an FTP server we continue. Next, an
     * FTP 'QUIT' command is sent. Provided that the interface's response is
     * valid we set the service status to SERVICE_AVAILABLE and return.
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Get the parameters
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
    String userid = ParameterMap.getKeyedString(parameters, "userid", null);
    String password = ParameterMap.getKeyedString(parameters, "password", null);
    // Extract the address
    InetAddress ipAddr = svc.getAddress();
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        LOG.debug("FtpMonitor.poll: Polling interface: {} {}", InetAddressUtils.str(ipAddr), tracker);
        Socket socket = null;
        try {
            // create a connected socket
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("FtpMonitor: connected to host: {} on port: {}", ipAddr, port);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            BufferedReader lineRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            FtpResponse bannerResponse = FtpResponse.readResponse(lineRdr);
            if (bannerResponse.isSuccess()) {
                // Attempt to login if userid and password available
                boolean loggedInSuccessfully = false;
                LOG.debug("FtpMonitor: Banner response successful.");
                if (userid == null || userid.length() == 0 || password == null || password.length() == 0) {
                    loggedInSuccessfully = true;
                } else {
                    FtpResponse.sendCommand(socket, "USER " + userid);
                    FtpResponse userResponse = FtpResponse.readResponse(lineRdr);
                    if (userResponse.isSuccess() || userResponse.isIntermediate()) {
                        LOG.debug("FtpMonitor: User response successful.");
                        FtpResponse.sendCommand(socket, "PASS " + password);
                        FtpResponse passResponse = FtpResponse.readResponse(lineRdr);
                        if (passResponse.isSuccess()) {
                            LOG.debug("FtpMonitor.poll: Login successful, parsed return code: {}", passResponse.getCode());
                            loggedInSuccessfully = true;
                        } else {
                            LOG.debug("FtpMonitor.poll: Login failed, parsed return code: {}, full response: {}", passResponse.getCode(), passResponse);
                            loggedInSuccessfully = false;
                        }
                    }
                }
                // Store the response time before we try to quit
                double responseTime = tracker.elapsedTimeInMillis();
                if (loggedInSuccessfully) {
                    FtpResponse.sendCommand(socket, "QUIT");
                    FtpResponse quitResponse = FtpResponse.readResponse(lineRdr);
                    /*
                         * Special Cases for success:
                         * 
                         * Also want to accept the following
                         * ERROR message generated by some FTP servers
                         * following a QUIT command without a previous
                         * successful login:
                         *
                         * "530 QUIT : User not logged in. Please login with
                         * USER and PASS first."
                         * 
                         * Also want to accept the following ERROR
                         * message generated by some FTP servers following a
                         * QUIT command without a previously successful login:
                         *
                         * "425 Session is disconnected."
                         */
                    if (quitResponse.isSuccess() || (quitResponse.getCode() == 530) || (quitResponse.getCode() == 425)) {
                        serviceStatus = PollStatus.available(responseTime);
                    }
                }
            }
            /*
                 * If we get this far and the status has not been set
                 * to available, then something didn't verify during
                 * the banner checking or login/QUIT command process.
                 */
            if (!serviceStatus.isAvailable()) {
                serviceStatus = PollStatus.unavailable();
            }
        } catch (NumberFormatException e) {
            String reason = "NumberFormatException while polling address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (InterruptedIOException e) {
            String reason = "did not connect to host with " + tracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (ConnectException e) {
            String reason = "Connection exception for address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                // Close the socket
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                LOG.debug("FtpMonitor.poll: Error closing socket", e);
            }
        }
    }
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) PollStatus(org.opennms.netmgt.poller.PollStatus) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) NoRouteToHostException(java.net.NoRouteToHostException) FtpResponse(org.opennms.netmgt.poller.monitors.support.FtpResponse) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) BufferedReader(java.io.BufferedReader) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 92 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class GpMonitor method poll.

// read()
/**
     * {@inheritDoc}
     *
     * Poll the specified address for service availability.
     *
     * During the poll an attempt is made to call the specified external script
     * or program. If the connection request is successful, the banner line
     * returned as standard output by the script or program is parsed for a
     * partial match with the banner string specified in the poller
     * configuration. Provided that the script's response is valid we set the
     * service status to SERVICE_AVAILABLE and return.
     *
     * The timeout is handled by ExecRunner and is also passed as a parameter to
     * the script or program being called.
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    LOG.warn("GpMonitor: This poller monitor is deprecated in favor of SystemExecuteMonitor. GpMonitor will be removed in a future release.");
    //
    // Process parameters
    //
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    String hoption = ParameterMap.getKeyedString(parameters, "hoption", "--hostname");
    String toption = ParameterMap.getKeyedString(parameters, "toption", "--timeout");
    //
    // convert timeout to seconds for ExecRunner
    //
    String args = ParameterMap.getKeyedString(parameters, "args", null);
    // Script
    //
    String script = ParameterMap.getKeyedString(parameters, "script", null);
    if (script == null) {
        throw new RuntimeException("GpMonitor: required parameter 'script' is not present in supplied properties.");
    }
    // BannerMatch
    //
    String strBannerMatch = (String) parameters.get("banner");
    // Script standard output
    //
    String scriptoutput = "";
    // Script error output
    //
    String scripterror = "";
    // Get the address instance.
    //
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, script = {}, arguments = {}, {}", hostAddress, script, args, tracker);
    // Give it a whirl
    //
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        try {
            tracker.startAttempt();
            int exitStatus = 100;
            // Some scripts, such as Nagios check scripts, look for -H and -t versus --hostname and 
            // --timeout. If the optional parameter option-type is set to short, then the former
            // will be used.
            int timeoutInSeconds = (int) tracker.getTimeoutInSeconds();
            ExecRunner er = new ExecRunner();
            er.setMaxRunTimeSecs(timeoutInSeconds);
            if (args == null)
                exitStatus = er.exec(script + " " + hoption + " " + hostAddress + " " + toption + " " + timeoutInSeconds);
            else
                exitStatus = er.exec(script + " " + hoption + " " + hostAddress + " " + toption + " " + timeoutInSeconds + " " + args);
            double responseTime = tracker.elapsedTimeInMillis();
            if (exitStatus != 0) {
                scriptoutput = er.getOutString();
                String reason = script + " failed with exit code " + exitStatus + ". Standard out: " + scriptoutput;
                LOG.debug(reason);
                serviceStatus = PollStatus.unavailable(reason);
            }
            if (er.isMaxRunTimeExceeded()) {
                String reason = script + " failed. Timeout exceeded";
                LOG.debug(reason);
                serviceStatus = PollStatus.unavailable(reason);
            } else {
                if (exitStatus == 0) {
                    scriptoutput = er.getOutString();
                    scripterror = er.getErrString();
                    if (!scriptoutput.equals(""))
                        LOG.debug("{} output  = {}", script, scriptoutput);
                    else
                        LOG.debug("{} returned no output", script);
                    if (!scripterror.equals(""))
                        LOG.debug("{} error = {}", script, scripterror);
                    if (strBannerMatch == null || strBannerMatch.equals("*")) {
                        serviceStatus = PollStatus.available(responseTime);
                    } else {
                        if (scriptoutput.indexOf(strBannerMatch) > -1) {
                            serviceStatus = PollStatus.available(responseTime);
                        } else {
                            serviceStatus = PollStatus.unavailable(script + "banner not contained in output banner='" + strBannerMatch + "' output='" + scriptoutput + "'");
                        }
                    }
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            String reason = script + " ArrayIndexOutOfBoundsException";
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException occurred. Check for proper operation of " + script;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (Throwable e) {
            String reason = script + "Exception occurred";
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        }
    }
    //
    // return the status of the service
    //
    LOG.debug("poll: GP - serviceStatus= {} {}", serviceStatus, hostAddress);
    return serviceStatus;
}
Also used : ExecRunner(org.opennms.core.utils.ExecRunner) PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 93 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class JDBCMonitor method poll.

/**
	 * {@inheritDoc}
	 *
	 * Network interface to poll for a given service. Make sure you're using the
	 * latest (at least 5.5) <a
	 * href="http://www.sybase.com/detail_list/1,6902,2912,00.html">JConnect
	 * version </a> or the plugin will not be able to tell exactly if the
	 * service is up or not.
	 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_AVAILABLE
	 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNAVAILABLE
	 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNRESPONSIVE
	 * @see <a
	 *      href="http://manuals.sybase.com/onlinebooks/group-jc/jcg0550e/prjdbc/@Generic__BookTextView/9332;pt=1016#X">Error
	 *      codes for JConnect </a>
	 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Assume that the service is down
    PollStatus status = PollStatus.unavailable();
    Driver driver = null;
    Connection con = null;
    Statement statement = null;
    ResultSet resultset = null;
    if (parameters == null) {
        throw new NullPointerException("parameter cannot be null");
    }
    String driverClass = ParameterMap.getKeyedString(parameters, "driver", DBTools.DEFAULT_JDBC_DRIVER);
    try {
        driver = (Driver) Class.forName(driverClass).newInstance();
        LOG.debug("Loaded JDBC driver: {}", driverClass);
    } catch (Throwable exp) {
        throw new RuntimeException("Unable to load driver class: " + exp.toString(), exp);
    }
    LOG.info("Loaded JDBC driver");
    // Get the JDBC url host part
    InetAddress ipAddr = svc.getAddress();
    String url = null;
    url = DBTools.constructUrl(ParameterMap.getKeyedString(parameters, "url", DBTools.DEFAULT_URL), ipAddr.getCanonicalHostName());
    LOG.debug("JDBC url: {}", url);
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    String db_user = ParameterMap.getKeyedString(parameters, "user", DBTools.DEFAULT_DATABASE_USER);
    String db_pass = ParameterMap.getKeyedString(parameters, "password", DBTools.DEFAULT_DATABASE_PASSWORD);
    Properties props = new Properties();
    props.setProperty("user", db_user);
    props.setProperty("password", db_pass);
    props.setProperty("timeout", String.valueOf(tracker.getTimeoutInSeconds()));
    for (tracker.reset(); tracker.shouldRetry(); tracker.nextAttempt()) {
        try {
            con = driver.connect(url, props);
            // We are connected, upgrade the status to unresponsive
            status = PollStatus.unresponsive();
            if (con == null) {
                LOG.error("Wrong kind of JDBC driver ({}) to connect to the JDBC URL: {}", driverClass, url);
                status = PollStatus.unavailable("Wrong kind of JDBC driver to connect to the JDBC URL");
                break;
            } else {
                LOG.debug("JDBC Connection Established");
                tracker.startAttempt();
                status = checkDatabaseStatus(con, parameters);
                if (status.isAvailable()) {
                    double responseTime = tracker.elapsedTimeInMillis();
                    status = PollStatus.available(responseTime);
                    LOG.debug("JDBC service is AVAILABLE on: {}", ipAddr.getCanonicalHostName());
                    LOG.debug("poll: responseTime= {}ms", responseTime);
                    break;
                }
            }
        // end if con
        } catch (SQLException sqlEx) {
            String reason = "JDBC service is not responding on: " + ipAddr.getCanonicalHostName() + ", " + sqlEx.getSQLState() + ", " + sqlEx.toString();
            LOG.debug(reason, sqlEx);
            status = PollStatus.unavailable(reason);
        } finally {
            closeResultSet(resultset);
            closeStmt(statement);
            closeConnection(con);
        }
    }
    return status;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) Driver(java.sql.Driver) Properties(java.util.Properties) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) ResultSet(java.sql.ResultSet) InetAddress(java.net.InetAddress)

Example 94 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class JDBCMonitor method checkDatabaseStatus.

/**
	 * <p>checkDatabaseStatus</p>
	 *
	 * @param con a {@link java.sql.Connection} object.
	 * @param parameters a {@link java.util.Map} object.
	 * @return a {@link org.opennms.netmgt.poller.PollStatus} object.
	 */
public PollStatus checkDatabaseStatus(Connection con, Map<String, Object> parameters) {
    PollStatus status = PollStatus.unavailable("Unable to retrieve database catalogs");
    ResultSet resultset = null;
    try {
        // We are connected, upgrade the status to unresponsive
        status = PollStatus.unresponsive();
        DatabaseMetaData metadata = con.getMetaData();
        resultset = metadata.getCatalogs();
        while (resultset.next()) {
            resultset.getString(1);
        }
        // The query worked, assume than the server is ok
        if (resultset != null) {
            status = PollStatus.available();
        }
    } catch (SQLException sqlEx) {
        String reason = "JDBC service failed to retrieve metadata: " + sqlEx.getSQLState() + ", " + sqlEx.toString();
        LOG.debug(reason, sqlEx);
        status = PollStatus.unavailable(reason);
    } finally {
        closeResultSet(resultset);
    }
    return status;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 95 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class JDBCStoredProcedureMonitor method checkDatabaseStatus.

/** {@inheritDoc} */
@Override
public PollStatus checkDatabaseStatus(Connection con, Map<String, Object> parameters) {
    PollStatus status = PollStatus.unavailable();
    CallableStatement cs = null;
    try {
        boolean bPass = false;
        String storedProcedure = ParameterMap.getKeyedString(parameters, "stored-procedure", null);
        if (storedProcedure == null)
            return status;
        String schemaName = ParameterMap.getKeyedString(parameters, "schema", "test");
        String procedureCall = "{ ? = call " + schemaName + "." + storedProcedure + "()}";
        cs = con.prepareCall(procedureCall);
        LOG.debug("Calling stored procedure: {}", procedureCall);
        cs.registerOutParameter(1, java.sql.Types.BIT);
        cs.executeUpdate();
        bPass = cs.getBoolean(1);
        LOG.debug("Stored procedure returned: {}", bPass);
        // If the query worked, assume than the server is ok
        if (bPass) {
            status = PollStatus.available();
        }
    } catch (SQLException sqlEx) {
        String reason = "JDBC stored procedure call not functional: " + sqlEx.getSQLState() + ", " + sqlEx.toString();
        LOG.debug(reason, sqlEx);
        status = PollStatus.unavailable(reason);
    } finally {
        closeStmt(cs);
    }
    return status;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) SQLException(java.sql.SQLException) CallableStatement(java.sql.CallableStatement)

Aggregations

PollStatus (org.opennms.netmgt.poller.PollStatus)200 Test (org.junit.Test)92 MonitoredService (org.opennms.netmgt.poller.MonitoredService)51 ServiceMonitor (org.opennms.netmgt.poller.ServiceMonitor)47 InetAddress (java.net.InetAddress)39 MockMonitoredService (org.opennms.netmgt.poller.mock.MockMonitoredService)36 HashMap (java.util.HashMap)35 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)29 ConcurrentSkipListMap (java.util.concurrent.ConcurrentSkipListMap)28 JUnitHttpServer (org.opennms.core.test.http.annotations.JUnitHttpServer)18 IOException (java.io.IOException)17 Socket (java.net.Socket)17 InputStreamReader (java.io.InputStreamReader)16 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)14 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)14 BufferedReader (java.io.BufferedReader)13 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)12 InterruptedIOException (java.io.InterruptedIOException)11 ConnectException (java.net.ConnectException)11 NoRouteToHostException (java.net.NoRouteToHostException)11