Ejemplo n.º 1
0
    /** Send the message over the channel specified by the message. */
    protected void write(Channel channel, PaxosMessage msg) {
      ChannelFuture future;

      // Send out a command.
      future = channel.write(msg); // Write the contents to the channel.
      future.addListener(this);
    }
Ejemplo n.º 2
0
  public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = Integer.parseInt("8080");

    ChannelFactory factory =
        new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

    ClientBootstrap bootstrap = new ClientBootstrap(factory);

    bootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          public ChannelPipeline getPipeline() {
            return Channels.pipeline(new TimeDecoder(), new TimeClientHandler());
          }
        });

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
      future.getCause().printStackTrace();
    }
    future.getChannel().getCloseFuture().awaitUninterruptibly();
    factory.releaseExternalResources();
  }
Ejemplo n.º 3
0
  /** Connects to the IMAP server logs in with the given credentials. */
  @Override
  public synchronized boolean connect(final DisconnectListener listener) {
    reset();

    ChannelFuture future =
        bootstrap.connect(new InetSocketAddress(config.getHost(), config.getPort()));

    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
      throw new RuntimeException("Could not connect channel", future.getCause());
    }

    this.channel = channel;
    this.disconnectListener = listener;
    if (null != listener) {
      // https://issues.jboss.org/browse/NETTY-47?page=com.atlassian.jirafisheyeplugin%3Afisheye-issuepanel#issue-tabs
      channel
          .getCloseFuture()
          .addListener(
              new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                  mailClientHandler.idleAcknowledged.set(false);
                  mailClientHandler.disconnected();
                  listener.disconnected();
                }
              });
    }
    return login();
  }
  private ChannelFuture sendFile(ChannelHandlerContext ctx, Channel ch, FileChunk file)
      throws IOException {
    RandomAccessFile raf;
    try {
      raf = new RandomAccessFile(file.getFile(), "r");
    } catch (FileNotFoundException fnfe) {
      return null;
    }

    ChannelFuture writeFuture;
    if (ch.getPipeline().get(SslHandler.class) != null) {
      // Cannot use zero-copy with HTTPS.
      writeFuture = ch.write(new ChunkedFile(raf, file.startOffset(), file.length(), 8192));
    } else {
      // No encryption - use zero-copy.
      final FileRegion region =
          new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length());
      writeFuture = ch.write(region);
      writeFuture.addListener(
          new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
              region.releaseExternalResources();
            }
          });
    }

    return writeFuture;
  }
Ejemplo n.º 5
0
  @Test
  public void shouldPropagateDownstreamFlushOnPipelineFutureSuccess() throws Exception {

    context.checking(
        new Expectations() {
          {
            oneOf(upstream)
                .handleUpstream(
                    with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class)));
            oneOf(upstream)
                .handleUpstream(
                    with(any(ChannelHandlerContext.class)), with(channelState(OPEN, TRUE)));
            oneOf(downstream)
                .handleDownstream(
                    with(any(ChannelHandlerContext.class)), with(any(FlushEvent.class)));
          }
        });

    channelFactory.newChannel(pipeline);
    ChannelFuture executionFuture = execution.getHandlerFuture();
    executionFuture.setSuccess();

    ChannelFuture handlerFuture = handler.getHandlerFuture();
    handlerFuture.sync();

    context.assertIsSatisfied();
  }
Ejemplo n.º 6
0
  static void close(NioSocketChannel channel, ChannelFuture future) {
    NioWorker worker = channel.worker;

    boolean connected = channel.isConnected();
    boolean bound = channel.isBound();
    try {
      channel.socket.close();
      worker.cancelledKeys++;

      if (channel.setClosed()) {
        future.setSuccess();
        if (connected) {
          fireChannelDisconnected(channel);
        }
        if (bound) {
          fireChannelUnbound(channel);
        }

        cleanUpWriteBuffer(channel);
        fireChannelClosed(channel);
      } else {
        future.setSuccess();
      }
    } catch (Throwable t) {
      future.setFailure(t);
      fireExceptionCaught(channel, t);
    }
  }
