Пример #1
0
    @Override
    public void run(Timeout timeout) throws Exception {
      if (timeout.isCancelled()) {
        return;
      }

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

      State state = (State) ctx.getAttachment();
      long currentTime = System.currentTimeMillis();
      long nextDelay = timeoutMillis - (currentTime - state.lastReadTime);
      if (nextDelay <= 0) {
        // Read timed out - set a new timeout and notify the callback.
        state.timeout = timer.newTimeout(this, timeoutMillis, TimeUnit.MILLISECONDS);
        try {
          // FIXME This should be called from an I/O thread.
          //       To be fixed in Netty 4.
          readTimedOut(ctx);
        } catch (Throwable t) {
          fireExceptionCaught(ctx, t);
        }
      } else {
        // Read occurred before the timeout - set a new timeout with shorter delay.
        state.timeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
      }
    }
  @Override
  public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    if (LOG.isTraceEnabled()) {
      LOG.trace("Channel closed: {}", ctx.getChannel());
    }

    Exchange exchange = getExchange(ctx);
    AsyncCallback callback = getAsyncCallback(ctx);

    // remove state
    producer.removeState(ctx.getChannel());

    // to keep track of open sockets
    producer.getAllChannels().remove(ctx.getChannel());

    if (producer.getConfiguration().isSync() && !messageReceived && !exceptionHandled) {
      // To avoid call the callback.done twice
      exceptionHandled = true;
      // session was closed but no message received. This could be because the remote server had an
      // internal error
      // and could not return a response. We should count down to stop waiting for a response
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Channel closed but no message received from address: {}",
            producer.getConfiguration().getAddress());
      }
      exchange.setException(
          new CamelExchangeException(
              "No response received from remote server: "
                  + producer.getConfiguration().getAddress(),
              exchange));
      // signal callback
      callback.done(false);
    }
  }
 @Override
 public void incomingMessage(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
   if (event.getMessage() instanceof MappingHttpRequest) {
     MappingHttpRequest httpRequest = (MappingHttpRequest) event.getMessage();
     if (httpRequest.getMessage() instanceof WalrusRequestType) {
       WalrusRequestType request = (WalrusRequestType) httpRequest.getMessage();
       BucketLogData logData = request.getLogData();
       if (logData != null) {
         long currentTime = System.currentTimeMillis();
         logData.setTotalTime(currentTime);
         logData.setTurnAroundTime(currentTime);
         logData.setUri(httpRequest.getUri());
         String referrer = httpRequest.getHeader(HttpHeaders.Names.REFERER);
         if (referrer != null) logData.setReferrer(referrer);
         String userAgent = httpRequest.getHeader(HttpHeaders.Names.USER_AGENT);
         if (userAgent != null) logData.setUserAgent(userAgent);
         logData.setTimestamp(
             String.format("[%1$td/%1$tb/%1$tY:%1$tH:%1$tM:%1$tS %1$tz]", Calendar.getInstance()));
         User user = Contexts.lookup(httpRequest.getCorrelationId()).getUser();
         if (user != null) logData.setAccessorId(user.getUserId());
         if (request.getBucket() != null) logData.setBucketName(request.getBucket());
         if (request.getKey() != null) logData.setKey(request.getKey());
         if (ctx.getChannel().getRemoteAddress() instanceof InetSocketAddress) {
           InetSocketAddress sockAddress = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
           logData.setSourceAddress(sockAddress.getAddress().getHostAddress());
         }
       }
     }
   }
 }
