protected InetSocketAddress bindToPort(final String name, final InetAddress hostAddress, String port) { PortsRange portsRange = new PortsRange(port); final AtomicReference<Exception> lastException = new AtomicReference<>(); final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>(); boolean success = portsRange.iterate(portNumber -> { try { Channel channel = bind(name, new InetSocketAddress(hostAddress, portNumber)); synchronized (serverChannels) { List<Channel> list = serverChannels.get(name); if (list == null) { list = new ArrayList<>(); serverChannels.put(name, list); } list.add(channel); boundSocket.set(getLocalAddress(channel)); } } catch (Exception e) { lastException.set(e); return false; } return true; }); if (!success) { throw new BindTransportException("Failed to bind to [" + port + "]", lastException.get()); } if (logger.isDebugEnabled()) { logger.debug("Bound profile [{}] to address {{}}", name, NetworkAddress.format(boundSocket.get())); } return boundSocket.get(); }
/** * Sends back an error response to the caller via the given channel * @param nodeVersion the caller node version * @param channel the channel to send the response to * @param error the error to return * @param requestId the request ID this response replies to * @param action the action this response replies to */ public void sendErrorResponse(Version nodeVersion, Channel channel, final Exception error, final long requestId, final String action) throws IOException { try (BytesStreamOutput stream = new BytesStreamOutput()) { stream.setVersion(nodeVersion); RemoteTransportException tx = new RemoteTransportException( nodeName(), new InetSocketTransportAddress(getLocalAddress(channel)), action, error); threadPool.getThreadContext().writeTo(stream); stream.writeException(tx); byte status = 0; status = TransportStatus.setResponse(status); status = TransportStatus.setError(status); final BytesReference bytes = stream.bytes(); final BytesReference header = buildHeader(requestId, status, nodeVersion, bytes.length()); Runnable onRequestSent = () -> transportServiceAdapter.onResponseSent(requestId, action, error); sendMessage(channel, new CompositeBytesReference(header, bytes), onRequestSent); } }