Search in sources :

Example 21 with NoRouteToHostException

use of java.net.NoRouteToHostException in project opennms by OpenNMS.

the class MemcachedMonitor method poll.

/**
     * {@inheritDoc}
     *
     * Poll the specified address for Memcached service availability.
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
    // Extract the address
    InetAddress ipv4Addr = svc.getAddress();
    String host = InetAddressUtils.str(ipv4Addr);
    LOG.debug("polling interface: {} {}", host, timeoutTracker);
    PollStatus serviceStatus = PollStatus.unavailable();
    for (timeoutTracker.reset(); timeoutTracker.shouldRetry() && !serviceStatus.isAvailable(); timeoutTracker.nextAttempt()) {
        Socket socket = null;
        try {
            timeoutTracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipv4Addr, port), timeoutTracker.getConnectionTimeout());
            socket.setSoTimeout(timeoutTracker.getSoTimeout());
            LOG.debug("connected to host: {} on port: {}", host, port);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
            osw.write("stats\n");
            osw.flush();
            // Allocate a line reader
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            Map<String, Number> statProps = new LinkedHashMap<String, Number>();
            for (String key : m_keys) {
                statProps.put(key, null);
            }
            String line = null;
            do {
                line = reader.readLine();
                if (line == null)
                    break;
                String[] statEntry = line.trim().split("\\s", 3);
                if (statEntry[0].equals("STAT")) {
                    try {
                        Number value;
                        if (statEntry[2].contains(".")) {
                            value = Double.parseDouble(statEntry[2]);
                        } else {
                            value = Long.parseLong(statEntry[2]);
                        }
                        String key = statEntry[1].toLowerCase();
                        key = key.replaceAll("_", "");
                        if (key.length() > 19) {
                            key = key.substring(0, 19);
                        }
                        if (statProps.containsKey(key)) {
                            statProps.put(key, value);
                        }
                    } catch (Throwable e) {
                    // ignore errors parsing
                    }
                } else if (statEntry[0].equals("END")) {
                    serviceStatus = PollStatus.available();
                    osw.write("quit\n");
                    osw.flush();
                    break;
                }
            } while (line != null);
            serviceStatus.setProperties(statProps);
            serviceStatus.setResponseTime(timeoutTracker.elapsedTimeInMillis());
        } catch (ConnectException e) {
            // Connection refused!! Continue to retry.
            String reason = "Connection refused by host " + host;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (NoRouteToHostException e) {
            // No route to host!! Try retries anyway in case strict timeouts are enabled
            String reason = "Unable to test host " + host + ", no route available";
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (InterruptedIOException e) {
            String reason = "did not connect to host " + host + " within timeout: " + timeoutTracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "Error communicating with host " + host;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (Throwable t) {
            String reason = "Undeclared throwable exception caught contacting host " + host;
            LOG.debug(reason, t);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
            } catch (IOException 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) LinkedHashMap(java.util.LinkedHashMap) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 22 with NoRouteToHostException

use of java.net.NoRouteToHostException in project opennms by OpenNMS.

the class Pop3Monitor method poll.

/**
     * {@inheritDoc}
     *
     * <P>
     * Poll the specified address for POP3 service availability.
     * </P>
     *
     * <P>
     * During the poll an attempt is made to connect on the specified port (by
     * default TCP port 110). If the connection request is successful, the
     * banner line generated by the interface is parsed and if the response
     * indicates that we are talking to an POP3 server we continue. Next, a POP3
     * 'QUIT' command is sent to the interface. Again the response is parsed and
     * verified. Provided that the interface's response is valid we set the
     * service status to SERVICE_AVAILABLE and return.
     * </P>
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Process parameters
    //
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
    InetAddress ipAddr = svc.getAddress();
    LOG.debug("poll: address = {}, port = {}, {}", ipAddr, port, tracker);
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        Socket socket = null;
        final String hostAddress = InetAddressUtils.str(ipAddr);
        try {
            //
            // create a connected socket
            //
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("Pop3Monitor: connected to host: {} on port: {}", ipAddr, port);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            BufferedReader rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //
            // Tokenize the Banner Line, and check the first
            // line for a valid return.
            //
            // Server response should start with: "+OK"
            //
            String banner = rdr.readLine();
            double responseTime = tracker.elapsedTimeInMillis();
            if (banner == null)
                continue;
            StringTokenizer t = new StringTokenizer(banner);
            if (t.nextToken().equals("+OK")) {
                //
                // POP3 server should recoginize the QUIT command
                //
                String cmd = "QUIT\r\n";
                socket.getOutputStream().write(cmd.getBytes());
                //
                // Parse the response to the QUIT command
                //
                // Server response should start with: "+OK"
                //
                t = new StringTokenizer(rdr.readLine());
                if (t.nextToken().equals("+OK")) {
                    serviceStatus = PollStatus.available(responseTime);
                }
            }
            // the banner checking or QUIT command process.
            if (!serviceStatus.isAvailable()) {
                serviceStatus = PollStatus.unavailable();
            }
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            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 " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                // Close the socket
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                LOG.debug("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) StringTokenizer(java.util.StringTokenizer) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) BufferedReader(java.io.BufferedReader) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 23 with NoRouteToHostException

use of java.net.NoRouteToHostException in project opennms by OpenNMS.

the class ImapMonitor method poll.

/**
     * {@inheritDoc}
     *
     * <P>
     * Poll the specified address for IMAP service availability.
     * </P>
     *
     * <P>
     * During the poll an attempt is made to connect on the specified port (by
     * default TCP port 143). If the connection request is successful, the
     * banner line generated by the interface is parsed and if it starts with a '*
     * OK , it indicates that we are talking to an IMAP server and we continue.
     * Next, a 'LOGOUT' command is sent to the interface. Again the response is
     * parsed and the response is verified to see that we get a '* OK'. If the
     * interface's response is valid we set the service status to
     * SERVICE_AVAILABLE and return.
     * </P>
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Process parameters
    //
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Retries
    //
    final int port = determinePort(parameters);
    // Get interface address from NetworkInterface
    //
    InetAddress ipAddr = svc.getAddress();
    LOG.debug("ImapMonitor.poll: address: {} port: {} {}", ipAddr, port, tracker);
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        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());
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            // For SSL support
            socket = getSocketWrapper().wrapSocket(socket);
            BufferedReader rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //
            // Tokenize the Banner Line, and check the first
            // line for a valid return.
            //
            String banner = rdr.readLine();
            double responseTime = tracker.elapsedTimeInMillis();
            LOG.debug("ImapMonitor.Poll(): banner: {}", banner);
            if (banner != null && banner.startsWith(IMAP_START_RESPONSE_PREFIX)) {
                //
                // Send the LOGOUT
                //
                socket.getOutputStream().write(IMAP_LOGOUT_REQUEST.getBytes());
                //
                // get the returned string, tokenize, and
                // verify the correct output.
                //
                String response = rdr.readLine();
                if (response != null && response.startsWith(IMAP_BYE_RESPONSE_PREFIX)) {
                    response = rdr.readLine();
                    if (response != null && response.startsWith(IMAP_LOGOUT_RESPONSE_PREFIX)) {
                        serviceStatus = PollStatus.available(responseTime);
                    }
                }
            }
            // the banner checking or logout process.
            if (!serviceStatus.isAvailable()) {
                serviceStatus = PollStatus.unavailable();
            }
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address: " + ipAddr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (ConnectException e) {
            // Connection refused. Continue to retry.
            String reason = "Connection 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 (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) {
                e.fillInStackTrace();
                LOG.debug("ImapMonitor.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) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) BufferedReader(java.io.BufferedReader) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 24 with NoRouteToHostException

use of java.net.NoRouteToHostException in project opennms by OpenNMS.

the class TrivialTimeMonitor method pollTimeUdp.

/**
     * <p>pollTimeUdp</p>
     *
     * @param svc a {@link org.opennms.netmgt.poller.MonitoredService} object.
     * @param parameters a {@link java.util.Map} object.
     * @param serviceStatus a {@link org.opennms.netmgt.poller.PollStatus} object.
     * @param tracker a {@link org.opennms.core.utils.TimeoutTracker} object.
     * @param ipv4Addr a {@link java.net.InetAddress} object.
     * @param port a int.
     * @param allowedSkew a int.
     * @param persistSkew a boolean.
     * @return a {@link org.opennms.netmgt.poller.PollStatus} object.
     */