Пример #4
0
  /**
   * Starts an SSL / TLS handshake for the specified channel.
   *
   * @return a {@link ChannelFuture} which is notified when the handshake succeeds or fails.
   */
  public ChannelFuture handshake() {
    if (handshaken && !isEnableRenegotiation()) {
      throw new IllegalStateException("renegotiation disabled");
    }

    ChannelHandlerContext ctx = this.ctx;
    Channel channel = ctx.getChannel();
    ChannelFuture handshakeFuture;
    synchronized (handshakeLock) {
      if (handshaking) {
        return this.handshakeFuture;
      } else {
        handshaking = true;
        try {
          engine.beginHandshake();
          runDelegatedTasks();
          handshakeFuture = this.handshakeFuture = future(channel);
        } catch (SSLException e) {
          handshakeFuture = this.handshakeFuture = failedFuture(channel, e);
        }
      }
    }

    try {
      wrapNonAppData(ctx, channel);
    } catch (SSLException e) {
      handshakeFuture.setFailure(e);
    }
    return handshakeFuture;
  }
  protected void increaseCounter(Runnable task) {
    if (!shouldCount(task)) {
      return;
    }

    Settings settings = this.settings;
    long maxChannelMemorySize = settings.maxChannelMemorySize;

    int increment = settings.objectSizeEstimator.estimateSize(task);

    if (task instanceof ChannelEventRunnable) {
      ChannelEventRunnable eventTask = (ChannelEventRunnable) task;
      eventTask.estimatedSize = increment;
      Channel channel = eventTask.getEvent().getChannel();
      long channelCounter = getChannelCounter(channel).addAndGet(increment);
      // System.out.println("IC: " + channelCounter + ", " + increment);
      if (maxChannelMemorySize != 0 && channelCounter >= maxChannelMemorySize && channel.isOpen()) {
        if (channel.isReadable()) {
          // System.out.println("UNREADABLE");
          ChannelHandlerContext ctx = eventTask.getContext();
          if (ctx.getHandler() instanceof ExecutionHandler) {
            // readSuspended = true;
            ctx.setAttachment(Boolean.TRUE);
          }
          channel.setReadable(false);
        }
      }
    } else {
      ((MemoryAwareRunnable) task).estimatedSize = increment;
    }

    if (totalLimiter != null) {
      totalLimiter.increase(increment);
    }
  }
  private boolean handleRevision1Response(ChannelHandlerContext ctx, int payloadLength)
      throws Exception {
    int code = buffered.readInt();

    int descriptionLength = buffered.readInt();
    byte[] descBytes = new byte[descriptionLength];
    buffered.readBytes(descBytes, 0, descBytes.length);

    String description = new String(descBytes, StandardCharsets.UTF_8);

    logger.debug(
        "Decoded payload with length:[{}], code:[{}], descriptionLength:[{}], description:[{}] on connection [{}]",
        payloadLength,
        code,
        descriptionLength,
        description,
        ctx.getChannel().getLocalAddress());

    if (200 <= code && code <= 299) {
      logger.info(
          "Connected to Found Elasticsearch: [{}]: [{}] on connection [{}]",
          code,
          description,
          ctx.getChannel().getLocalAddress());
      return true;
    } else {
      logger.error(
          "Unable to connect to Found Elasticsearch: [{}]: [{}] on connection [{}]",
          code,
          description,
          ctx.getChannel().getLocalAddress());
      return false;
    }
  }
  @Override
  @SuppressWarnings("unchecked")
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    S serverChannel = (S) ctx.getAttachment();

    T childChannel = createChildChannel(serverChannel, e.getChannel());
    fireChannelOpen(childChannel);

    ChannelAddress localAddress = serverChannel.getLocalAddress();
    childChannel.setLocalAddress(localAddress);
    childChannel.setBound();
    fireChannelBound(childChannel, localAddress);

    ctx.setAttachment(childChannel);

    ctx.sendUpstream(e);

    // TODO: fire CONNECTED_BARRIER event to next pipeline
    // then fire CONNECTED event when future completes successfully
    ChannelAddress remoteAddress = localAddress.newEphemeralAddress();
    childChannel.setRemoteAddress(remoteAddress);
    childChannel.setConnected();
    fireChannelConnected(childChannel, remoteAddress);
  }
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    getLogger(ctx.getChannel()).debug("Error while processing imap request", e.getCause());

    if (e.getCause() instanceof TooLongFrameException) {

      // Max line length exceeded
      // See RFC 2683 section 3.2.1
      //
      // "For its part, a server should allow for a command line of at
      // least
      // 8000 octets. This provides plenty of leeway for accepting
      // reasonable
      // length commands from clients. The server should send a BAD
      // response
      // to a command that does not end within the server's maximum
      // accepted
      // command length."
      //
      // See also JAMES-1190
      ImapResponseComposer composer = (ImapResponseComposer) ctx.getAttachment();
      composer.untaggedResponse(
          ImapConstants.BAD + " failed. Maximum command line length exceeded");
    } else {
      // logout on error not sure if that is the best way to handle it
      final ImapSession imapSession = (ImapSession) attributes.get(ctx.getChannel());
      if (imapSession != null) imapSession.logout();

      // Make sure we close the channel after all the buffers were flushed out
      Channel channel = ctx.getChannel();
      if (channel.isConnected()) {
        channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
      }
    }
  }
  private void cleanup(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try {
      ChannelBuffer cumulation = this.cumulation;
      if (cumulation == null) {
        return;
      } else {
        this.cumulation = null;
      }

      if (cumulation.readable()) {
        // Make sure all frames are read before notifying a closed
        // channel.
        callDecode(ctx, ctx.getChannel(), cumulation, null);
      }

      // Call decodeLast() finally. Please note that decodeLast() is
      // called even if there's nothing more to read from the buffer to
      // notify a user that the connection was closed explicitly.
      Object partialFrame = decodeLast(ctx, ctx.getChannel(), cumulation);
      if (partialFrame != null) {
        Channels.fireMessageReceived(ctx, partialFrame, null);
      }
    } finally {
      ctx.sendUpstream(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);
  }
Пример #11
0
 @Override
 public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e)
     throws Exception {
   final MappingHttpRequest request = MappingHttpMessage.extractMessage(e);
   final BaseMessage msg = BaseMessage.extractMessage(e);
   if (msg != null) {
     try {
       final Class<? extends ComponentId> compClass = ComponentMessages.lookup(msg);
       ComponentId compId = ComponentIds.lookup(compClass);
       if (compId.isAlwaysLocal() || Topology.isEnabledLocally(compClass)) {
         ctx.sendUpstream(e);
       } else {
         Handlers.sendRedirect(ctx, e, compClass, request);
       }
     } catch (final NoSuchElementException ex) {
       LOG.warn(
           "Failed to find reverse component mapping for message type: " + msg.getClass());
       ctx.sendUpstream(e);
     } catch (final Exception ex) {
       Logs.extreme().error(ex, ex);
       ctx.sendUpstream(e);
     }
   } else {
     ctx.sendUpstream(e);
   }
 }