Ejemplo n.º 7
0
  public static void serve404(
      NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) {
    Logger.trace("serve404: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    nettyResponse.setHeader(SERVER, signature);

    nettyResponse.setHeader(CONTENT_TYPE, "text/html");
    Map<String, Object> binding = getBindingForErrors(e, false);

    String format = Request.current().format;
    if (format == null) {
      format = "txt";
    }
    nettyResponse.setHeader(
        CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain")));

    String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
    try {
      ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
      nettyResponse.setContent(buf);
      ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
      writeFuture.addListener(ChannelFutureListener.CLOSE);
    } catch (UnsupportedEncodingException fex) {
      Logger.error(fex, "(utf-8 ?)");
    }
    Logger.trace("serve404: end");
  }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

    // Cast to a String first.
    // We know it is a String because we put some codec in TelnetPipelineFactory.
    String request = (String) e.getMessage();

    // Generate and write a response.
    String response;
    boolean close = false;
    if (request.length() == 0) {
      response = "Please type something.\r\n";
    } else if (request.toLowerCase().equals("bye")) {
      response = "Have a good day!\r\n";
      close = true;
    } else {
      response = "Did you say '" + request + "'?\r\n";
    }

    // We do not need to write a ChannelBuffer here.
    // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
    ChannelFuture future = e.getChannel().write(response);

    // Close the connection after sending 'Have a good day!'
    // if the client has sent 'bye'.
    if (close) {
      future.addListener(ChannelFutureListener.CLOSE);
    }
  }
Ejemplo n.º 9
0
  protected static void writeResponse(
      ChannelHandlerContext ctx,
      Response response,
      HttpResponse nettyResponse,
      HttpRequest nettyRequest) {
    Logger.trace("writeResponse: begin");
    byte[] content = null;

    final boolean keepAlive = isKeepAlive(nettyRequest);
    if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
      content = new byte[0];
    } else {
      content = response.out.toByteArray();
    }

    ChannelBuffer buf = ChannelBuffers.copiedBuffer(content);
    nettyResponse.setContent(buf);

    if (keepAlive) {
      // Add 'Content-Length' header only for a keep-alive connection.
      Logger.trace("writeResponse: content length [" + response.out.size() + "]");
      setContentLength(nettyResponse, response.out.size());
    }

    ChannelFuture f = ctx.getChannel().write(nettyResponse);

    // Decide whether to close the connection or not.
    if (!keepAlive) {
      // Close the connection when the whole content is written out.
      f.addListener(ChannelFutureListener.CLOSE);
    }
    Logger.trace("writeResponse: end");
  }
Ejemplo n.º 10
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;
  }
Ejemplo n.º 11
0
  @Override
  public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable(false);

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));

    outboundChannel = f.getChannel();
    f.addListener(
        new ChannelFutureListener() {
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              // Connection attempt succeeded:
              // Begin to accept incoming traffic.
              inboundChannel.setReadable(true);
            } else {
              // Close the connection if the connection attempt has failed.
              inboundChannel.close();
            }
          }
        });
  }
Ejemplo n.º 12
0
  static void write(
      OioDatagramChannel channel,
      ChannelFuture future,
      Object message,
      SocketAddress remoteAddress) {
    try {
      ChannelBuffer buf = (ChannelBuffer) message;
      int length = buf.readableBytes();
      ByteBuffer nioBuf = buf.toByteBuffer();
      DatagramPacket packet;
      if (nioBuf.hasArray()) {
        // Avoid copy if the buffer is backed by an array.
        packet = new DatagramPacket(nioBuf.array(), nioBuf.arrayOffset(), length);
      } else {
        // Otherwise it will be expensive.
        byte[] arrayBuf = new byte[length];
        buf.getBytes(0, arrayBuf);
        packet = new DatagramPacket(arrayBuf, length);
      }

      if (remoteAddress != null) {
        packet.setSocketAddress(remoteAddress);
      }
      channel.socket.send(packet);
      fireWriteComplete(channel, length);
      future.setSuccess();
    } catch (Throwable t) {
      future.setFailure(t);
      fireExceptionCaught(channel, t);
    }
  }
