List of usage examples for io.netty.channel ChannelFuture awaitUninterruptibly
boolean awaitUninterruptibly(long timeoutMillis);
From source file:org.hornetq.core.remoting.impl.netty.NettyConnection.java
License:Apache License
private void closeSSLAndChannel(SslHandler sslHandler, Channel channel) { if (sslHandler != null) { try {/*w w w. ja v a2s .c om*/ ChannelFuture sslCloseFuture = sslHandler.close(); if (!sslCloseFuture.awaitUninterruptibly(10000)) { HornetQClientLogger.LOGGER.timeoutClosingSSL(); } } catch (Throwable t) { // ignore } } ChannelFuture closeFuture = channel.close(); if (!closeFuture.awaitUninterruptibly(10000)) { HornetQClientLogger.LOGGER.timeoutClosingNettyChannel(); } }
From source file:org.scache.network.client.TransportClientFactory.java
License:Apache License
/** Create a completely new {@link TransportClient} to the remote address. */ private TransportClient createClient(InetSocketAddress address) throws IOException { logger.debug("Creating new connection to " + address); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(socketChannelClass) // Disable Nagle's Algorithm since we don't want packets to wait .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs()) .option(ChannelOption.ALLOCATOR, pooledAllocator); final AtomicReference<TransportClient> clientRef = new AtomicReference<>(); final AtomicReference<Channel> channelRef = new AtomicReference<>(); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override//from w w w. java 2 s .c o m public void initChannel(SocketChannel ch) { TransportChannelHandler clientHandler = context.initializePipeline(ch); clientRef.set(clientHandler.getClient()); channelRef.set(ch); } }); // Connect to the remote server long preConnect = System.nanoTime(); ChannelFuture cf = bootstrap.connect(address); if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) { throw new IOException( String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs())); } else if (cf.cause() != null) { throw new IOException(String.format("Failed to connect to %s", address), cf.cause()); } TransportClient client = clientRef.get(); Channel channel = channelRef.get(); assert client != null : "Channel future completed successfully with null client"; // Execute any client bootstraps synchronously before marking the Client as successful. long preBootstrap = System.nanoTime(); logger.debug("Connection to {} successful, running bootstraps...", address); try { for (TransportClientBootstrap clientBootstrap : clientBootstraps) { clientBootstrap.doBootstrap(client, channel); } } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000; logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e); client.close(); throw Throwables.propagate(e); } long postBootstrap = System.nanoTime(); logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address, (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000); return client; }
From source file:org.shelloid.vpt.agent.LocalLink.java
License:Open Source License
public Channel bind(int port) throws Exception { final EventLoopGroup bossGroup = new NioEventLoopGroup(1); final EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 20) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override//from www .j av a 2 s .co m public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new AppSideAgentHandler()); } }); ChannelFuture f = b.bind(port).sync(); final Channel ch = f.channel(); if (f.isSuccess()) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { long timeOut = 1000 * 60 * 5; Platform.shelloidLogger.info("Gracefull shutdown initiated."); ChannelFuture cf = ch.close(); cf.awaitUninterruptibly(timeOut); bossGroup.shutdownGracefully().awaitUninterruptibly(timeOut); workerGroup.shutdownGracefully().awaitUninterruptibly(timeOut); Platform.shelloidLogger.info("Gracefull shutdown finidhed."); } }); return ch; } else { throw new Exception("Can't bind to " + port); } }
From source file:org.shelloid.vpt.rms.server.VPTServer.java
License:Open Source License
public Channel run(ShelloidMX mx) throws Exception { final EventLoopGroup bossGroup = new NioEventLoopGroup(1); final EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w w w . j a v a2s . c o m*/ sslCtx = SslContext.newServerContext( new File(Configurations.get(Configurations.ConfigParams.CHAIN_FILE)), new File(Configurations.get(Configurations.ConfigParams.KEY_FILE))); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new VPTServerInitializer(sslCtx, mx)); final Channel ch = b.bind(port).sync().channel(); Platform.shelloidLogger.warn("VPT Server running on " + Configurations.SERVER_IP + ":" + Configurations.get(Configurations.ConfigParams.SERVER_PORT)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { long timeOut = 1000 * 60 * 5; Platform.shelloidLogger.warn("Gracefull shutdown initiated."); ChannelFuture cf = ch.close(); cf.awaitUninterruptibly(timeOut); bossGroup.shutdownGracefully().awaitUninterruptibly(timeOut); workerGroup.shutdownGracefully().awaitUninterruptibly(timeOut); Platform.shelloidLogger.warn("Gracefull shutdown finished."); } }); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } return null; }
From source file:org.vootoo.client.netty.NettySolrClient.java
License:Apache License
@Override public NamedList<Object> request(SolrRequest request, String collection) throws SolrServerException, IOException { final ProtobufRequestSetter protobufRequestSetter = new ProtobufRequestSetter(); if (collection != null) { protobufRequestSetter.setCollection(collection); }/*w ww .j a va 2 s .com*/ ResponseParser parser = createRequest(request, protobufRequestSetter); final SolrParams solrParams = protobufRequestSetter.getSolrParams(); //CommonParams.TIME_ALLOWED + 20ms int timeout = protobufRequestSetter.getTimeout() + 20; // create rid and ResponsePromise ConnectionPoolContext poolContext = connectionPool.poolContext(); ResponsePromise responsePromise = poolContext.createResponsePromise(); Long rid = responsePromise.getRid(); SolrClientHandler solrClientHandler = null; try { SolrProtocol.SolrRequest protocolRequest = protobufRequestSetter.setRid(rid).buildProtocolRequest(); Channel channel = null; ChannelFuture writeFuture = null; //send netty request try { channel = connectionPool.acquireConnect(); solrClientHandler = SolrClientHandler.getSolrClientHandler(channel); // send request writeFuture = solrClientHandler.writeRequest(channel, protocolRequest, responsePromise); } finally { if (channel != null) { connectionPool.releaseConnect(channel); } } boolean writeDone = writeFuture.awaitUninterruptibly(timeout); if (!writeDone) { //write timeout throw createTimeoutException(rid, timeout, "write request timeout", solrParams); } SolrProtocol.SolrResponse protocolResponse = responsePromise.waitResult(timeout); if (protocolResponse == null) { throw createTimeoutException(rid, timeout, solrParams); } if (logger.isDebugEnabled()) { logger.debug("rid={}, [{}] response size={}", rid, serverUrl(), protocolResponse.getSerializedSize()); } // protocolResponse error if (protocolResponse.getExceptionBodyCount() > 0) { List<VootooException> solrExcs = new ArrayList<>(protocolResponse.getExceptionBodyCount()); VootooException firstE = null; int eNum = 0; //has exception for (SolrProtocol.ExceptionBody e : protocolResponse.getExceptionBodyList()) { VootooException se = ProtobufUtil.toVootooException(e); se.setRemoteServer(serverUrl()); if (se.code() != VootooException.ErrorCode.UNKNOWN.code) { //use first SolrException without ErrorCode.UNKNOWN if (firstE == null) { firstE = se; } } solrExcs.add(se); eNum++; if (logger.isDebugEnabled()) { logger.debug( "[WARN] rid={}, [{}] response exception ({}/{}), code={}, msg={}, meta={}, trace={}", new Object[] { rid, se.getRemoteServer(), eNum, protocolResponse.getExceptionBodyCount(), se.code(), se.getMessage(), se.getMetadata(), se.getRemoteTrace() }); } else if (logger.isInfoEnabled()) { logger.info("[WARN] rid={}, [{}] response exception ({}/{}), code={}, msg={}, meta={}", new Object[] { rid, se.getRemoteServer(), eNum, protocolResponse.getExceptionBodyCount(), se.code(), se.getMessage(), se.getMetadata() }); } } //for exc body if (firstE != null) { logger.warn("rid={}, [{}] response exception, ErrorCode={}, msg={}, meta={}", new Object[] { rid, firstE.getRemoteServer(), firstE.code(), firstE.getMessage(), firstE.getMetadata() }); //meta contain server url throw firstE; } else { //all Exception is ErrorCode.UNKNOWN //convert SolrServerException throw new SolrServerException("rid=" + rid + ", [" + serverUrl() + "] has unknow error", solrExcs.get(0)); } } //has exception InputStream responseInputStream = ProtobufUtil.getSolrResponseInputStream(protocolResponse); if (responseInputStream == null) { // not response body logger.warn("rid={}, [{}] not response body, params={}", rid, serverUrl(), solrParams); throw new SolrServerException( "rid=" + rid + ", [" + serverUrl() + "] not response body, params=" + solrParams); } String charset = ProtobufUtil.getResponseBodyCharset(protocolResponse); return parser.processResponse(responseInputStream, charset); } finally { if (solrClientHandler != null) { solrClientHandler.removeResponsePromise(rid); } } }
From source file:qunar.tc.qmq.netty.client.NettyConnectManageHandler.java
License:Apache License
Channel getOrCreateChannel(final String remoteAddr) throws ClientSendException { if (Strings.isNullOrEmpty(remoteAddr)) { throw new ClientSendException(ClientSendException.SendErrorCode.EMPTY_ADDRESS); }/*from ww w . ja v a2 s . co m*/ ChannelWrapper cw = channelTables.get(remoteAddr); if (cw != null && cw.isOK()) { return cw.getChannel(); } if (!tryLockChannelTable()) { throw new ClientSendException(ClientSendException.SendErrorCode.CREATE_CHANNEL_FAIL, remoteAddr); } try { boolean needCreateChannel = true; cw = channelTables.get(remoteAddr); if (cw != null) { if (cw.isOK()) { return cw.getChannel(); } else if (!cw.getChannelFuture().isDone()) { needCreateChannel = false; } else { channelTables.remove(remoteAddr); } } if (needCreateChannel) { ChannelFuture cf = bootstrap.connect(RemoteHelper.string2SocketAddress(remoteAddr)); LOGGER.debug("begin to connect remote host: {}", remoteAddr); cw = new ChannelWrapper(cf); channelTables.put(remoteAddr, cw); } } catch (Exception e) { LOGGER.error("create channel exception. remoteAddr={}", remoteAddr, e); } finally { channelLock.unlock(); } if (cw != null) { ChannelFuture cf = cw.getChannelFuture(); if (cf.awaitUninterruptibly(connectTimeout)) { if (cw.isOK()) { LOGGER.debug("connect remote host success: {}", remoteAddr); return cw.getChannel(); } else { if (connectFailLogLimit.tryAcquire()) { LOGGER.warn("connect remote host fail: {}. {}", remoteAddr, cf.toString(), cf.cause()); } } } else { if (connectFailLogLimit.tryAcquire()) { LOGGER.warn("connect remote host timeout: {}. {}", remoteAddr, cf.toString()); } } } throw new ClientSendException(ClientSendException.SendErrorCode.CREATE_CHANNEL_FAIL, remoteAddr); }
From source file:sailfish.remoting.channel.AbstractExchangeChannel.java
License:Apache License
private void waitWriteDone(ChannelFuture future, int timeout, RequestProtocol request, boolean needRemoveTrace) throws SailfishException { boolean done = future.awaitUninterruptibly(timeout); if (!done) {/*from w w w . ja va 2 s . c o m*/ // useless at most of time when do writeAndFlush(...) invoke future.cancel(true); if (needRemoveTrace) { getTracer().remove(request.packetId()); } throw new SailfishException(ExceptionCode.WRITE_TIMEOUT, String.format("write to remote[%s] timeout, protocol[%s]", channel.remoteAddress(), request)); } if (!future.isSuccess()) { if (needRemoveTrace) { getTracer().remove(request.packetId()); } throw new SailfishException(ExceptionCode.CHANNEL_WRITE_FAIL, String.format("write to remote[%s] fail, protocol[%s]", channel.remoteAddress(), request), future.cause()); } }