Пример #12
0
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
     throws Exception {
   Session session = new Session(ctx.getChannel());
   netHandler.onConnected(session);
   ctx.setAttachment(session);
 }
Пример #13
0
  @Override
  protected Object decode(
      ChannelHandlerContext context, Channel channel, ChannelBuffer buffer, VoidEnum state)
      throws Exception {
    int opcode = buffer.readUnsignedByte();
    MessageCodec<?> codec = CodecLookupService.find(opcode);

    if (codec == null) {
      OpenClassic.getLogger()
          .warning(
              "Invalid packet ID "
                  + opcode
                  + "! (previous ID = "
                  + this.previousOpcode
                  + ") Disconnecting user...");

      if (context.getAttachment() instanceof ServerSession) {
        ((ServerSession) context.getAttachment()).disconnect("Invalid packet ID " + opcode + "!");
      } else {
        channel.disconnect();
      }

      return null;
    }

    this.previousOpcode = opcode;

    return codec.decode(buffer);
  }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    if (event.getMessage() instanceof MappingHttpRequest) {
      MappingHttpRequest httpRequest = (MappingHttpRequest) event.getMessage();

      if (httpRequest.getMessage() instanceof ObjectStorageDataRequestType) {
        if (httpRequest.isChunked()) {
          // Chunked request, and beginning, setup map etc.
          initializeNewPut(ctx, (ObjectStorageDataRequestType) httpRequest.getMessage());
        }
      }
    } else if (event.getMessage() instanceof HttpChunk) {
      // Add the chunk to the current streams channel buffer.
      HttpChunk chunk = (HttpChunk) event.getMessage();
      appendChunk(chunk.getContent(), ctx.getChannel());

      if (chunk.isLast()) {
        // Remove from the map
        Logs.extreme()
            .debug(
                "Removing data map due to last chunk processed event for channel: "
                    + ctx.getChannel().getId());
        dataMap.remove(ctx.getChannel());
      }
    }
    // Always pass it on
    ctx.sendUpstream(event);
  }