Ejemplo n.º 13
0
  /**
   * Will bind the DatagramSocket to the passed-in address. Every call bind will spawn a new thread
   * using the that basically in turn
   */
  private void bind(
      final NioDatagramChannel channel,
      final ChannelFuture future,
      final InetSocketAddress address) {
    boolean bound = false;
    boolean started = false;
    try {
      // First bind the DatagramSocket the specified port.
      channel.getDatagramChannel().socket().bind(address);
      bound = true;

      future.setSuccess();
      fireChannelBound(channel, address);

      channel.worker.register(channel, null);
      started = true;
    } catch (final Throwable t) {
      future.setFailure(t);
      fireExceptionCaught(channel, t);
    } finally {
      if (!started && bound) {
        close(channel, future);
      }
    }
  }
Ejemplo n.º 14
0
  public void run() {
    // Configure the client.
    ClientBootstrap bootstrap =
        new ClientBootstrap(
            new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new FactorialClientPipelineFactory(count));

    // Make a new connection.
    ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port));

    // Wait until the connection is made successfully.
    Channel channel = connectFuture.awaitUninterruptibly().getChannel();

    // Get the handler instance to retrieve the answer.
    FactorialClientHandler handler = (FactorialClientHandler) channel.getPipeline().getLast();

    // Print out the answer.
    System.err.format("Factorial of %,d is: %,d", count, handler.getFactorial());

    // Shut down all thread pools to exit.
    bootstrap.releaseExternalResources();
  }
Ejemplo n.º 15
0
  public void sendResponse(final MessageEvent e) {
    // Build the response object.
    final HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    final ByteArrayOutputStream bos = receivedData;
    try {
      bos.write(" successfully received by server".getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException e1) {
      e1.printStackTrace();
    } catch (final IOException e1) {
      e1.printStackTrace();
    }
    final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(bos.toByteArray());
    response.setContent(buffer);
    // response.setContent(arg0)
    // response.setContent(ChannelBuffers.copiedBuffer(buf.toString(),
    // CharsetUtil.UTF_8));
    response.setHeader(CONTENT_TYPE, "application/octet-stream");

    final ChannelFuture future = e.getChannel().write(response);

    // Close the non-keep-alive connection after the write operation is
    // done.
    // if (!keepAlive) {
    future.addListener(ChannelFutureListener.CLOSE);
    // }
  }
Ejemplo n.º 16
0
 private static boolean waitComplete(ChannelFuture writeFuture, String failedMessage) {
   if (!writeFuture.awaitUninterruptibly(500) || !writeFuture.isSuccess()) {
     LOG.info("port check: " + failedMessage + ", " + writeFuture.isSuccess());
     return false;
   }
   return true;
 }
Ejemplo n.º 17
0
  public void sendRequest(MetaInfo meta) {
    System.out.println(Thread.currentThread().getId() + " start sendRequest");
    URI uri = null;
    try {
      System.out.println(meta.getParams());
      uri = new URI(meta.getUrl());
    } catch (URISyntaxException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
    String host = uri.getHost();
    int port = 80;

    HttpRequest request =
        new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.valueOf(meta.getMethod()), uri.toASCIIString());
    meta.buildHttpRequestHeader(request);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    Channel channel = future.getChannel();
    channel.getPipeline().addLast("handler", new DownloaderHandler());
    GlobalVar.metaInfoVar.set(channel, meta);

    future.addListener(new ConnectOk(request));
    channel.getCloseFuture().awaitUninterruptibly().addListener(new ConnectClose());
    System.out.println(Thread.currentThread().getId() + " end sendRequest");
  }
Ejemplo n.º 18
0
  protected ChannelFuture sendFile(File file) {
    final RandomAccessFile raf;
    try {
      raf = new RandomAccessFile(file, "r");
      long fileLength = file.length();

      // Write the content.
      ChannelFuture writeFuture;
      if (isSSL()) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
      } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = channel.write(region);
      }
      writeFuture.addListener(
          new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
              raf.close();
            }
          });
      return writeFuture;
    } catch (IOException e) {
      handleException(e);
      return null;
    }
  }
