@Override
 public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   if (e.getMessage() instanceof KafkaRequest) {
     ctx.setAttachment(((KafkaRequest) e.getMessage()).getResponseHandler());
   }
   super.writeRequested(ctx, e);
 }
Example #2
0
 @Override
 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   Channel channel = e.getChannel();
   logger.info("channel disconnected at :{}", channel);
   streamClientListener.onDisconnected(channel);
   super.channelDisconnected(ctx, e);
 }
  /**
   * Detects if we're connecting to a Found Elasticsearch cluster (using pre-configured host
   * suffixes) and adds a SSL handler at the beginning of the pipeline if we're connecting to a
   * SSL-endpoint (using a list of pre-configured ports).
   */
  @Override
  public void connectRequested(final ChannelHandlerContext ctx, final ChannelStateEvent e)
      throws Exception {
    if (e.getValue() instanceof InetSocketAddress) {
      InetSocketAddress inetSocketAddress = (InetSocketAddress) e.getValue();

      for (String suffix : hostSuffixes) {
        isFoundCluster = isFoundCluster || inetSocketAddress.getHostString().endsWith(suffix);
      }

      if (isFoundCluster) {
        for (int sslPort : sslPorts) {
          if (inetSocketAddress.getPort() == sslPort) {
            logger.debug(
                "Enabling SSL on transport layer with unsafeAllowSelfSigned=[{}].",
                unsafeAllowSelfSigned);
            FoundSSLHandler handler =
                FoundSSLUtils.getSSLHandler(unsafeAllowSelfSigned, inetSocketAddress);
            ctx.getPipeline().addFirst("ssl", handler);
            break;
          }
        }
      } else {
        ctx.getPipeline().remove(this);
      }
    }
    super.connectRequested(ctx, e);
  }
 @Override
 public synchronized void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
     throws Exception {
   if (isFoundCluster && !headerSent) {
     sendHeader(ctx);
   }
   super.channelConnected(ctx, e);
 }
 @Override
 public synchronized void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
     throws Exception {
   if (isFoundCluster && !headerSent) {
     sendHeader(ctx);
   }
   super.writeRequested(ctx, e);
 }
 @Override
 public final void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof MessageEvent && ((MessageEvent) e).getMessage() instanceof Message) {
     Message buffer = (Message) ((MessageEvent) e).getMessage();
     BandwidthMonitor.bytesReceived.addAndGet(buffer.getBuffer().readableBytes());
   }
   super.handleUpstream(ctx, e);
 }
Example #7
0
  @Override
  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    super.channelDisconnected(ctx, e);

    if (!ctx.getChannel().isConnected()) {
      tryToFinishOffChannel(ctx.getChannel());
    }
  }
Example #8
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   if (e.getCause() instanceof ClosedChannelException) {
     // these are part of life
     // XXX Debug logging might be good
     return;
   }
   super.exceptionCaught(ctx, e);
 }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (handshakeComplete) {
      super.messageReceived(ctx, e);
    } else {
      if (e.getMessage() instanceof ChannelBuffer) {
        ChannelBuffer newBuffer = (ChannelBuffer) e.getMessage();
        buffered = ChannelBuffers.copiedBuffer(buffered, newBuffer);

        if (buffered.readableBytes() < 8) {
          return;
        }
        int payloadLength = buffered.getInt(0);
        int revision = buffered.getInt(4);

        boolean handshakeSuccessful = false;

        if (revision == 1 || revision == -1) {
          if (buffered.readableBytes() < payloadLength + 4) {
            return;
          }
          buffered.skipBytes(8);

          if (revision == 1) {
            handshakeSuccessful = handleRevision1Response(ctx, payloadLength);
          } else {
            handshakeSuccessful = handleGenericResponse(ctx, payloadLength);
          }
        } else {
          handshakeSuccessful = handleUnknownRevisionResponse(ctx);
        }

        if (!handshakeSuccessful) {
          ctx.getChannel().close();
        }

        if (keepAliveInterval.millis() > 0) {
          ctx.getPipeline()
              .addBefore(
                  ctx.getName(),
                  "found-connection-keep-alive",
                  new ConnectionKeepAliveHandler(scheduler, keepAliveInterval));
        }

        handshakeComplete = true;

        ChannelBuffer remaining = buffered.slice();
        if (remaining.readableBytes() > 0) {
          ctx.sendUpstream(
              new UpstreamMessageEvent(
                  ctx.getChannel(), remaining, ctx.getChannel().getRemoteAddress()));
        }

        ctx.getPipeline().remove(this);
      }
    }
  }
Example #10
0
 @Override
 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)
     throws Exception {
   PhysicalLocation pl = (PhysicalLocation) ctx.getAttachment();
   if (pl != null) {
     plMap.remove(pl);
   }
   super.channelDisconnected(ctx, e);
 }
  @Override
  public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
    // Log all channel state changes.
    if (e instanceof ChannelStateEvent) {
      //			logger.trace("server : channel state changed: " + e);
    }

    super.handleUpstream(ctx, e);
  }
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   Object attachment = ctx.getAttachment();
   if (e.getMessage() instanceof KafkaResponse && attachment instanceof ResponseHandler) {
     ((ResponseHandler) attachment).received((KafkaResponse) e.getMessage());
   } else {
     super.messageReceived(ctx, e);
   }
 }