Пример #15
0
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   context.getWorkers().put(ctx.getChannel(), new MasterWorkerHolder(ctx.getChannel()));
   Channel channel = ctx.getChannel();
   SocketAddress addr = channel.getRemoteAddress();
   SocketLog.info("worker connected , :" + addr.toString());
   super.channelConnected(ctx, e);
 }
Пример #16
0
  @Override
  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    super.channelDisconnected(ctx, e);

    if (!ctx.getChannel().isConnected()) {
      tryToFinishOffChannel(ctx.getChannel());
    }
  }
Пример #17
0
  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    logger.error(
        "something goes wrong with channel:{}, exception={}",
        ctx.getChannel(),
        ExceptionUtils.getStackTrace(e.getCause()));

    ctx.getChannel().close();
  }
Пример #18
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
    if (!(me.getMessage() instanceof HttpRequest)) {
      ctx.sendUpstream(me);
      return;
    }

    HttpRequest request = (HttpRequest) me.getMessage();
    Object response;

    // Look up resource
    String path = request.getUri();
    String host = request.getHeader("host");
    log.debug("Received request for path:" + path);

    boolean showHtml = false;
    if (path.endsWith("?html")) {
      showHtml = true;
      path = path.replace("?html", "");
    }

    for (String service : resources.keySet()) {
      log.debug("Available Service: " + service);
    }

    Model model = resources.get(path);

    if (model != null) {
      if (request.getMethod() == HttpMethod.GET) {
        if (showHtml) {
          String html = HtmlCreator.createModelPage(model, new URI(path), host);
          response = ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8")));

          log.debug("Returned html page for resource: " + path);
        } else {
          response = new SelfDescription(model, new URI(request.getUri()));

          log.debug("Resource found: " + path);
        }
      } else {
        response =
            new DefaultHttpResponse(
                request.getProtocolVersion(), HttpResponseStatus.METHOD_NOT_ALLOWED);

        log.debug("Method not allowed: " + request.getMethod());
      }
    } else {
      response =
          HttpResponseFactory.createHttpResponse(
              request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND);

      log.debug("Resource not found: " + path);
    }

    // Send response
    ChannelFuture future = Channels.write(ctx.getChannel(), response);
    future.addListener(ChannelFutureListener.CLOSE);
  }
  @Override
  public void channelBound(final ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    ImapSession imapsession =
        new NettyImapSession(
            ctx.getChannel(), logger, context, enabledCipherSuites, compress, plainAuthDisallowed);
    attributes.set(ctx.getChannel(), imapsession);
    super.channelBound(ctx, e);
  }
  @BeforeMethod
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    handler = new SyslogTCPFramingRouterHandler(2048, Delimiters.lineDelimiter());

    when(context.getPipeline()).thenReturn(pipeline);
    when(context.getName()).thenReturn("current");
  }
 private void receivedConnect(NetData.JoinMessage message) {
   logger.info("Received Start Join");
   NetClient client = new NetClient(channelHandlerContext.getChannel(), networkSystem, identity);
   client.setPreferredName(message.getName());
   client.setColor(new Color(message.getColor().getRgba()));
   client.setViewDistanceMode(ViewDistance.forIndex(message.getViewDistanceLevel()));
   channelHandlerContext.getPipeline().remove(this);
   serverHandler.connectionComplete(client);
 }