Ejemplo n.º 19
0
  /**
   * Writes the given body to Netty channel. Will <b>not</b >wait until the body has been written.
   *
   * @param log logger to use
   * @param channel the Netty channel
   * @param remoteAddress the remote address when using UDP
   * @param body the body to write (send)
   * @param exchange the exchange
   * @param listener listener with work to be executed when the operation is complete
   */
  public static void writeBodyAsync(
      Logger log,
      Channel channel,
      SocketAddress remoteAddress,
      Object body,
      Exchange exchange,
      ChannelFutureListener listener) {
    ChannelFuture future;
    if (remoteAddress != null) {
      if (log.isDebugEnabled()) {
        log.debug(
            "Channel: {} remote address: {} writing body: {}",
            new Object[] {channel, remoteAddress, body});
      }
      future = channel.write(body, remoteAddress);
    } else {
      if (log.isDebugEnabled()) {
        log.debug("Channel: {} writing body: {}", new Object[] {channel, body});
      }
      future = channel.write(body);
    }

    if (listener != null) {
      future.addListener(listener);
    }
  }
Ejemplo n.º 20
0
  /**
   * Forcefully shuts down the connection to this tablet server and fails all the outstanding RPCs.
   * Only use when shutting down a client.
   *
   * @return deferred object to use to track the shutting down of this connection
   */
  public Deferred<Void> shutdown() {
    // First, check whether we have RPCs in flight and cancel them.
    for (Iterator<KuduRpc<?>> ite = rpcs_inflight.values().iterator(); ite.hasNext(); ) {
      KuduRpc<?> rpc = ite.next();
      rpc.errback(new ConnectionResetException(null));
      ite.remove();
    }

    // Same for the pending RPCs.
    synchronized (this) {
      if (pending_rpcs != null) {
        for (Iterator<KuduRpc<?>> ite = pending_rpcs.iterator(); ite.hasNext(); ) {
          ite.next().errback(new ConnectionResetException(null));
          ite.remove();
        }
      }
    }

    final Channel chancopy = chan;
    if (chancopy == null) {
      return Deferred.fromResult(null);
    }
    if (chancopy.isConnected()) {
      Channels.disconnect(chancopy); // ... this is going to set it to null.
      // At this point, all in-flight RPCs are going to be failed.
    }
    if (chancopy.isBound()) {
      Channels.unbind(chancopy);
    }
    // It's OK to call close() on a Channel if it's already closed.
    final ChannelFuture future = Channels.close(chancopy);
    // Now wrap the ChannelFuture in a Deferred.
    final Deferred<Void> d = new Deferred<Void>();
    // Opportunistically check if it's already completed successfully.
    if (future.isSuccess()) {
      d.callback(null);
    } else {
      // If we get here, either the future failed (yeah, that sounds weird)
      // or the future hasn't completed yet (heh).
      future.addListener(
          new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture future) {
              if (future.isSuccess()) {
                d.callback(null);
                return;
              }
              final Throwable t = future.getCause();
              if (t instanceof Exception) {
                d.callback(t);
              } else {
                // Wrap the Throwable because Deferred doesn't handle Throwables,
                // it only uses Exception.
                d.callback(
                    new NonRecoverableException("Failed to shutdown: " + TabletClient.this, t));
              }
            }
          });
    }
    return d;
  }
