Search in sources :

Example 96 with InterruptedIOException

use of java.io.InterruptedIOException in project opennms by OpenNMS.

the class Receiver method run.

/**
     * <p>run</p>
     */
@Override
public void run() {
    //
    synchronized (this) {
        m_status = RUNNING;
    }
    byte[] dgbuf = new byte[2048];
    //
    for (; ; ) {
        try {
            DatagramPacket pkt = new DatagramPacket(dgbuf, dgbuf.length);
            m_receiver.receive(pkt);
            LOG.debug("got a DHCP response.");
            Message msg = new Message(pkt.getAddress(), new DHCPMessage(pkt.getData()));
            synchronized (m_clients) {
                Iterator<Client> iter = m_clients.iterator();
                if (!iter.hasNext()) {
                    LOG.debug("No client waiting for response.");
                }
                while (iter.hasNext()) {
                    Client c = iter.next();
                    if (c.getStatus() == RUNNING) {
                        try {
                            LOG.debug("sending DHCP response pkt to client {}", c.getName());
                            c.sendMessage(msg);
                        } catch (IOException ex) {
                            LOG.warn("Error sending response to client {}", c.getName());
                        }
                    } else if (c.getStatus() == STOPPED) {
                        LOG.debug("Removing stale client {}", c.getName());
                        iter.remove();
                    }
                }
            }
        } catch (InterruptedIOException ex) {
        // ignore
        } catch (ArrayIndexOutOfBoundsException ex) {
            LOG.warn("An error occurred when reading DHCP response. Ignoring exception: ", ex);
        } catch (IOException ex) {
            synchronized (this) {
                if (m_status == RUNNING)
                    LOG.warn("Failed to read message, I/O error", ex);
            }
            break;
        } catch (Throwable t) {
            synchronized (this) {
                if (m_status == RUNNING)
                    LOG.warn("Undeclared throwable caught", t);
            }
            break;
        }
        synchronized (this) {
            if (m_status != RUNNING)
                break;
        }
    }
    synchronized (this) {
        m_status = STOP_PENDING;
    }
    // close the datagram socket
    //
    m_receiver.close();
    synchronized (this) {
        m_status = STOPPED;
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) DHCPMessage(edu.bucknell.net.JDHCP.DHCPMessage) DatagramPacket(java.net.DatagramPacket) DHCPMessage(edu.bucknell.net.JDHCP.DHCPMessage) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException)

Example 97 with InterruptedIOException

use of java.io.InterruptedIOException in project opennms by OpenNMS.

the class Receiver2 method run.

/**
     * <p>run</p>
     */
@Override
public void run() {
    //
    synchronized (this) {
        m_status = RUNNING;
    }
    byte[] dgbuf = new byte[2048];
    //
    for (; ; ) {
        try {
            DatagramPacket pkt = new DatagramPacket(dgbuf, dgbuf.length);
            m_receiver.receive(pkt);
            LOG.debug("got a DHCP response.");
            Message msg = new Message(pkt.getAddress(), new DHCPMessage(pkt.getData()));
            synchronized (m_clients) {
                Iterator<Client> iter = m_clients.iterator();
                if (!iter.hasNext()) {
                    LOG.debug("No client waiting for response.");
                }
                while (iter.hasNext()) {
                    Client c = iter.next();
                    if (c.getStatus() == RUNNING) {
                        try {
                            LOG.debug("sending DHCP response pkt to client {}", c.getName());
                            c.sendMessage(msg);
                        } catch (IOException ex) {
                            LOG.warn("Error sending response to client {}", c.getName());
                        }
                    } else if (c.getStatus() == STOPPED) {
                        LOG.debug("Removing stale client {}", c.getName());
                        iter.remove();
                    }
                }
            }
        } catch (InterruptedIOException ex) {
        // ignore
        } catch (ArrayIndexOutOfBoundsException ex) {
            LOG.warn("An error occurred when reading DHCP response. Ignoring exception: ", ex);
        } catch (NegativeArraySizeException ex) {
            // Ignore cases where the target returns a badly-formatted DHCP response
            // Fixes http://bugzilla.opennms.org/show_bug.cgi?id=3445
            LOG.warn("An error occurred when reading DHCP response. Ignoring exception: ", ex);
        } catch (IOException ex) {
            synchronized (this) {
                if (m_status == RUNNING)
                    LOG.warn("Failed to read message, I/O error", ex);
            }
            break;
        } catch (Throwable t) {
            synchronized (this) {
                if (m_status == RUNNING)
                    LOG.warn("Undeclared throwable caught", t);
            }
            break;
        }
        synchronized (this) {
            if (m_status != RUNNING)
                break;
        }
    }
    synchronized (this) {
        m_status = STOP_PENDING;
    }
    // close the datagram socket
    //
    m_receiver.close();
    synchronized (this) {
        m_status = STOPPED;
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) DHCPMessage(edu.bucknell.net.JDHCP.DHCPMessage) DatagramPacket(java.net.DatagramPacket) DHCPMessage(edu.bucknell.net.JDHCP.DHCPMessage) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException)

