use of org.jboss.netty.channel.ChannelFutureListener in project jstorm by alibaba.
the class NettyClient method flushRequest.
protected void flushRequest(Channel channel, final NettyMessage requests) {
if (requests == null || requests.isEmpty())
return;
Long batchSize = (long) requests.getEncodedLength();
pendings.incrementAndGet();
if (this.enableNettyMetrics && sendSpeed != null) {
sendSpeed.update(batchSize);
}
NettyMetricInstance.totalSendSpeed.update(batchSize);
if (MetricUtils.metricAccurateCal) {
NettyMetricInstance.batchSizeWorkerHistogram.update(batchSize);
}
ChannelFuture future = channel.write(requests);
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
pendings.decrementAndGet();
if (!future.isSuccess()) {
Channel channel = future.getChannel();
if (!isClosed()) {
LOG.info("Failed to send requests to " + name + ": " + channel.toString() + ":", future.getCause());
}
if (null != channel) {
exceptionChannel(channel);
}
}
}
});
}
use of org.jboss.netty.channel.ChannelFutureListener in project load-balancer by RestComm.
the class HttpRequestHandler method handleHttpRequest.
private void handleHttpRequest(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
String currAddress = e.getRemoteAddress().toString();
semaphore = semaphoreMap.get(currAddress);
if (semaphore == null) {
semaphore = new Semaphore(1);
Semaphore tempSemaphore = semaphoreMap.putIfAbsent(currAddress, semaphore);
if (tempSemaphore != null)
semaphore = tempSemaphore;
}
try {
semaphore.acquire();
} catch (InterruptedException ex) {
}
if (!readingChunks && e.getMessage() instanceof HttpRequest) {
request = (HttpRequest) e.getMessage();
if (logger.isDebugEnabled()) {
logger.debug("Request URI accessed: " + request.getUri() + " channel " + e.getChannel());
}
if (HttpChannelAssociations.urlRewriteFilter != null)
HttpChannelAssociations.urlRewriteFilter.doFilter(request, e);
AdvancedChannel currentAC = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
Channel associatedChannel = null;
if (currentAC != null)
associatedChannel = currentAC.getChannel();
InvocationContext invocationContext = balancerRunner.getLatestInvocationContext();
// SIPNode node = null;
try {
// TODO: If WebSocket request, choose a NODE that is able to
// handle WebSocket requests (has a websocket connector)
node = invocationContext.balancerAlgorithm.processHttpRequest(request);
} catch (Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
logger.warn("Problem in balancer algorithm", ex);
writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Load Balancer Error: Exception in the balancer algorithm:\n" + sw.toString());
return;
}
if (node == null) {
if (logger.isInfoEnabled()) {
logger.info("Service unavailable. No server is available.");
}
writeResponse(e, HttpResponseStatus.SERVICE_UNAVAILABLE, IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("500.html")));
return;
}
if (associatedChannel != null && associatedChannel.isConnected()) {
semaphore.release();
associatedChannel.write(request);
} else {
e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
// Start the connection attempt.
ChannelFuture future = null;
Set<String> headers = request.getHeaderNames();
if (headers.contains("Sec-WebSocket-Protocol")) {
if (request.getHeader("Sec-WebSocket-Protocol").equalsIgnoreCase("sip")) {
if (logger.isDebugEnabled()) {
logger.debug("New SIP over WebSocket request. WebSocket uri: " + request.getUri());
logger.debug("Dispatching WebSocket request to node: " + node.getIp() + " port: " + node.getProperties().get("wsPort"));
}
wsrequest = true;
wsVersion = request.getHeader(Names.SEC_WEBSOCKET_VERSION);
websocketServerPipelineFactory = new WebsocketModifyClientPipelineFactory();
future = HttpChannelAssociations.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("wsPort"))));
}
} else {
if (!isSecured) {
if (logger.isDebugEnabled()) {
logger.debug("Dispatching HTTP request to node: " + node.getIp() + " port: " + node.getProperties().get("httpPort"));
}
future = HttpChannelAssociations.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("httpPort"))));
} else {
if (logger.isDebugEnabled()) {
logger.debug("Dispatching HTTPS request to node: " + node.getIp() + " port: " + node.getProperties().get("sslPort"));
}
future = HttpChannelAssociations.inboundSecureBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("sslPort"))));
}
}
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
Channel channel = arg0.getChannel();
if (pattern != null && pattern.matcher(request.getUri()).find()) {
logger.info("request : " + request.getUri() + " matches to pattern : " + pattern);
HttpChannelAssociations.channels.put(new AdvancedChannel(e.getChannel(), true), new AdvancedChannel(channel, true));
HttpChannelAssociations.channels.put(new AdvancedChannel(channel, true), new AdvancedChannel(e.getChannel(), true));
} else {
HttpChannelAssociations.channels.put(new AdvancedChannel(e.getChannel(), false), new AdvancedChannel(channel, false));
HttpChannelAssociations.channels.put(new AdvancedChannel(channel, false), new AdvancedChannel(e.getChannel(), false));
}
if (request.isChunked()) {
readingChunks = true;
}
semaphore.release();
channel.write(request);
if (wsrequest) {
if (logger.isDebugEnabled()) {
logger.debug("This is a websocket request, changing the pipeline");
}
// Modify the Client Pipeline - Phase 1
ChannelPipeline p = channel.getPipeline();
websocketServerPipelineFactory.upgradeClientPipelineFactoryPhase1(p, wsVersion);
}
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
closeChannelPair(arg0.getChannel());
}
});
}
});
}
} else {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
readingChunks = false;
}
semaphore.release();
HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel())).getChannel().write(chunk);
if (logger.isDebugEnabled())
logger.debug("Send chunked request from : " + e.getChannel().getLocalAddress() + " to : " + e.getChannel().getRemoteAddress() + " capacity : " + chunk.getContent().capacity());
}
}
use of org.jboss.netty.channel.ChannelFutureListener in project weave by continuuity.
the class SimpleKafkaClient method getOffset.
@Override
public ListenableFuture<long[]> getOffset(final String topic, final int partition, long time, int maxOffsets) {
final SettableFuture<long[]> resultFuture = SettableFuture.create();
final ChannelBuffer body = ChannelBuffers.buffer(Longs.BYTES + Ints.BYTES);
body.writeLong(time);
body.writeInt(maxOffsets);
connectionPool.connect(getTopicBroker(topic, partition).getAddress()).getChannelFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (checkFailure(future)) {
return;
}
future.getChannel().write(KafkaRequest.createOffsets(topic, partition, body, new ResponseHandler() {
@Override
public void received(KafkaResponse response) {
if (response.getErrorCode() != FetchException.ErrorCode.OK) {
resultFuture.setException(new FetchException("Failed to fetch offset.", response.getErrorCode()));
} else {
// Decode the offset response, which contains 4 bytes number of offsets, followed by number of offsets,
// each 8 bytes in size.
ChannelBuffer resultBuffer = response.getBody();
int size = resultBuffer.readInt();
long[] result = new long[size];
for (int i = 0; i < size; i++) {
result[i] = resultBuffer.readLong();
}
resultFuture.set(result);
}
}
})).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
checkFailure(future);
}
});
}
private boolean checkFailure(ChannelFuture future) {
if (!future.isSuccess()) {
if (future.isCancelled()) {
resultFuture.cancel(true);
} else {
resultFuture.setException(future.getCause());
}
return true;
}
return false;
}
});
return resultFuture;
}
use of org.jboss.netty.channel.ChannelFutureListener in project crate by crate.
the class Messages method sendReadyForQuery.
/**
* ReadyForQuery (B)
* <p>
* Byte1('Z')
* Identifies the message type. ReadyForQuery is sent whenever the
* backend is ready for a new query cycle.
* <p>
* Int32(5)
* Length of message contents in bytes, including self.
* <p>
* Byte1
* Current backend transaction status indicator. Possible values are
* 'I' if idle (not in a transaction block); 'T' if in a transaction
* block; or 'E' if in a failed transaction block (queries will be
* rejected until block is ended).
*/
static void sendReadyForQuery(Channel channel) {
ChannelBuffer buffer = ChannelBuffers.buffer(6);
buffer.writeByte('Z');
buffer.writeInt(5);
buffer.writeByte('I');
ChannelFuture channelFuture = channel.write(buffer);
if (LOGGER.isTraceEnabled()) {
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
LOGGER.trace("sentReadyForQuery");
}
});
}
}
use of org.jboss.netty.channel.ChannelFutureListener in project neo4j by neo4j.
the class NetworkSender method send.
private synchronized void send(final Message message) {
monitor.queuedMessage(message);
final URI to = URI.create(message.getHeader(Message.TO));
ExecutorService senderExecutor = senderExecutors.get(to);
if (senderExecutor == null) {
senderExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("Cluster Sender " + to.toASCIIString(), monitor));
senderExecutors.put(to, senderExecutor);
}
senderExecutor.submit(new Runnable() {
@Override
public void run() {
Channel channel = getChannel(to);
try {
if (channel == null) {
channel = openChannel(to);
openedChannel(to, channel);
// Instance could be connected to, remove any marker of it being failed
failedInstances.remove(to);
}
} catch (Exception e) {
// Only print out failure message on first fail
if (!failedInstances.contains(to)) {
msgLog.warn(e.getMessage());
failedInstances.add(to);
}
return;
}
try {
// Set FROM header
message.setHeader(Message.FROM, me.toASCIIString());
msgLog.debug("Sending to " + to + ": " + message);
ChannelFuture future = channel.write(message);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
monitor.sentMessage(message);
if (!future.isSuccess()) {
msgLog.debug("Unable to write " + message + " to " + future.getChannel(), future.getCause());
closedChannel(future.getChannel());
// Try again
send(message);
}
}
});
} catch (Exception e) {
if (Exceptions.contains(e, ClosedChannelException.class)) {
msgLog.warn("Could not send message, because the connection has been closed.");
} else {
msgLog.warn("Could not send message", e);
}
channel.close();
}
}
});
}
Aggregations