Ejemplo n.º 21
0
  private void bind(OioDatagramChannel channel, ChannelFuture future, SocketAddress localAddress) {
    boolean bound = false;
    boolean workerStarted = false;
    try {
      channel.socket.bind(localAddress);
      bound = true;

      // Fire events
      future.setSuccess();
      fireChannelBound(channel, channel.getLocalAddress());

      // Start the business.
      workerExecutor.execute(
          new IoWorkerRunnable(
              new ThreadRenamingRunnable(
                  new OioDatagramWorker(channel),
                  "Old I/O datagram worker (channelId: "
                      + channel.getId()
                      + ", "
                      + channel.getLocalAddress()
                      + ')')));
      workerStarted = true;
    } catch (Throwable t) {
      future.setFailure(t);
      fireExceptionCaught(channel, t);
    } finally {
      if (bound && !workerStarted) {
        OioDatagramWorker.close(channel, future);
      }
    }
  }
Ejemplo n.º 22
0
 static void close(OioDatagramChannel channel, ChannelFuture future) {
   boolean connected = channel.isConnected();
   boolean bound = channel.isBound();
   try {
     channel.socket.close();
     if (channel.setClosed()) {
       future.setSuccess();
       if (connected) {
         // Notify the worker so it stops reading.
         Thread currentThread = Thread.currentThread();
         Thread workerThread = channel.workerThread;
         if (workerThread != null && currentThread != workerThread) {
           workerThread.interrupt();
         }
         fireChannelDisconnected(channel);
       }
       if (bound) {
         fireChannelUnbound(channel);
       }
       fireChannelClosed(channel);
     } else {
       future.setSuccess();
     }
   } catch (Throwable t) {
     future.setFailure(t);
     fireExceptionCaught(channel, t);
   }
 }
Ejemplo n.º 23
0
  public void handleGameRoomJoin(Player player, Channel channel, ChannelBuffer buffer) {
    String refKey = NettyUtils.readString(buffer);

    GameRoom gameRoom = lookupService.gameRoomLookup(refKey);
    if (null != gameRoom) {
      PlayerSession playerSession = gameRoom.createPlayerSession();
      playerSession.setConnectParameter(
          NettyUtils.NETTY_CHANNEL, channel); // TODO is this required?
      gameRoom.onLogin(playerSession);
      LOG.trace("Sending GAME_ROOM_JOIN_SUCCESS to channel {}", channel.getId());
      ChannelFuture future =
          channel.write(NettyUtils.createBufferForOpcode(Events.GAME_ROOM_JOIN_SUCCESS));
      connectToGameRoom(gameRoom, playerSession, future);
      loginUdp(playerSession, buffer);
    } else {
      // Write failure and close channel.
      ChannelFuture future =
          channel.write(NettyUtils.createBufferForOpcode(Events.GAME_ROOM_JOIN_FAILURE));
      future.addListener(ChannelFutureListener.CLOSE);
      LOG.error(
          "Invalid ref key provided by client: {}. Channel {} will be closed",
          refKey,
          channel.getId());
    }
  }
Ejemplo n.º 24
0
  public void stop() {
    log.info("Shutting down proxy");
    if (stopped.get()) {
      log.info("Already stopped");
      return;
    }
    stopped.set(true);

    log.info("Closing all channels...");

    // See http://static.netty.io/3.5/guide/#start.12

    final ChannelGroupFuture future = allChannels.close();
    future.awaitUninterruptibly(10 * 1000);

    if (!future.isCompleteSuccess()) {
      final Iterator<ChannelFuture> iter = future.iterator();
      while (iter.hasNext()) {
        final ChannelFuture cf = iter.next();
        if (!cf.isSuccess()) {
          log.warn("Cause of failure for {} is {}", cf.getChannel(), cf.getCause());
        }
      }
    }
    log.info("Stopping timer");
    timer.stop();
    serverChannelFactory.releaseExternalResources();
    clientChannelFactory.releaseExternalResources();

    log.info("Done shutting down proxy");
  }