public PollStatus pollTimeUdp(MonitoredService svc, Map<String, Object> parameters, PollStatus serviceStatus, TimeoutTracker tracker, InetAddress ipv4Addr, int port, int allowedSkew, boolean persistSkew) {
    int localTime = 0;
    int remoteTime = 0;
    boolean gotTime = false;
    for (tracker.reset(); tracker.shouldRetry() && !gotTime; tracker.nextAttempt()) {
        DatagramSocket socket = null;
        final String hostAddress = InetAddressUtils.str(ipv4Addr);
        try {
            tracker.startAttempt();
            socket = new DatagramSocket();
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("Requesting time from host: {} on UDP port: {}", ipv4Addr, port);
            //
            // Send an empty datagram per RFC868
            //
            socket.send(new DatagramPacket(new byte[] {}, 0, ipv4Addr, port));
            //
            // Try to receive a response from the remote socket
            //
            byte[] timeBytes = new byte[4];
            ByteBuffer timeByteBuffer = ByteBuffer.wrap(timeBytes);
            DatagramPacket timePacket = new DatagramPacket(timeBytes, timeBytes.length, ipv4Addr, port);
            socket.receive(timePacket);
            int bytesRead = timePacket.getLength();
            if (bytesRead != 4)
                continue;
            LOG.debug("pollTimeUdp: bytes read = {}", bytesRead);
            try {
                remoteTime = timeByteBuffer.getInt();
            } catch (BufferUnderflowException bue) {
                LOG.error("Encountered buffer underflow while reading time from remote socket.");
                remoteTime = 0;
                serviceStatus = PollStatus.unavailable("Failed to read a valid time from remote host.");
                // to next iteration of for() loop
                continue;
            }
            localTime = (int) (System.currentTimeMillis() / 1000) - EPOCH_ADJ_FACTOR;
            gotTime = true;
            serviceStatus = qualifyTime(remoteTime, localTime, allowedSkew, serviceStatus, tracker.elapsedTimeInMillis(), persistSkew);
        } catch (PortUnreachableException e) {
            String reason = "Port unreachable exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            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 (IOException e) {
            String reason = "IOException while polling address: " + ipv4Addr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            if (socket != null)
                socket.close();
        }
    }
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) PortUnreachableException(java.net.PortUnreachableException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer) NoRouteToHostException(java.net.NoRouteToHostException) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 25 with NoRouteToHostException

