Search in sources :

Example 1 with ClosedByInterruptException

use of java.nio.channels.ClosedByInterruptException in project buck by facebook.

the class MissingSymbolsHandler method createListener.

/**
   * Instantiate a MissingSymbolsHandler and wrap it in a listener that calls it on the appropriate
   * events. This is done as part of the global listener setup in Main, and it's the entry point
   * into most of the dependency autodetection code.
   */
public static BuckEventListener createListener(ProjectFilesystem projectFilesystem, ImmutableSet<Description<?>> descriptions, BuckConfig config, BuckEventBus buckEventBus, Console console, JavacOptions javacOptions, ImmutableMap<String, String> environment) {
    final MissingSymbolsHandler missingSymbolsHandler = create(projectFilesystem, descriptions, config, buckEventBus, console, javacOptions, environment);
    final Multimap<BuildId, MissingSymbolEvent> missingSymbolEvents = HashMultimap.create();
    BuckEventListener missingSymbolsListener = new BuckEventListener() {

        @Override
        public void outputTrace(BuildId buildId) {
        // If we put {@link #printNeededDependencies} here, it's output won't be visible in buckd.
        // Instead, we listen for BuildEvent.Finished, below.
        }

        @Subscribe
        public void onMissingSymbol(MissingSymbolEvent event) {
            missingSymbolEvents.put(event.getBuildId(), event);
        }

        @Subscribe
        public void onBuildFinished(BuildEvent.Finished event) {
            // Shortcircuit if there aren't any failures.
            if (missingSymbolEvents.get(event.getBuildId()).isEmpty()) {
                return;
            }
            try {
                missingSymbolsHandler.printNeededDependencies(missingSymbolEvents.get(event.getBuildId()));
            } catch (InterruptedException e) {
                LOG.debug(e, "Missing symbols handler did not complete in time.");
            } catch (RuntimeException e) {
                if (e.getCause() instanceof ClosedByInterruptException) {
                    LOG.debug(e.getCause(), "Missing symbols handler did not complete in time.");
                } else {
                    throw e;
                }
            }
            missingSymbolEvents.removeAll(event.getBuildId());
        }
    };
    return missingSymbolsListener;
}
Also used : ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) BuildId(com.facebook.buck.model.BuildId) MissingSymbolEvent(com.facebook.buck.event.MissingSymbolEvent) BuckEventListener(com.facebook.buck.event.BuckEventListener)

Example 2 with ClosedByInterruptException

use of java.nio.channels.ClosedByInterruptException in project OpenAM by OpenRock.

the class RadiusRequestListener method run.

/**
     * Where the work gets done. :-) Blocks until packets are received, validates the source IP against configured
     * clients and drops packets accordingly, then spools valid ones to the thread pool for handling and goes back to
     * listening.
     */