Ejemplo n.º 25
0
  private void connect(
      OioDatagramChannel channel, ChannelFuture future, SocketAddress remoteAddress) {

    boolean bound = channel.isBound();
    boolean connected = false;
    boolean workerStarted = false;

    future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

    // Clear the cached address so that the next getRemoteAddress() call
    // updates the cache.
    channel.remoteAddress = null;

    try {
      channel.socket.connect(remoteAddress);
      connected = true;

      // Fire events.
      future.setSuccess();
      if (!bound) {
        fireChannelBound(channel, channel.getLocalAddress());
      }
      fireChannelConnected(channel, channel.getRemoteAddress());

      String threadName =
          "Old I/O datagram worker (channelId: "
              + channel.getId()
              + ", "
              + channel.getLocalAddress()
              + " => "
              + channel.getRemoteAddress()
              + ')';
      if (!bound) {
        // Start the business.
        workerExecutor.execute(
            new IoWorkerRunnable(
                new ThreadRenamingRunnable(new OioDatagramWorker(channel), threadName)));
      } else {
        // Worker started by bind() - just rename.
        Thread workerThread = channel.workerThread;
        if (workerThread != null) {
          try {
            workerThread.setName(threadName);
          } catch (SecurityException e) {
            // Ignore.
          }
        }
      }

      workerStarted = true;
    } catch (Throwable t) {
      future.setFailure(t);
      fireExceptionCaught(channel, t);
    } finally {
      if (connected && !workerStarted) {
        OioDatagramWorker.close(channel, future);
      }
    }
  }
Ejemplo n.º 26
0
  private void stopConfiguration() throws Exception {

    if (configuration == null) {
      // abort received but script not prepared, therefore entire script failed
      if (progress == null) {
        progress = new ScriptProgress(newSequential(0, 0), "");
      }
      RegionInfo scriptInfo = progress.getScriptInfo();
      progress.addScriptFailure(scriptInfo);
    } else {
      // stopping the configuration will implicitly trigger the script complete listener
      // to handle incomplete script that is being aborted by canceling the finish future

      // clear out the pipelines for new connections to avoid impacting the observed script
      for (ServerBootstrapResolver serverResolver : configuration.getServerResolvers()) {
        ServerBootstrap server = serverResolver.resolve();
        server.setPipelineFactory(pipelineFactory(pipeline(closeOnExceptionHandler)));
      }
      for (ClientBootstrapResolver clientResolver : configuration.getClientResolvers()) {
        ClientBootstrap client = clientResolver.resolve();
        client.setPipelineFactory(pipelineFactory(pipeline(closeOnExceptionHandler)));
      }

      // remove each handler from the configuration pipelines
      // this will trigger failures for any handlers on a pipeline for an incomplete stream
      // including pipelines not yet associated with any channel
      for (ChannelPipeline pipeline : configuration.getClientAndServerPipelines()) {
        stopStream(pipeline);
      }

      // cancel any pending binds and connects
      for (ChannelFuture bindFuture : bindFutures) {
        bindFuture.cancel();
      }

      for (ChannelFuture connectFuture : connectFutures) {
        connectFuture.cancel();
      }

      // close server and client channels
      final ChannelGroupFuture closeFuture = serverChannels.close();
      closeFuture.addListener(
          new ChannelGroupFutureListener() {
            @Override
            public void operationComplete(final ChannelGroupFuture future) {
              clientChannels.close();
            }
          });

      for (AutoCloseable resource : configuration.getResources()) {
        try {
          resource.close();
        } catch (Exception e) {
          // ignore
        }
      }
    }
  }
Ejemplo n.º 27
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);
  }
 private void flushResponse() {
   // Send the response and close the connection.
   try {
     ChannelFuture future = write(responseBuffer);
     future.addListener(ChannelFutureListener.CLOSE);
   } catch (Exception e) {
     ioExceptionHandler.uncaughtException(Thread.currentThread(), e);
   }
 }
Ejemplo n.º 29
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);
   }
 }
Ejemplo n.º 30
0
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Get the SslHandler in the current pipeline.
    // We added it in SecureChatPipelineFactory.
    final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);

    // Get notified when SSL handshake is done.
    ChannelFuture handshakeFuture = sslHandler.handshake();
    handshakeFuture.addListener(new SslLister(sslHandler));
  }