Example 98 with InterruptedIOException

use of java.io.InterruptedIOException in project opennms by OpenNMS.

the class NrpeMonitor 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 banner line generated by the
     * interface is parsed and if the banner text indicates that we are talking
     * to 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) {
    String reason = null;
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    String command = ParameterMap.getKeyedString(parameters, "command", NrpePacket.HELLO_COMMAND);
    int port = ParameterMap.getKeyedInteger(parameters, "port", CheckNrpe.DEFAULT_PORT);
    int padding = ParameterMap.getKeyedInteger(parameters, "padding", NrpePacket.DEFAULT_PADDING);
    boolean useSsl = ParameterMap.getKeyedBoolean(parameters, "usessl", DEFAULT_USE_SSL);
    /*
        // Port
        //
        int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
        if (port == DEFAULT_PORT) {
            throw new RuntimeException("NrpeMonitor: required parameter 'port' is not present in supplied properties.");
        }
        */
    // BannerMatch
    //
    //Commented out because it is not currently referenced in this monitor
    //String strBannerMatch = (String) parameters.get("banner");
    // Get the address instance.
    //
    InetAddress ipv4Addr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipv4Addr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
    // Give it a whirl
    //
    int serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
    Double responseTime = null;
    for (tracker.reset(); tracker.shouldRetry() && serviceStatus != PollStatus.SERVICE_AVAILABLE; tracker.nextAttempt()) {
        Socket socket = null;
        try {
            //
            // create a connected socket
            //
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipv4Addr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("NrpeMonitor: connected to host: {} on port: {}", ipv4Addr, port);
            reason = "Perhaps check the value of 'usessl' for this monitor against the NRPE daemon configuration";
            socket = wrapSocket(socket, useSsl);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
            reason = "Connected successfully, but no response received";
            NrpePacket p = new NrpePacket(NrpePacket.QUERY_PACKET, (short) 0, command);
            byte[] b = p.buildPacket(padding);
            OutputStream o = socket.getOutputStream();
            o.write(b);
            /*
                if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {

				if (true) {
                    serviceStatus = SERVICE_AVAILABLE;
                    // Store response time in RRD
                    if (responseTime >= 0 && rrdPath != null) {
                        try {
                            this.updateRRD(rrdPath, ipv4Addr, dsName, responseTime, pkg);
                        } catch (RuntimeException rex) {
                            LOG.debug("There was a problem writing the RRD: {}", rex);
                        }
                    }
                    break;
                }

                BufferedReader rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //
                // Tokenize the Banner Line, and check the first
                // line for a valid return.
                //
                String response = rdr.readLine();
                responseTime = System.currentTimeMillis() - sentTime;

                if (response == null)
                    continue;
                LOG.debug("poll: banner = {}", response);
                LOG.debug("poll: responseTime= {}ms", responseTime);

                if (response.indexOf(strBannerMatch) > -1) {
                */
            NrpePacket response = NrpePacket.receivePacket(socket.getInputStream(), padding);
            responseTime = tracker.elapsedTimeInMillis();
            if (response.getResultCode() == 0) {
                serviceStatus = PollStatus.SERVICE_AVAILABLE;
                reason = null;
            } else {
                serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
                reason = "NRPE command returned code " + response.getResultCode() + " and message: " + response.getBuffer();
            }
        } catch (NoRouteToHostException e) {
            reason = "No route to host exception for address " + hostAddress;
            LOG.warn("poll: {}", reason, e);
        } catch (InterruptedIOException e) {
            reason = "did not connect to host within " + tracker;
            LOG.debug("NrpeMonitor: did not connect to host within {}", tracker);
        } catch (ConnectException e) {
            reason = "Connection exception for address: " + ipv4Addr;
            //
            if (LOG.isDebugEnabled()) {
                e.fillInStackTrace();
                LOG.debug("poll: {}", reason, e);
            }
        } catch (NrpeException e) {
            reason = "NrpeException while polling address: " + ipv4Addr;
            if (LOG.isDebugEnabled()) {
                e.fillInStackTrace();
                LOG.debug("poll: {}", reason, e);
            }
        } catch (IOException e) {
            // Ignore
            reason = "IOException while polling address: " + ipv4Addr;
            if (LOG.isDebugEnabled()) {
                e.fillInStackTrace();
                LOG.debug("poll: {}", reason, e);
            }
        } finally {
            try {
                // Close the socket
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                if (LOG.isDebugEnabled()) {
                    e.fillInStackTrace();
                    LOG.debug("poll: Error closing socket.", e);
                }
            }
        }
    }
    //
    if (reason == null) {
        return PollStatus.get(serviceStatus, responseTime);
    } else {
        return PollStatus.get(serviceStatus, reason);
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) NrpeException(org.opennms.netmgt.poller.monitors.nrpe.NrpeException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) NoRouteToHostException(java.net.NoRouteToHostException) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) InetAddress(java.net.InetAddress) NrpePacket(org.opennms.netmgt.poller.monitors.nrpe.NrpePacket) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 99 with InterruptedIOException