use of java.net.NoRouteToHostException in project opennms by OpenNMS.

the class NtpMonitor method poll.

/**
     * {@inheritDoc}
     *
     * <P>
     * Poll the specified address for NTP service availability.
     * </P>
     *
     * <P>
     * During the poll an NTP request query packet is generated. The query is
     * sent via UDP socket to the interface at the specified port (by default
     * UDP port 123). If a response is received, it is parsed and validated. If
     * the NTP was successful the service status is set to SERVICE_AVAILABLE and
     * the method returns.
     * </P>
     */
@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);
    // get the address and NTP address request
    //
    InetAddress ipAddr = svc.getAddress();
    PollStatus serviceStatus = PollStatus.unavailable();
    DatagramSocket socket = null;
    double responseTime = -1.0;
    try {
        socket = new DatagramSocket();
        // will force the
        socket.setSoTimeout(tracker.getSoTimeout());
        for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
            try {
                // Send NTP request
                //
                byte[] data = new NtpMessage().toByteArray();
                DatagramPacket outgoing = new DatagramPacket(data, data.length, ipAddr, port);
                tracker.startAttempt();
                socket.send(outgoing);
                // Get NTP Response
                //
                // byte[] buffer = new byte[512];
                DatagramPacket incoming = new DatagramPacket(data, data.length);
                socket.receive(incoming);
                responseTime = tracker.elapsedTimeInMillis();
                double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
                // Validate NTP Response
                // IOException thrown if packet does not decode as expected.
                NtpMessage msg = new NtpMessage(incoming.getData());
                double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;
                LOG.debug("poll: valid NTP request received the local clock offset is {}, responseTime= {}ms", localClockOffset, responseTime);
                LOG.debug("poll: NTP message : {}", msg);
                serviceStatus = PollStatus.available(responseTime);
            } catch (InterruptedIOException ex) {
            // Ignore, no response received.
            }
        }
    } catch (NoRouteToHostException e) {
        String reason = "No route to host exception for address: " + ipAddr;
        LOG.debug(reason, e);
        serviceStatus = PollStatus.unavailable(reason);
    } catch (ConnectException e) {
        String reason = "Connection exception for address: " + ipAddr;
        LOG.debug(reason, e);
        serviceStatus = PollStatus.unavailable(reason);
    } catch (IOException ex) {
        String reason = "IOException while polling address: " + ipAddr;
        LOG.debug(reason, ex);
        serviceStatus = PollStatus.unavailable(reason);
    } finally {
        if (socket != null)
            socket.close();
    }
    //
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) PollStatus(org.opennms.netmgt.poller.PollStatus) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) NoRouteToHostException(java.net.NoRouteToHostException) NtpMessage(org.opennms.netmgt.poller.monitors.support.NtpMessage) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) InetAddress(java.net.InetAddress) ConnectException(java.net.ConnectException)

Aggregations

NoRouteToHostException (java.net.NoRouteToHostException)31 IOException (java.io.IOException)26 InterruptedIOException (java.io.InterruptedIOException)19 ConnectException (java.net.ConnectException)19 InetSocketAddress (java.net.InetSocketAddress)14 Socket (java.net.Socket)14 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)13 InetAddress (java.net.InetAddress)12 PollStatus (org.opennms.netmgt.poller.PollStatus)11 InputStreamReader (java.io.InputStreamReader)7 BufferedInputStream (java.io.BufferedInputStream)6 BufferedReader (java.io.BufferedReader)6 URL (java.net.URL)6 ProtocolException (java.net.ProtocolException)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 Test (org.junit.Test)4 DatagramSocket (java.net.DatagramSocket)3 SocketTimeoutException (java.net.SocketTimeoutException)3 OutputStream (java.io.OutputStream)2