@Override
public void run() {
    // Flag to hold interrupted state for returning after cleanup.
    boolean interrupted = false;
    dumpBannerToLog();
    while (!terminated && !interrupted) {
        try {
            // assure big-endian (network) byte order for our buffer
            final ByteBuffer bfr = ByteBuffer.allocate(RadiusServerConstants.MAX_PACKET_SIZE);
            bfr.order(ByteOrder.BIG_ENDIAN);
            InetSocketAddress iAddr = null;
            // see if we have a datagram packet waiting for us
            try {
                iAddr = (InetSocketAddress) channel.receive(bfr);
                if (iAddr == null) {
                    // no datagram was available, it happens, just go back to listening
                    LOG.message("DatagramChannel receive returned null. No datagram available.");
                    continue;
                } else {
                    eventBus.post(new PacketReceivedEvent());
                }
            } catch (final ClosedByInterruptException c) {
                interrupted = true;
                continue;
            } catch (final IOException e) {
                LOG.warning("Exception Receiving RADIUS packet. Ignoring.", e);
                continue;
            } catch (final SecurityException e) {
                LOG.error("a security manager has been installed and it does not permit datagrams to be " + " accepted from the datagram's sender. Ignoring", e);
                continue;
            }
            // see if it is for a registered client
            final String ipAddr = iAddr.getAddress().toString();
            final ClientConfig clientConfig = config.findClient(ipAddr);
            if (clientConfig == null) {
                LOG.warning("No Defined RADIUS Client matches IP address " + ipAddr + ". Dropping request.");
                continue;
            }
            if (!clientConfig.isClassIsValid()) {
                LOG.warning("Declared Handler Class for Client '" + clientConfig.getName() + "' is not valid. See earlier loading exception. Dropping request.");
                continue;
            }
            // prepare buffer for draining and queue up a handler
            bfr.flip();
            final RadiusRequestContext reqCtx = new RadiusRequestContext(clientConfig, channel, iAddr);
            final PromiseImpl<RadiusResponse, RadiusProcessingException> promise = PromiseImpl.create();
            final RadiusRequestHandler requestHandler = new RadiusRequestHandler(accessRequestHandlerFactory, reqCtx, bfr, promise, promise, eventBus);
            executorService.execute(requestHandler);
            try {
                final RadiusResponse result = promise.getOrThrow();
                eventBus.post(new PacketProcessedEvent());
            } catch (final RadiusProcessingException e) {
                final RadiusProcessingExceptionNature nature = e.getNature();
                switch(nature) {
                    case CATASTROPHIC:
                        LOG.error("Catestrophic error processing a RADIUS request.", e);
                        terminated = true;
                        break;
                    case INVALID_RESPONSE:
                        LOG.error("Failed to handle request. This request will be ignored.", e);
                        break;
                    case TEMPORARY_FAILURE:
                        final String errStr = "Failed to handle request. This request could be retried, but that is" + " currently not implemented.";
                        LOG.error(errStr, e);
                        break;
                    default:
                        break;
                }
            }
        } catch (final Exception t) {
            LOG.error("Error receiving request.", t);
        }
    }
    // re-assert interrupted state if it occurred
    if (interrupted) {
        Thread.currentThread().interrupt();
    }
    try {
        // be sure that channel is closed
        channel.close();
    } catch (final Exception e) {
        LOG.error("Failed to close the Listener's UDP channel", e);
    }
    LOG.message("RADIUS Listener Exited.");
    this.listenerThread = null;
}
Also used : PacketReceivedEvent(org.forgerock.openam.radius.server.events.PacketReceivedEvent) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SocketException(java.net.SocketException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) PacketProcessedEvent(org.forgerock.openam.radius.server.events.PacketProcessedEvent) ClientConfig(org.forgerock.openam.radius.server.config.ClientConfig)

Example 3 with ClosedByInterruptException

use of java.nio.channels.ClosedByInterruptException in project voltdb by VoltDB.

the class SocketJoiner method runPrimary.

/*
     * After startup everything is a primary and can accept
     * new nodes into the cluster. This loop accepts the new socket
     * and passes it off the HostMessenger via the JoinHandler interface
     */