Пример #22
0
 private void handleInitialize(ChannelHandlerContext ctx, MappingHttpRequest request)
     throws IOException, SocketException {
   InetSocketAddress addr = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
   LOG.info(LogUtil.subheader("Using " + addr.getHostName() + " as the database address."));
   Component.db.setHostAddress(addr.getHostName());
   Component.db.markEnabled();
   Component.dns.setHostAddress(addr.getHostName());
   Component.eucalyptus.setHostAddress(addr.getHostName());
   Component.cluster.setHostAddress(addr.getHostName());
   Component.jetty.setHostAddress(addr.getHostName());
   HeartbeatType msg = (HeartbeatType) request.getMessage();
   LOG.info(LogUtil.header("Got heartbeat event: " + LogUtil.dumpObject(msg)));
   for (HeartbeatComponentType component : msg.getComponents()) {
     LOG.info(LogUtil.subheader("Registering local component: " + LogUtil.dumpObject(component)));
     System.setProperty("euca." + component.getComponent() + ".name", component.getName());
     Component.valueOf(component.getComponent()).markLocal();
     // FIXME: this is needed because we can't dynamically change the mule config, so we need to
     // disable at init time and hup when a new component is loaded.
     initializedComponents.add(component.getComponent());
   }
   // FIXME: this is needed because we can't dynamically change the mule config, so we need to
   // disable at init time and hup when a new component is loaded.
   if (!initializedComponents.contains(Component.storage.name())) {
     Component.storage.markDisabled();
   }
   // FIXME: this is needed because we can't dynamically change the mule config, so we need to
   // disable at init time and hup when a new component is loaded.
   if (!initializedComponents.contains(Component.walrus.name())) {
     Component.walrus.markDisabled();
   }
   System.setProperty("euca.db.password", Hashes.getHexSignature());
   System.setProperty("euca.db.url", Component.db.getUri().toASCIIString());
   boolean foundDb = false;
   try {
     foundDb = NetworkUtil.testReachability(addr.getHostName());
     LOG.debug("Initializing SSL just in case: " + SslSetup.class);
     foundDb = true;
   } catch (Throwable e) {
     foundDb = false;
   }
   if (foundDb) {
     HttpResponse response =
         new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
     ChannelFuture writeFuture = ctx.getChannel().write(response);
     writeFuture.addListener(ChannelFutureListener.CLOSE);
     initialized = true;
     if (this.channel != null) {
       this.channel.close();
     }
   } else {
     HttpResponse response =
         new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_ACCEPTABLE);
     ChannelFuture writeFuture = ctx.getChannel().write(response);
     writeFuture.addListener(ChannelFutureListener.CLOSE);
   }
 }
 /** Invoked when a connection is closed */
 @Override
 public final void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
   GameSession session = (GameSession) ctx.getAttachment();
   if (session != null) {
     synchronized (LogicService.getWorkerThread()) {
       World.getSingleton().unregisterPlayer(session.getPlayer());
     }
   }
   ctx.getChannel().close();
 }
Пример #24
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());
  }
 /* (non-Javadoc)
  * @see org.jboss.netty.channel.ChannelFutureListener#operationComplete(org.jboss.netty.channel.ChannelFuture)
  */
 @Override
 public void operationComplete(ChannelFuture future) throws Exception {
   if (upstreamContext != null && bgpEvent != null) {
     upstreamContext.sendUpstream(
         new UpstreamMessageEvent(
             upstreamContext.getChannel(),
             bgpEvent,
             upstreamContext.getChannel().getRemoteAddress()));
   }
 }
Пример #26
0
 /**
  * Sends an SSL {@code close_notify} message to the specified channel and destroys the underlying
  * {@link SSLEngine}.
  */
 public ChannelFuture close() {
   ChannelHandlerContext ctx = this.ctx;
   Channel channel = ctx.getChannel();
   try {
     engine.closeOutbound();
     return wrapNonAppData(ctx, channel);
   } catch (SSLException e) {
     return failedFuture(channel, e);
   }
 }
Пример #27
0
    @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);
    }
Пример #28
0
 @Override
 public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e)
     throws Exception {
   if (!Bootstrap.isFinished()) {
     // TODO:GRZE: do nothing for the moment, not envouh info here.
     //        throw new ServiceNotReadyException( "System has not yet completed booting." );
     ctx.sendUpstream(e);
   } else {
     ctx.sendUpstream(e);
   }
 }
Пример #29
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
   Route route = app.getRouter().parseRoute(getUtf(buffer));
   byte[] data = new byte[buffer.readableBytes()];
   buffer.readBytes(data);
   LocalSession localSession = sessions.getSession(ctx.getChannel().getId()).getLocalSession();
   byte[] response = server.handle(route, localSession, data);
   if (response != null) {
     ctx.getChannel().write(response);
   }
 }
Пример #30
0
  @Override
  public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent ce) throws Exception {
    if (!(ce instanceof MessageEvent)) {
      ctx.sendUpstream(ce);
      return;
    }
    MessageEvent e = (MessageEvent) ce;
    RedisConnection conn = (RedisConnection) e.getChannel().getAttachment();
    ChannelBuffer cb = (ChannelBuffer) e.getMessage();
    conn.replyFromBackend(cb.copy());

    ctx.sendUpstream(ce);
  }