Search in sources :

Example 91 with InterruptedIOException

use of java.io.InterruptedIOException in project GNS by MobilityFirst.

the class UdpDnsServer method run.

@Override
public void run() {
    NameResolution.getLogger().log(Level.INFO, "Starting local DNS Server on port {0}{1}fallback DNS server at {2}", new Object[] { sock.getLocalPort(), gnsServerIP != null ? (" with GNS server at " + gnsServerIP + " and ") : " with ", dnsServerIP });
    while (true) {
        try {
            final short udpLength = 512;
            while (true) {
                byte[] incomingData = new byte[udpLength];
                DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
                // Read the incoming request
                incomingPacket.setLength(incomingData.length);
                try {
                    sock.receive(incomingPacket);
                } catch (InterruptedIOException e) {
                    continue;
                }
                executor.execute(new LookupWorker(sock, incomingPacket, incomingData, gnsServer, dnsServer, dnsCache, handler));
            }
        } catch (IOException e) {
            NameResolution.getLogger().log(Level.SEVERE, "Error in UDP Server (will sleep for 3 seconds and try again): {0}", e);
            ThreadUtils.sleep(3000);
        }
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException)

Example 92 with InterruptedIOException

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

the class TcpServer method run.

/**
     * The logic execution context to accept and process incoming connection
     * requests. When a new connection is received a new thread of control is
     * created to process the connection. This method encapsulates that control
     * logic so that it can be executed in it's own java thread.
     */
@Override
public void run() {
    // get the thread context for the ability to stop the process
    m_context = Thread.currentThread();
    synchronized (m_context) {
        m_context.notifyAll();
    }
    // get the log information
    Logging.putPrefix(m_logPrefix);
    // check to see if the thread has already been stopped.
    if (m_stop) {
        LOG.debug("Stop flag set on thread startup");
        try {
            if (m_tcpSock != null) {
                m_tcpSock.close();
            }
            LOG.debug("The socket has been closed");
        } catch (Throwable e) {
            LOG.warn("An exception occured closing the socket", e);
        }
        LOG.debug("Thread exiting");
        return;
    }
    LOG.debug("Server connection processor started on {}:{}", m_ipAddress, m_tcpPort);
    /*
         *
         * Set the initial timeout on the socket. This allows
         * the thread to wake up every 1/2 second and check the
         * shutdown status.
         */
    try {
        m_tcpSock.setSoTimeout(500);
    } catch (SocketException e) {
        if (!m_stop) {
            LOG.warn("An I/O exception occured setting the socket timeout", e);
        }
        LOG.debug("Thread exiting due to socket error", e);
        return;
    }
    // used to avoid seeing the trace message repeatedly
    boolean ioInterrupted = false;
    /*
         * Check the status of the fiber and respond
         * correctly. When the fiber enters a STOPPED or
         * STOP PENDING state then shutdown occurs by exiting
         * the while loop
         */
    while (m_parent.getStatus() != Fiber.STOPPED && m_parent.getStatus() != Fiber.STOP_PENDING && !m_stop) {
        try {
            if (!ioInterrupted) {
                LOG.debug("Waiting for new connection");
            }
            /*
                 * Get the newbie socket connection from the client.
                 * After accepting the connection start up a thread
                 * to process the request
                 */
            Socket newbie = m_tcpSock.accept();
            // reset the flag
            ioInterrupted = false;
            // build a connection string for the thread identifier
            StringBuffer connection = new StringBuffer(InetAddressUtils.str(newbie.getInetAddress()));
            connection.append(":").append(newbie.getPort());
            LOG.debug("New connection accepted from {}", connection);
            // start a new handler
            TcpStreamHandler handler = new TcpStreamHandler(m_parent, newbie, m_handlers, m_recsPerConn);
            Thread processor = new Thread(handler, m_parent.getName() + "[" + connection + "]");
            synchronized (processor) {
                processor.start();
                try {
                    processor.wait();
                } catch (InterruptedException e) {
                    LOG.warn("The thread was interrupted", e);
                }
            }
            LOG.debug("A new stream handler thread has been started");
            // add the handler to the list
            m_receivers.add(handler);
        } catch (InterruptedIOException e) {
            /*
                 * do nothing on interrupted I/O
                 * DON'T Continue, the end of the loop
                 * checks and removes terminated threads
                 */
            ioInterrupted = true;
        } catch (IOException e) {
            LOG.error("Server Socket I/O Error", e);
            break;
        }
        /*
             * Go through the threads in the list of
             * receivers and find the dead ones. When
             * they are no longer alive just remove them
             * from the list.
             */
        Iterator<TcpStreamHandler> i = m_receivers.iterator();
        while (i.hasNext()) {
            TcpStreamHandler t = i.next();
            if (!t.isAlive()) {
                i.remove();
            }
        }
    }
    // Either a fatal I/O error has occured or the service has been stopped.
    try {
        LOG.debug("closing the server socket connection");
        m_tcpSock.close();
    } catch (Throwable t) {
        LOG.error("An I/O Error Occcured Closing the Server Socket", t);
    }
    // Log the termination of this runnable
    LOG.debug("TCP Server Shutdown");
}
Also used : SocketException(java.net.SocketException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 93 with InterruptedIOException

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

the class TcpRecordHandler method run.

/**
     * The execution context.
     */
@Override
public void run() {
    // get the thread context right off
    m_context = Thread.currentThread();
    synchronized (m_context) {
        m_context.notifyAll();
    }
    /*
         * Check the stop flag, if it is set then go a head and exit
         * before doing any work on the socket
         */
    if (m_stop) {
        LOG.debug("Stop flag set before thread startup, thread exiting");
        return;
    } else {
        LOG.debug("Thread started, remote is {}", InetAddressUtils.str(m_connection.getInetAddress()));
    }
    // get the input stream
    InputStream socketIn = null;
    try {
        // needed in case connection closed!
        m_connection.setSoTimeout(500);
        socketIn = new BufferedInputStream(m_connection.getInputStream());
    } catch (final IOException e) {
        if (!m_stop) {
            LOG.warn("An I/O Exception occured.", e);
        }
        m_xchange.add(e);
        LOG.debug("Thread exiting due to socket exception, stop flag = {}", Boolean.valueOf(m_stop));
        return;
    }
    int level = 8;
    int ch = 0;
    boolean moreInput = true;
    while (moreInput) {
        // check to see if the thread is interrupted
        if (Thread.interrupted()) {
            LOG.debug("Thread Interrupted");
            break;
        }
        try {
            ch = socketIn.read();
            if (ch == -1) {
                moreInput = false;
                continue;
            }
        } catch (final InterruptedIOException e) {
            // this was expected
            continue;
        } catch (final EOFException e) {
            m_xchange.add(e);
            moreInput = false;
            continue;
        } catch (final IOException e) {
            m_xchange.add(e);
            if (!m_stop) {
                LOG.warn("An I/O error occured reading from the remote host.", e);
            }
            moreInput = false;
            continue;
        }
        try {
            level = m_tokenizer[level].next((char) ch);
        } catch (final IOException e) {
            if (!m_stop) {
                LOG.warn("An I/O error occured writing to the processor stream.", e);
                LOG.warn("Discarding the remainder of the event contents");
                try {
                    /*
                         * this will discard current stream
                         * and cause all forwards to be discarded.
                         */
                    closeStream();
                } catch (final IOException e2) {
                }
            } else {
                m_xchange.add(e);
                moreInput = false;
            }
        }
    }
    // ensure that the receiver knows that no new element is coming!
    try {
        if (m_out != null) {
            m_out.close();
        }
    } catch (final IOException e) {
        if (!m_stop) {
            LOG.warn("An I/O Error occured closing the processor stream.", e);
        }
    }
    m_xchange.add(new EOFException("No More Input"));
    LOG.debug("Thread Terminated");
}
Also used : InterruptedIOException(java.io.InterruptedIOException) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) EOFException(java.io.EOFException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException)

Example 94 with InterruptedIOException

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

the class UdpReceiver method run.

/**
     * The execution context.
     */
@Override
public void run() {
    // get the context
    m_context = Thread.currentThread();
    // Get a log instance
    Logging.putPrefix(m_logPrefix);
    if (m_stop) {
        LOG.debug("Stop flag set before thread started, exiting");
        return;
    } else {
        LOG.debug("Thread context started");
    }
    // allocate a buffer
    final int length = 0xffff;
    final byte[] buffer = new byte[length];
    DatagramPacket pkt = new DatagramPacket(buffer, length);
    // Set an SO timout to make sure we don't block forever if a socket is closed.
    try {
        LOG.debug("Setting socket timeout to 500ms");
        m_dgSock.setSoTimeout(500);
    } catch (SocketException e) {
        LOG.warn("An I/O error occured while trying to set the socket timeout", e);
    }
    // Increase the receive buffer for the socket
    try {
        LOG.debug("Setting receive buffer size to {}", length);
        m_dgSock.setReceiveBufferSize(length);
    } catch (SocketException e) {
        LOG.info("Failed to set the receive buffer to {}", length, e);
    }
    // set to avoid numerious tracing message
    boolean ioInterrupted = false;
    // now start processing incoming request
    while (!m_stop) {
        if (m_context.isInterrupted()) {
            LOG.debug("Thread context interrupted");
            break;
        }
        try {
            if (!ioInterrupted) {
                LOG.debug("Wating on a datagram to arrive");
            }
            m_dgSock.receive(pkt);
            // reset the flag
            ioInterrupted = false;
        } catch (InterruptedIOException e) {
            ioInterrupted = true;
            continue;
        } catch (IOException e) {
            LOG.error("An I/O exception occured on the datagram receipt port, exiting", e);
            break;
        }
        LOG.debug("Sending received packet to processor");
        UdpReceivedEvent re = UdpReceivedEvent.make(pkt);
        synchronized (m_eventsIn) {
            m_eventsIn.add(re);
            m_eventsIn.notify();
        }
        pkt = new DatagramPacket(buffer, length);
    }
    LOG.debug("Thread context exiting");
}
Also used : SocketException(java.net.SocketException) InterruptedIOException(java.io.InterruptedIOException) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException)