private void runPrimary() throws Exception {
    try {
        // start the server socket on the right interface
        doBind();
        while (true) {
            try {
                final int selectedKeyCount = m_selector.select();
                if (selectedKeyCount == 0)
                    continue;
                Set<SelectionKey> selectedKeys = m_selector.selectedKeys();
                try {
                    for (SelectionKey key : selectedKeys) {
                        processSSC((ServerSocketChannel) key.channel());
                    }
                } finally {
                    selectedKeys.clear();
                }
            } catch (ClosedByInterruptException e) {
                throw new InterruptedException();
            } catch (ClosedSelectorException e) {
                throw new InterruptedException();
            } catch (Exception e) {
                LOG.error("fault occurrent in the connection accept loop", e);
            }
        }
    } finally {
        for (ServerSocketChannel ssc : m_listenerSockets) {
            try {
                ssc.close();
            } catch (IOException e) {
            }
        }
        m_listenerSockets.clear();
        try {
            m_selector.close();
        } catch (IOException e) {
        }
        m_selector = null;
    }
}
Also used : ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) IOException(java.io.IOException) EOFException(java.io.EOFException) JSONException(org.json_voltpatches.JSONException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 4 with ClosedByInterruptException

use of java.nio.channels.ClosedByInterruptException in project voltdb by VoltDB.

the class SocketJoiner method connectToPrimary.

/*
     * If this node failed to bind to the leader address
     * it must connect to the leader which will generate a host id and
     * advertise the rest of the cluster so that connectToPrimary can connect to it
     */
private void connectToPrimary(InetSocketAddress coordIp, ConnectStrategy mode) throws Exception {
    // collect clock skews from all nodes
    List<Long> skews = new ArrayList<Long>();
    // collect the set of active voltdb version strings in the cluster
    // this is used to limit simulatanious versions to two
    Set<String> activeVersions = new TreeSet<String>();
    try {
        LOG.debug("Non-Primary Starting & Connecting to Primary");
        SocketChannel socket = createLeaderSocket(coordIp, mode);
        // in probe mode
        if (socket == null)
            return;
        if (!coordIp.equals(m_coordIp)) {
            m_coordIp = coordIp;
        }
        socket.socket().setTcpNoDelay(true);
        socket.socket().setPerformancePreferences(0, 2, 1);
        // blocking call, send a request to the leader node and get a host id assigned by the leader
        RequestHostIdResponse response = requestHostId(socket, skews, activeVersions);
        // check if the membership request is accepted
        JSONObject responseBody = response.getResponseBody();
        if (!responseBody.optBoolean(ACCEPTED, true)) {
            socket.close();
            if (!responseBody.optBoolean(MAY_RETRY, false)) {
                org.voltdb.VoltDB.crashLocalVoltDB("Request to join cluster is rejected: " + responseBody.optString(REASON, "rejection reason is not available"));
            }
            throw new CoreUtils.RetryException(responseBody.optString(REASON, "rejection reason is not available"));
        }
        /*
             * Get the generated host id, and the interface we connected on
             * that was echoed back
             */
        m_localHostId = responseBody.getInt(NEW_HOST_ID);
        m_reportedInternalInterface = responseBody.getString(REPORTED_ADDRESS);
        ImmutableMap.Builder<Integer, JSONObject> cmbld = ImmutableMap.builder();
        cmbld.put(m_localHostId, m_acceptor.decorate(responseBody, Optional.<Boolean>empty()));
        /*
             * Loop over all the hosts and create a connection (except for the first entry, that is the leader)
             * and publish the host id that was generated. This finishes creating the mesh
             */
        JSONArray otherHosts = responseBody.getJSONArray(HOSTS);
        int[] hostIds = new int[otherHosts.length()];
        SocketChannel[] hostSockets = new SocketChannel[hostIds.length];
        InetSocketAddress[] listeningAddresses = new InetSocketAddress[hostIds.length];
        for (int ii = 0; ii < otherHosts.length(); ii++) {
            JSONObject host = otherHosts.getJSONObject(ii);
            String address = host.getString(ADDRESS);
            int port = host.getInt(PORT);
            final int hostId = host.getInt(HOST_ID);
            LOG.info("Leader provided address " + address + ":" + port);
            InetSocketAddress hostAddr = new InetSocketAddress(address, port);
            if (ii == 0) {
                //Leader already has a socket
                hostIds[ii] = hostId;
                listeningAddresses[ii] = hostAddr;
                hostSockets[ii] = socket;
                cmbld.put(ii, response.getLeaderInfo());
                continue;
            }
            // connect to all the peer hosts (except leader) and advertise our existence
            SocketChannel hostSocket = connectToHost(hostAddr);
            JSONObject hostInfo = publishHostId(hostAddr, hostSocket, skews, activeVersions);
            hostIds[ii] = hostId;
            hostSockets[ii] = hostSocket;
            listeningAddresses[ii] = hostAddr;
            cmbld.put(ii, hostInfo);
        }
        /*
             * The max difference of clock skew cannot exceed MAX_CLOCKSKEW, and the number of
             * active versions in the cluster cannot be more than 2.
             */
        checkClockSkew(skews);
        checkActiveVersions(activeVersions, m_acceptor.getVersionChecker().getVersionString());
        /*
             * Notify the leader that we connected to the entire cluster, it will then go
             * and queue a txn for our agreement site to join the cluster
             */
        ByteBuffer joinCompleteBuffer = ByteBuffer.allocate(1);
        while (joinCompleteBuffer.hasRemaining()) {
            hostSockets[0].write(joinCompleteBuffer);
        }
        /*
             * Let host messenger know about the connections.
             * It will init the agreement site and then we are done.
             */
        m_joinHandler.notifyOfHosts(m_localHostId, hostIds, hostSockets, listeningAddresses, cmbld.build());
    } catch (ClosedByInterruptException e) {
    //This is how shutdown is done
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) JSONArray(org.json_voltpatches.JSONArray) ByteBuffer(java.nio.ByteBuffer) ImmutableMap(com.google_voltpatches.common.collect.ImmutableMap) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) JSONObject(org.json_voltpatches.JSONObject) TreeSet(java.util.TreeSet) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 5 with ClosedByInterruptException

use of java.nio.channels.ClosedByInterruptException in project quorrabot by GloriousEggroll.

the class WebSocketServer method run.

// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
    synchronized (this) {
        if (selectorthread != null) {
            throw new IllegalStateException(getClass().getName() + " can only be started once.");
        }
        selectorthread = Thread.currentThread();
        if (isclosed.get()) {
            return;
        }
    }
    selectorthread.setName("WebsocketSelector" + selectorthread.getId());
    try {
        server = ServerSocketChannel.open();
        server.configureBlocking(false);
        ServerSocket socket = server.socket();
        socket.setReceiveBufferSize(WebSocketImpl.RCVBUF);
        socket.bind(address);
        selector = Selector.open();
        server.register(selector, server.validOps());
    } catch (IOException ex) {
        handleFatal(null, ex);
        return;
    }
    try {
        while (!selectorthread.isInterrupted()) {
            SelectionKey key = null;
            WebSocketImpl conn = null;
            try {
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> i = keys.iterator();
                while (i.hasNext()) {
                    key = i.next();
                    if (!key.isValid()) {
                        // Object o = key.attachment();
                        continue;
                    }
                    if (key.isAcceptable()) {
                        if (!onConnect(key)) {
                            key.cancel();
                            continue;
                        }
                        SocketChannel channel = server.accept();
                        channel.configureBlocking(false);
                        WebSocketImpl w = wsf.createWebSocket(this, drafts, channel.socket());
                        w.key = channel.register(selector, SelectionKey.OP_READ, w);
                        w.channel = wsf.wrapChannel(channel, w.key);
                        i.remove();
                        allocateBuffers(w);
                        continue;
                    }
                    if (key.isReadable()) {
                        conn = (WebSocketImpl) key.attachment();
                        ByteBuffer buf = takeBuffer();
                        try {
                            if (SocketChannelIOHelper.read(buf, conn, conn.channel)) {
                                if (buf.hasRemaining()) {
                                    conn.inQueue.put(buf);
                                    queue(conn);
                                    i.remove();
                                    if (conn.channel instanceof WrappedByteChannel) {
                                        if (((WrappedByteChannel) conn.channel).isNeedRead()) {
                                            iqueue.add(conn);
                                        }
                                    }
                                } else {
                                    pushBuffer(buf);
                                }
                            } else {
                                pushBuffer(buf);
                            }
                        } catch (IOException e) {
                            pushBuffer(buf);
                            throw e;
                        }
                    }
                    if (key.isWritable()) {
                        conn = (WebSocketImpl) key.attachment();
                        if (SocketChannelIOHelper.batch(conn, conn.channel)) {
                            if (key.isValid()) {
                                key.interestOps(SelectionKey.OP_READ);
                            }
                        }
                    }
                }
                while (!iqueue.isEmpty()) {
                    conn = iqueue.remove(0);
                    WrappedByteChannel c = ((WrappedByteChannel) conn.channel);
                    ByteBuffer buf = takeBuffer();
                    try {
                        if (SocketChannelIOHelper.readMore(buf, conn, c)) {
                            iqueue.add(conn);
                        }
                        if (buf.hasRemaining()) {
                            conn.inQueue.put(buf);
                            queue(conn);
                        } else {
                            pushBuffer(buf);
                        }
                    } catch (IOException e) {
                        pushBuffer(buf);
                        throw e;
                    }
                }
            } catch (CancelledKeyException e) {
            // an other thread may cancel the key
            } catch (ClosedByInterruptException e) {
                // do the same stuff as when InterruptedException is thrown
                return;
            } catch (IOException ex) {
                if (key != null) {
                    key.cancel();
                }
                handleIOException(key, conn, ex);
            } catch (InterruptedException e) {
                // FIXME controlled shutdown (e.g. take care of buffermanagement)
                return;
            }
        }
    } catch (RuntimeException e) {
        // should hopefully never occur
        handleFatal(null, e);
    } finally {
        if (decoders != null) {
            for (WebSocketWorker w : decoders) {
                w.interrupt();
            }
        }
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                onError(null, e);
            }
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) CancelledKeyException(java.nio.channels.CancelledKeyException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) WrappedByteChannel(org.java_websocket.WrappedByteChannel) WebSocketImpl(org.java_websocket.WebSocketImpl)

Aggregations

ClosedByInterruptException (java.nio.channels.ClosedByInterruptException)79 IOException (java.io.IOException)48 ByteBuffer (java.nio.ByteBuffer)15 ClosedChannelException (java.nio.channels.ClosedChannelException)11 SocketTimeoutException (java.net.SocketTimeoutException)9 InetSocketAddress (java.net.InetSocketAddress)7 MappedByteBuffer (java.nio.MappedByteBuffer)7 SocketChannel (java.nio.channels.SocketChannel)7 File (java.io.File)6 ServerSocketChannel (java.nio.channels.ServerSocketChannel)6 ServerSocket (java.net.ServerSocket)5 FileChannel (java.nio.channels.FileChannel)5 FileLockInterruptionException (java.nio.channels.FileLockInterruptionException)5 InterruptedIOException (java.io.InterruptedIOException)4 Path (java.nio.file.Path)4 Test (org.junit.Test)4 BuildId (com.facebook.buck.model.BuildId)3 FileNotFoundException (java.io.FileNotFoundException)3 InputStream (java.io.InputStream)3 SocketException (java.net.SocketException)3