Example #13
0
  @Override
  public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    super.channelClosed(ctx, e);

    if (!ctx.getChannel().isOpen()) {
      tryToFinishOffChannel(ctx.getChannel());
    }

    channelGroup.remove(e.getChannel());
  }
    @Override
    public void bindRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
      // apply bind settings before we try to bind the channel
      ChannelConfig channelConfig = ctx.getChannel().getConfig();
      channelConfig.setOption("reuseAddress", config.reuseAddress);
      channelConfig.setOption("backlog", config.backlog);

      // propagate channel open event
      super.bindRequested(ctx, e);
    }
    @Override
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

      // add bind handler to pipeline
      String baseName = ctx.getName();
      String name = format("%s:socket", baseName);
      ctx.getPipeline().addAfter(baseName, name, bindHandler);

      // propagate channel open event
      super.channelOpen(ctx, e);
    }
Example #16
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   // avoid stack overflow when exception happens on close
   if (TRUE != ctx.getAttachment()) {
     ctx.setAttachment(TRUE);
     // close channel and avoid warning logged by default exceptionCaught implementation
     Channel channel = ctx.getChannel();
     channel.close();
   } else {
     // log exception during close
     super.exceptionCaught(ctx, e);
   }
 }
Example #17
0
 @Override
 public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception {
   /*
    * This is here to ensure that channels that have stuff written to them for a long time, long transaction
    * pulls and store copies (mainly the latter), will not timeout and have their transactions rolled back.
    * This is actually not a problem, since both mentioned above have no transaction associated with them
    * but it is more sanitary and leaves less exceptions in the logs
    * Each time a write completes, simply update the corresponding channel's timestamp.
    */
   Pair<RequestContext, AtomicLong> slave = connectedSlaveChannels.get(ctx.getChannel());
   if (slave != null) {
     slave.other().set(clock.currentTimeMillis());
     super.writeComplete(ctx, e);
   }
 }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   if (e.getCause() instanceof ClosedChannelException) {
     // do nothing
   } else if (e.getCause() instanceof UnresolvedAddressException) {
     logger.error(
         "Unable to resolve one of the server addresses: [{}]", e.getCause().getMessage());
   } else if (e.getCause() instanceof ConnectException) {
     logger.error("Unable to connect: [{}]", e.getCause().getMessage());
   } else if (e.getCause().getMessage() != null
       && e.getCause().getMessage().contains("Connection reset by peer")) {
     // still do nothing
   } else {
     super.exceptionCaught(ctx, e);
   }
 }
 @Override
 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof MessageEvent) {
     ChannelBuffer message = (ChannelBuffer) ((MessageEvent) e).getMessage();
     long size = message.readableBytes() * 8;
     if (size < 16000) {
       double d_ns = 62.5;
       Long l = Math.round(size * d_ns);
       Thread.sleep(0, l.intValue());
     } else {
       double d_ms = 0.0000625;
       Thread.sleep(Math.round(size * d_ms));
     }
   }
   super.handleUpstream(ctx, e);
 }