use of java.io.InterruptedIOException in project opennms by OpenNMS.

the class TcpMonitor 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 banner line generated by the
     * interface is parsed and if the banner text indicates that we are talking
     * to 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) {
    //
    // Process parameters
    //
    //
    // Get interface address from NetworkInterface
    //
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    //
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    if (port == DEFAULT_PORT) {
        throw new RuntimeException("TcpMonitor: required parameter 'port' is not present in supplied properties.");
    }
    // BannerMatch
    //
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
    // Get the address instance.
    //
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
    // Give it a whirl
    //
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        Socket socket = null;
        try {
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("TcpMonitor: connected to host: {} on port: {}", ipAddr, port);
            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {
                serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
                break;
            }
            BufferedReader rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //
            // Tokenize the Banner Line, and check the first
            // line for a valid return.
            //
            String response = rdr.readLine();
            double responseTime = tracker.elapsedTimeInMillis();
            if (response == null)
                continue;
            LOG.debug("poll: banner = {}", response);
            LOG.debug("poll: responseTime= {}ms", responseTime);
            //Could it be a regex?
            if (strBannerMatch.charAt(0) == '~') {
                if (!response.matches(strBannerMatch.substring(1)))
                    serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                else
                    serviceStatus = PollStatus.available(responseTime);
            } else {
                if (response.indexOf(strBannerMatch) > -1) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus.unavailable("Banner: '" + response + "' does not contain match string '" + strBannerMatch + "'");
                }
            }
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            // Break out of for(;;)
            break;
        } 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) {
                e.fillInStackTrace();
                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) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) BufferedReader(java.io.BufferedReader) InetAddress(java.net.InetAddress) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Example 100 with InterruptedIOException

use of java.io.InterruptedIOException in project opennms by OpenNMS.

the class TrivialTimeMonitor method pollTimeTcp.

/**
     * <p>pollTimeTcp</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 pollTimeTcp(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()) {
        Socket socket = null;
        try {
            tracker.startAttempt();
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipv4Addr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("Connected to host: {} on TCP port: {}", ipv4Addr, port);
            //
            // Try to read from the socket
            //
            byte[] timeBytes = new byte[4];
            ByteBuffer timeByteBuffer = ByteBuffer.wrap(timeBytes);
            int bytesRead = socket.getInputStream().read(timeBytes);
            if (bytesRead != 4)
                continue;
            LOG.debug("pollTimeTcp: 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 (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + InetAddressUtils.str(ipv4Addr);
            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: " + ipv4Addr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address: " + ipv4Addr;
            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("pollTimeTcp: Error closing socket.", e);
            }
        }
    }
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer) NoRouteToHostException(java.net.NoRouteToHostException) Socket(java.net.Socket) DatagramSocket(java.net.DatagramSocket) BufferUnderflowException(java.nio.BufferUnderflowException) ConnectException(java.net.ConnectException)

Aggregations

InterruptedIOException (java.io.InterruptedIOException)274 IOException (java.io.IOException)186 Test (org.junit.Test)39 ArrayList (java.util.ArrayList)27 Socket (java.net.Socket)26 ConnectException (java.net.ConnectException)22 ExecutionException (java.util.concurrent.ExecutionException)22 InputStream (java.io.InputStream)21 InetSocketAddress (java.net.InetSocketAddress)21 ByteBuffer (java.nio.ByteBuffer)21 Path (org.apache.hadoop.fs.Path)20 NoRouteToHostException (java.net.NoRouteToHostException)19 ServletException (javax.servlet.ServletException)17 CountDownLatch (java.util.concurrent.CountDownLatch)16 SocketTimeoutException (java.net.SocketTimeoutException)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 HttpServletResponse (javax.servlet.http.HttpServletResponse)15 EOFException (java.io.EOFException)14 SocketException (java.net.SocketException)14 OutputStream (java.io.OutputStream)13