Example 95 with InterruptedIOException

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

the class Poller method isServer.

/**
     * <p>
     * This method actually tests the remote host to determine if it is
     * running a functional DHCP server.
     * </p>
     * <p>
     * Formats a DHCP query and encodes it in a client request message which
     * is sent to the DHCP daemon over the established TCP socket connection.
     * If a matching DHCP response packet is not received from the DHCP daemon
     * within the specified timeout the client request message will be re-sent
     * up to the specified number of retries.
     * </p>
     * <p>
     * If a response is received from the DHCP daemon it is validated to
     * ensure that:
     * </p>
     * <ul>
     * <li>The DHCP response packet was sent from the remote host to which the
     * original request packet was directed.</li>
     * <li>The XID of the DHCP response packet matches the XID of the original
     * DHCP request packet.</li>
     * </ul>
     * <p>
     * If the response validates 'true' is returned. Otherwise the request is
     * resent until max retry count is exceeded.
     * </p>
     * <p>
     * Before returning, a client disconnect message (remote host field set to
     * zero) is sent to the DHCP daemon.
     * </p>
     * 
     * @return response time in milliseconds if the specified host responded
     *         with a valid DHCP offer datagram within the context of the
     *         specified timeout and retry values or negative one (-1)
     *         otherwise.
     */