Example #20
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   Object message = ((MessageEvent) e).getMessage();
   if (message instanceof MappingHttpRequest) {
     MappingHttpRequest request = ((MappingHttpRequest) message);
     if (HttpMethod.GET.equals(request.getMethod())) {
       handleGet(ctx, request);
     } else if (!initialized) {
       handleInitialize(ctx, request);
     } else if (request.getMessage() instanceof HeartbeatType) {
       handleHeartbeat(request);
     } else {
       ChannelFuture writeFuture =
           ctx.getChannel()
               .write(
                   new DefaultHttpResponse(
                       request.getProtocolVersion(), HttpResponseStatus.NOT_ACCEPTABLE));
       writeFuture.addListener(ChannelFutureListener.CLOSE);
     }
   } else {
     super.messageReceived(ctx, e);
   }
 }
  /** Expected Message types: - HTTP Requests */
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    if (!(e.getMessage() instanceof HttpRequest)) {
      super.messageReceived(ctx, e);
      return;
    }

    HttpRequest httpRequest = (HttpRequest) e.getMessage();
    URI targetUri =
        toThing(URI.create("http://" + httpRequest.getHeader("HOST") + httpRequest.getUri()));

    log.debug("Received HTTP request for " + targetUri);

    if (httpRequest.getHeader("HOST").contains(DNS_WILDCARD_POSTFIX)) {
      String targetUriHost = InetAddress.getByName(targetUri.getHost()).getHostAddress();
      // remove leading zeros per block
      targetUriHost = targetUriHost.replaceAll(":0000", ":0");
      targetUriHost = targetUriHost.replaceAll(":000", ":0");
      targetUriHost = targetUriHost.replaceAll(":00", ":0");
      targetUriHost = targetUriHost.replaceAll("(:0)([ABCDEFabcdef123456789])", ":$2");

      // return shortened IP
      targetUriHost =
          targetUriHost.replaceAll("((?:(?:^|:)0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2");
      log.debug("Target host: " + targetUriHost);

      String targetUriPath = targetUri.getRawPath();
      log.debug("Target path: " + targetUriPath);

      if (IPAddressUtil.isIPv6LiteralAddress(targetUriHost)) {
        targetUriHost = "[" + targetUriHost + "]";
      }

      targetUri = toThing(URI.create("http://" + targetUriHost + httpRequest.getUri()));
      log.debug("Shortened target URI: " + targetUri);
    }

    URI uriToCheck = targetUri;
    if ((uriToCheck.getQuery() != null) && (uriToCheck.getQuery().equals("html"))) {
      uriToCheck = toThing(URI.create("http://" + targetUri.getHost() + targetUri.getPath()));
    }

    if (entities.containsKey(uriToCheck)) {
      Backend backend = entities.get(uriToCheck);
      try {
        ctx.getPipeline().remove("Backend to handle request");
      } catch (NoSuchElementException ex) {
        // Fine. There was no handler to be removed.
      }
      ctx.getPipeline().addLast("Backend to handle request", backend);
      log.debug("Forward request to " + backend);
    } else if (virtualEntities.containsKey(uriToCheck)) {
      Backend backend = virtualEntities.get(uriToCheck);
      try {
        ctx.getPipeline().remove("Backend to handle request");
      } catch (NoSuchElementException ex) {
        // Fine. There was no handler to be removed.
      }
      ctx.getPipeline().addLast("Backend to handle request", backend);
      log.debug("Forward request to " + backend);
    }

    //        else if (targetUriPath.equals(PATH_TO_SERVER_LIST)) {
    //            // Handle request for resource at path ".well-known/core"
    //            StringBuilder buf = new StringBuilder();
    //            for(URI entity: getServices()) {
    //                buf.append(toThing(entity).toString() + "\n");
    //            }
    //            Channels.write(ctx.getChannel(),
    // Answer.create(buf.toString()).setMime("text/plain"));
    //            return;
    //        }

    //        else if("/visualizer".equals(targetUriPath)){
    //            try {
    //                ctx.getPipeline().remove("Backend to handle request");
    //            }
    //            catch(NoSuchElementException ex) {
    //                //Fine. There was no handler to be removed.
    //            }
    //            ctx.getPipeline().addLast("VisualizerService", VisualizerService.getInstance());
    //            log.debug("Forward request to visualizer.");
    //        }

    /*else if(targetUriPath.startsWith(SERVER_PATH_TO_SLSE_UI)) {
    	String f = LOCAL_PATH_TO_SLSE_UI + targetUriPath.substring(SERVER_PATH_TO_SLSE_UI.length());
    	Channels.write(ctx.getChannel(), Answer.create(new File(f)).setMime("text/n3"));
    }*/

    else if ("/".equals(targetUri.getRawPath())) {
      HttpResponse httpResponse =
          new DefaultHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK);

      httpResponse.setContent(getHtmlListOfServices());
      ChannelFuture future = Channels.write(ctx.getChannel(), httpResponse);
      future.addListener(ChannelFutureListener.CLOSE);
      return;
    } else if (httpRequest.getUri().endsWith("spitfire-logo.png")
        || (httpRequest.getUri().endsWith("favicon.ico"))) {
      File img;
      if (httpRequest.getUri().endsWith("spitfire-logo.png")) {
        img = new File("spitfire-logo.png");
      } else {
        img = new File("favicon.ico");
      }

      int imgLength = (int) img.length();

      FileInputStream in = new FileInputStream(img);
      byte[] imgMemory = new byte[imgLength];
      in.read(imgMemory);
      in.close();

      HttpResponse httpResponse =
          new DefaultHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK);
      httpResponse.setContent(ChannelBuffers.wrappedBuffer(imgMemory));
      ChannelFuture future = Channels.write(ctx.getChannel(), httpResponse);
      future.addListener(ChannelFutureListener.CLOSE);

      if (httpRequest.getUri().endsWith("spitfire-logo.png")) {
        log.debug("Served request for Spitfire image.");
      } else {
        log.debug("Served favicon.");
      }

      return;
    }

    ctx.sendUpstream(e);
  }
Example #22
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   e.getFuture().addListener(ChannelFutureListener.CLOSE);
   super.exceptionCaught(ctx, e);
 }
Example #23
0
 @Override
 public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception {
   super.writeComplete(ctx, e);
 }
Example #24
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   ChannelBuffer channelBuffer = (ChannelBuffer) e.getMessage();
   logger.info("message received :{}", channelBuffer.readableBytes());
   super.messageReceived(ctx, e);
 }
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   // TODO Auto-generated method stub
   super.channelClosed(ctx, e);
 }