static long isServer(InetAddress host, long timeout, int retries) throws IOException {
    boolean isDhcpServer = false;
    // List of DHCP queries to try. The default when extended
    // mode = false must be listed first. (DISCOVER)
    byte[] typeList = { (byte) DHCPMessage.DISCOVER, (byte) DHCPMessage.INFORM, (byte) DHCPMessage.REQUEST };
    String[] typeName = { "DISCOVER", "INFORM", "REQUEST" };
    DhcpdConfigFactory dcf = DhcpdConfigFactory.getInstance();
    if (!paramsChecked) {
        String s_extendedMode = dcf.getExtendedMode();
        if (s_extendedMode == null) {
            extendedMode = false;
        } else {
            extendedMode = Boolean.parseBoolean(s_extendedMode);
        }
        LOG.debug("isServer: DHCP extended mode is {}", extendedMode);
        String hwAddressStr = dcf.getMacAddress();
        LOG.debug("isServer: DHCP query hardware/MAC address is {}", hwAddressStr);
        setHwAddress(hwAddressStr);
        String myIpStr = dcf.getMyIpAddress();
        LOG.debug("isServer: DHCP relay agent address is {}", myIpStr);
        if (myIpStr == null || myIpStr.equals("") || myIpStr.equalsIgnoreCase("broadcast")) {
        // do nothing
        } else {
            try {
                InetAddressUtils.toIpAddrBytes(myIpStr);
                s_myIpAddress = setIpAddress(myIpStr);
                relayMode = true;
            } catch (IllegalArgumentException e) {
                LOG.warn("isServer: DHCP relay agent address is invalid: {}", myIpStr);
            }
        }
        if (extendedMode == true) {
            String requestStr = dcf.getRequestIpAddress();
            LOG.debug("isServer: REQUEST query target is {}", requestStr);
            if (requestStr == null || requestStr.equals("") || requestStr.equalsIgnoreCase("targetSubnet")) {
            // do nothing
            } else if (requestStr.equalsIgnoreCase("targetHost")) {
                targetOffset = false;
            } else {
                try {
                    InetAddressUtils.toIpAddrBytes(requestStr);
                    s_requestIpAddress = setIpAddress(requestStr);
                    reqTargetIp = false;
                    targetOffset = false;
                } catch (IllegalArgumentException e) {
                    LOG.warn("isServer: REQUEST query target is invalid: {}", requestStr);
                }
            }
            LOG.debug("REQUEST query options are: reqTargetIp = {}, targetOffset = {}", reqTargetIp, targetOffset);
        }
        paramsChecked = true;
    }
    int j = 1;
    if (extendedMode == true) {
        j = typeList.length;
    }
    if (timeout < 500) {
        timeout = 500;
    }
    Poller p = new Poller(timeout);
    long responseTime = -1;
    try {
        pollit: for (int i = 0; i < j; i++) {
            Message ping = getPollingRequest(host, (byte) typeList[i]);
            int rt = retries;
            while (rt >= 0 && !isDhcpServer) {
                LOG.debug("isServer: sending DHCP {} query to host {} with Xid: {}", typeName[i], InetAddressUtils.str(host), ping.getMessage().getXid());
                long start = System.currentTimeMillis();
                p.m_outs.writeObject(ping);
                long end;
                do {
                    Message resp = null;
                    try {
                        resp = (Message) p.m_ins.readObject();
                    } catch (InterruptedIOException ex) {
                        resp = null;
                    }
                    if (resp != null) {
                        responseTime = System.currentTimeMillis() - start;
                        // DEBUG only
                        LOG.debug("isServer: got a DHCP response from host {} with Xid: {}", InetAddressUtils.str(resp.getAddress()), resp.getMessage().getXid());
                        if (host.equals(resp.getAddress()) && ping.getMessage().getXid() == resp.getMessage().getXid()) {
                            // Inspect response message to see if it is a valid DHCP response
                            byte[] type = resp.getMessage().getOption(MESSAGE_TYPE);
                            if (type[0] == DHCPMessage.OFFER) {
                                LOG.debug("isServer: got a DHCP OFFER response, validating...");
                            } else if (type[0] == DHCPMessage.ACK) {
                                LOG.debug("isServer: got a DHCP ACK response, validating...");
                            } else if (type[0] == DHCPMessage.NAK) {
                                LOG.debug("isServer: got a DHCP NAK response, validating...");
                            }
                            // accept offer or ACK or NAK
                            if (type[0] == DHCPMessage.OFFER || (extendedMode == true && (type[0] == DHCPMessage.ACK || type[0] == DHCPMessage.NAK))) {
                                LOG.debug("isServer: got a valid DHCP response. responseTime= {}ms", responseTime);
                                isDhcpServer = true;
                                break pollit;
                            }
                        }
                    }
                    end = System.currentTimeMillis();
                } while ((end - start) < timeout);
                if (!isDhcpServer) {
                    LOG.debug("Timed out waiting for DHCP response, remaining retries: {}", rt);
                }
                --rt;
            }
        }
        LOG.debug("Sending disconnect request");
        p.m_outs.writeObject(getDisconnectRequest());
        LOG.debug("wait half a sec before closing connection");
        Thread.sleep(500);
        p.close();
    } catch (IOException ex) {
        LOG.error("IO Exception caught.", ex);
        p.close();
        throw ex;
    } catch (Throwable t) {
        LOG.error("Unexpected Exception caught.", t);
        p.close();
        throw new UndeclaredThrowableException(t);
    }
    // server or -1 if the remote box is NOT a DHCP server.
    if (isDhcpServer) {
        return responseTime;
    } else {
        return -1;
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) DHCPMessage(edu.bucknell.net.JDHCP.DHCPMessage) DhcpdConfigFactory(org.opennms.netmgt.config.dhcpd.DhcpdConfigFactory) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException)

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