Exemplo n.º 1
0
 /** Stop the Server */
 public void stop() {
   try {
     handler.destroy();
     final ChannelGroupFuture future = ALL_CHANNELS.close();
     future.awaitUninterruptibly();
     bootstrap.getFactory().releaseExternalResources();
     ALL_CHANNELS.clear();
   } finally {
     started.set(false);
   }
 }
Exemplo n.º 2
0
 public static void closeChannels(ChannelGroup allChannels) {
   if (allChannels.size() > 0) {
     // TODO : allow an option here to control if we need to drain connections and wait instead of
     // killing them all
     try {
       log.info("Closing %s open client connections", allChannels.size());
       if (!allChannels.close().await(5, TimeUnit.SECONDS)) {
         log.warn("Failed to close all open client connections");
       }
     } catch (InterruptedException e) {
       log.warn("Interrupted while closing client connections");
       Thread.currentThread().interrupt();
     }
   }
 }
Exemplo n.º 3
0
 /** close all channels, and release resources */
 public synchronized void close() {
   if (allChannels != null) {
     allChannels.close().awaitUninterruptibly();
     factory.releaseExternalResources();
     allChannels = null;
   }
 }
Exemplo n.º 4
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");
  }
Exemplo n.º 5
0
  private void actualClose(final Context closeContext, final Handler<Void> done) {
    if (id != null) {
      vertx.sharedNetServers().remove(id);
    }

    for (DefaultNetSocket sock : socketMap.values()) {
      sock.internalClose();
    }

    // We need to reset it since sock.internalClose() above can call into the close handlers of
    // sockets on the same thread
    // which can cause context id for the thread to change!

    Context.setContext(closeContext);

    ChannelGroupFuture fut = serverChannelGroup.close();
    if (done != null) {
      fut.addListener(
          new ChannelGroupFutureListener() {
            public void operationComplete(ChannelGroupFuture channelGroupFuture) throws Exception {
              executeCloseDone(closeContext, done);
            }
          });
    }
  }
Exemplo n.º 6
0
  /** Shuts the AirReceiver down gracefully */
  public static void onShutdown() {
    /* Close channels */
    final ChannelGroupFuture allChannelsClosed = s_allChannels.close();

    /* Stop all mDNS responders */
    synchronized (s_jmDNSInstances) {
      for (final JmDNS jmDNS : s_jmDNSInstances) {
        try {
          jmDNS.unregisterAllServices();
          s_logger.info("Unregistered all services on " + jmDNS.getInterface());
        } catch (final IOException e) {
          s_logger.info("Failed to unregister some services");
        }
      }
    }

    /* Wait for all channels to finish closing */
    allChannelsClosed.awaitUninterruptibly();

    /* Stop the ExecutorService */
    ExecutorService.shutdown();

    /* Release the OrderedMemoryAwareThreadPoolExecutor */
    ChannelExecutionHandler.releaseExternalResources();
  }
Exemplo n.º 7
0
  /** Stops this server. */
  public void shutdown() {
    // This is so we don't run this twice (/stop and actual shutdown)
    if (isShuttingDown) return;
    isShuttingDown = true;
    logger.info("The server is shutting down...");

    monitor.interrupt();

    // Stop scheduler and disable plugins
    scheduler.stop();
    pluginManager.clearPlugins();

    // Kick (and save) all players
    for (Player player : getOnlinePlayers()) {
      player.kickPlayer("Server shutting down.");
    }

    // Save worlds
    for (World world : getWorlds()) {
      unloadWorld(world, true);
    }
    storeQueue.end();

    // Gracefully stop Netty
    group.close();
    bootstrap.getFactory().releaseExternalResources();

    // And finally kill the console
    consoleManager.stop();
  }
  /** Start listening sockets */
  @LogMessageDoc(
      level = "INFO",
      message = "Listening for internal floodlight RPC on {port}",
      explanation = "The internal RPC service is ready for connections")
  protected void startServer(ChannelPipelineFactory pipelineFactory) {
    final ServerBootstrap bootstrap =
        new ServerBootstrap(new NioServerSocketChannelFactory(bossExecutor, workerExecutor));
    bootstrap.setOption("reuseAddr", true);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.sendBufferSize", SEND_BUFFER_SIZE);
    bootstrap.setOption("child.receiveBufferSize", SEND_BUFFER_SIZE);

    bootstrap.setPipelineFactory(pipelineFactory);
    serverBootstrap = bootstrap;

    int port = syncManager.getClusterConfig().getNode().getPort();
    InetSocketAddress sa;
    String listenAddress = syncManager.getClusterConfig().getListenAddress();
    if (listenAddress != null) sa = new InetSocketAddress(listenAddress, port);
    else sa = new InetSocketAddress(port);

    cg.add(bootstrap.bind(sa));

    logger.info("Listening for internal floodlight RPC on {}", sa);
  }
 /** Stop the RPC service */
 @LogMessageDocs({
   @LogMessageDoc(
       level = "WARN",
       message = "Failed to cleanly shut down RPC server",
       explanation = "Could not close all open sockets cleanly"),
   @LogMessageDoc(
       level = "WARN",
       message = "Interrupted while shutting down RPC server",
       explanation = "Could not close all open sockets cleanly")
 })
 public void shutdown() {
   shutDown = true;
   try {
     if (!cg.close().await(5, TimeUnit.SECONDS)) {
       logger.warn("Failed to cleanly shut down RPC server");
       return;
     }
     if (clientBootstrap != null) clientBootstrap.releaseExternalResources();
     clientBootstrap = null;
     if (serverBootstrap != null) serverBootstrap.releaseExternalResources();
     serverBootstrap = null;
     if (pipelineFactory != null) pipelineFactory.releaseExternalResources();
     pipelineFactory = null;
     if (bossExecutor != null) bossExecutor.shutdown();
     bossExecutor = null;
     if (workerExecutor != null) workerExecutor.shutdown();
     workerExecutor = null;
   } catch (InterruptedException e) {
     logger.warn("Interrupted while shutting down RPC server");
   }
   logger.debug("Internal floodlight RPC shut down");
 }
Exemplo n.º 10
0
 /** Stop the network manager, closing all connections and cleaning up all resources. */
 public void stop() {
   started.set(false);
   logger.info("Network manager stopping!");
   ChannelGroupFuture future = allChannels.close();
   future.awaitUninterruptibly();
   channelFactory.releaseExternalResources();
 }
Exemplo n.º 11
0
 public void stop() {
   log.info("Shutting down proxy");
   final ChannelGroupFuture future = allChannels.close();
   future.awaitUninterruptibly(6 * 1000);
   serverBootstrap.releaseExternalResources();
   log.info("Done shutting down proxy");
 }
 @Override
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   // as seen in http://www.jboss.org/netty/community.html#nabble-td2423020
   super.channelOpen(ctx, e);
   if (group != null) {
     group.add(ctx.getChannel());
   }
 }
Exemplo n.º 13
0
 /** Start the server */
 public void start() {
   final Channel serverChannel = bootstrap.bind(localSocket);
   ALL_CHANNELS.add(serverChannel);
   started.set(true);
   if (bootstrapFlashPolicy != null) {
     bootstrapFlashPolicy.bind(localPolicySocket);
   }
 }
Exemplo n.º 14
0
 @Override
 public void dispose() {
   try {
     openChannels.close().awaitUninterruptibly();
   } finally {
     channelFactory.releaseExternalResources();
   }
   LOG.info("web server stopped");
 }
Exemplo n.º 15
0
  public void start(final boolean localOnly, final boolean anyAddress) {
    log.info("Starting proxy on port: " + this.port);
    this.stopped.set(false);
    final HttpServerPipelineFactory factory =
        new HttpServerPipelineFactory(
            authenticationManager,
            this.allChannels,
            this.chainProxyManager,
            this.ksm,
            new DefaultRelayPipelineFactoryFactory(
                chainProxyManager,
                this.responseFilters,
                this.requestFilter,
                this.allChannels,
                timer),
            timer,
            this.clientChannelFactory,
            this.cacheManager);
    serverBootstrap.setPipelineFactory(factory);

    // Binding only to localhost can significantly improve the security of
    // the proxy.
    InetSocketAddress isa;
    if (localOnly) {
      isa = new InetSocketAddress("127.0.0.1", port);
    } else if (anyAddress) {
      isa = new InetSocketAddress(port);
    } else {
      try {
        isa = new InetSocketAddress(NetworkUtils.getLocalHost(), port);
      } catch (final UnknownHostException e) {
        log.error("Could not get local host?", e);
        isa = new InetSocketAddress(port);
      }
    }
    final Channel channel = serverBootstrap.bind(isa);
    allChannels.add(channel);

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread(
                new Runnable() {
                  public void run() {
                    stop();
                  }
                }));

    /*
    final ServerBootstrap sslBootstrap = new ServerBootstrap(
        new NioServerSocketChannelFactory(
            newServerThreadPool(),
            newServerThreadPool()));
    sslBootstrap.setPipelineFactory(new HttpsServerPipelineFactory());
    sslBootstrap.bind(new InetSocketAddress("127.0.0.1", 8443));
    */
  }
Exemplo n.º 16
0
 /**
  * Shutdown this client and close all open connections. The client should be discarded after
  * calling shutdown.
  */
 public void shutdown() {
   for (Channel c : channels) {
     ChannelPipeline pipeline = c.getPipeline();
     RedisAsyncConnection<?, ?> connection = pipeline.get(RedisAsyncConnection.class);
     connection.close();
   }
   ChannelGroupFuture future = channels.close();
   future.awaitUninterruptibly();
   bootstrap.releaseExternalResources();
 }
Exemplo n.º 17
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());
  }
Exemplo n.º 18
0
 @Override
 public void sendLoadMetrics(Map<Integer, Double> taskToLoad) {
   try {
     MessageBatch mb = new MessageBatch(1);
     mb.add(new TaskMessage(-1, _ser.serialize(Arrays.asList((Object) taskToLoad))));
     allChannels.write(mb);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Exemplo n.º 19
0
 public void stop() {
   try {
     myScheduler.shutdown();
     myBuildsExecutor.shutdown();
     final ChannelGroupFuture closeFuture = myAllOpenChannels.close();
     closeFuture.awaitUninterruptibly();
   } finally {
     myChannelFactory.releaseExternalResources();
   }
 }
Exemplo n.º 20
0
  public void start(int listenPort) {
    final ServerBootstrap bootstrap = new ServerBootstrap(myChannelFactory);
    bootstrap.setPipelineFactory(myPipelineFactory);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.keepAlive", true);
    final Channel serverChannel = bootstrap.bind(new InetSocketAddress(listenPort));
    myAllOpenChannels.add(serverChannel);

    startActivityMonitor();
  }
Exemplo n.º 21
0
 public void close() throws IOException {
   ChannelGroupFuture f = group.close().awaitUninterruptibly();
   if (!f.isCompleteSuccess()) {
     for (ChannelFuture future : f) {
       if (!future.isSuccess()) {
         throw new IOException(future.getCause());
       }
     }
   }
   bootstrap.releaseExternalResources();
 }
Exemplo n.º 22
0
  /** Start the network manager. */
  public void start() throws Exception {
    if (!started.compareAndSet(false, true)) {
      throw new IllegalStateException("You already started the server!");
    }

    logger.info("Network manager starting!");

    bootstrap = serverBootstrapProvider.get();
    channelFactory = channelFactoryProvider.get();
    allChannels.add(bootstrap.bind(serverAddress));
  }
  // IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
  // but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports
  // and any request to us will be intercepted
  // so, we bind to 127.0.0.1 and 0.0.0.0
  private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
    InetAddress localAddress;
    try {
      localAddress = InetAddress.getByName("127.0.0.1");
    } catch (UnknownHostException e) {
      LOG.error(e);
      return -1;
    }

    for (int i = 0; i < portsCount; i++) {
      int port = firstPort + i;
      try {
        openChannels.add(bootstrap.bind(new InetSocketAddress(localAddress, port)));
        return port;
      } catch (ChannelException e) {
        if (!openChannels.isEmpty()) {
          openChannels.close();
          openChannels.clear();
        }

        if (portsCount == 1) {
          throw e;
        } else if (!tryAnyPort && i == (portsCount - 1)) {
          LOG.error(e);
        }
      }
    }

    if (tryAnyPort) {
      LOG.info("We cannot bind to our default range, so, try to bind to any free port");
      try {
        Channel channel = bootstrap.bind(new InetSocketAddress(localAddress, 0));
        openChannels.add(channel);
        return ((InetSocketAddress) channel.getLocalAddress()).getPort();
      } catch (ChannelException e) {
        LOG.error(e);
      }
    }

    return -1;
  }
Exemplo n.º 24
0
  @SuppressWarnings("rawtypes")
  Server(Map storm_conf, int port) {
    this.storm_conf = storm_conf;
    this.port = port;
    _ser = new KryoValuesSerializer(storm_conf);

    // Configure the server.
    int buffer_size = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE));
    int backlog = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_SOCKET_BACKLOG), 500);
    int maxWorkers =
        Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_SERVER_WORKER_THREADS));

    ThreadFactory bossFactory = new NettyRenameThreadFactory(netty_name() + "-boss");
    ThreadFactory workerFactory = new NettyRenameThreadFactory(netty_name() + "-worker");

    if (maxWorkers > 0) {
      factory =
          new NioServerSocketChannelFactory(
              Executors.newCachedThreadPool(bossFactory),
              Executors.newCachedThreadPool(workerFactory),
              maxWorkers);
    } else {
      factory =
          new NioServerSocketChannelFactory(
              Executors.newCachedThreadPool(bossFactory),
              Executors.newCachedThreadPool(workerFactory));
    }

    LOG.info(
        "Create Netty Server "
            + netty_name()
            + ", buffer_size: "
            + buffer_size
            + ", maxWorkers: "
            + maxWorkers);

    bootstrap = new ServerBootstrap(factory);
    bootstrap.setOption("child.tcpNoDelay", true);
    bootstrap.setOption("child.receiveBufferSize", buffer_size);
    bootstrap.setOption("child.keepAlive", true);
    bootstrap.setOption("backlog", backlog);

    // Set up the pipeline factory.
    bootstrap.setPipelineFactory(new StormServerPipelineFactory(this));

    // Bind and start to accept incoming connections.
    Channel channel = bootstrap.bind(new InetSocketAddress(port));
    allChannels.add(channel);
  }
Exemplo n.º 25
0
  /**
   * The last call in the building of a RestExpress server, bind() causes Netty to bind to the
   * listening address and process incoming messages.
   *
   * @return Channel
   */
  public Channel bind(int port) {
    setPort(port);

    // Configure the server.
    if (getIoThreadCount() == 0) {
      bootstrap = Bootstraps.createServerNioBootstrap();
    } else {
      bootstrap = Bootstraps.createServerNioBootstrap(getIoThreadCount());
    }

    // Set up the event pipeline factory.
    DefaultRequestHandler requestHandler =
        new DefaultRequestHandler(createRouteResolver(), createResponseProcessorResolver());

    // Add MessageObservers to the request handler here, if desired...
    requestHandler.addMessageObserver(messageObservers.toArray(new MessageObserver[0]));

    requestHandler.setExceptionMap(exceptionMap);

    // Add pre/post processors to the request handler here...
    addPreprocessors(requestHandler);
    addPostprocessors(requestHandler);
    addFinallyProcessors(requestHandler);

    PipelineBuilder pf =
        new PipelineBuilder()
            .addRequestHandler(requestHandler)
            .setMaxContentLength(serverSettings.getMaxContentSize());

    if (getExecutorThreadCount() > 0) {
      ExecutionHandler executionHandler =
          new ExecutionHandler(
              new OrderedMemoryAwareThreadPoolExecutor(getExecutorThreadCount(), 0, 0));
      pf.setExecutionHandler(executionHandler);
    }

    bootstrap.setPipelineFactory(pf);
    setBootstrapOptions();

    // Bind and start to accept incoming connections.
    if (shouldUseSystemOut()) {
      System.out.println("Starting " + getName() + " Server on port " + port);
    }

    Channel channel = bootstrap.bind(new InetSocketAddress(port));
    allChannels.add(channel);
    bindPlugins();
    return channel;
  }
  @Override
  public void start(final boolean localOnly, final boolean anyAddress) {
    final int port = getPort();
    log.debug("Starting proxy on port: " + port);
    final HttpServerPipelineFactory factory =
        new StatsTrackingHttpServerPipelineFactory(
            authenticationManager,
            this.allChannels,
            this.chainProxyManager,
            new StatsTrackingDefaultRelayPipelineFactoryFactory(
                chainProxyManager,
                this.responseFilters,
                this.requestFilter,
                this.allChannels,
                this.timer),
            this.clientChannelFactory,
            this.timer,
            this.handshakeHandlerFactory);
    serverBootstrap.setPipelineFactory(factory);

    // Binding only to localhost can significantly improve the security of
    // the proxy.
    InetSocketAddress isa;
    if (localOnly) {
      isa = new InetSocketAddress("127.0.0.1", port);
    } else if (anyAddress) {
      isa = new InetSocketAddress(port);
    } else {
      try {
        isa = new InetSocketAddress(NetworkUtils.getLocalHost(), port);
      } catch (final UnknownHostException e) {
        log.error("Could not get local host?", e);
        isa = new InetSocketAddress(port);
      }
    }
    final Channel channel = serverBootstrap.bind(isa);
    allChannels.add(channel);

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread(
                new Runnable() {
                  @Override
                  public void run() {
                    stop();
                  }
                }));
    log.debug("Started " + this);
  }
Exemplo n.º 27
0
  @Override
  public synchronized void stop() {
    try {
      accepted.close().awaitUninterruptibly(10, TimeUnit.SECONDS);
      ServerBootstrap bootstrap = new ServerBootstrap(selector);
      bootstrap.releaseExternalResources();
      pipelineFact.destroy();

      localFS.close();
    } catch (Throwable t) {
      LOG.error(t);
    } finally {
      super.stop();
    }
  }
Exemplo n.º 28
0
  @Override
  public void stop() throws Throwable {
    // Close all open connections
    shuttingDown = true;

    targetCallExecutor.shutdown();
    targetCallExecutor.awaitTermination(10, TimeUnit.SECONDS);
    unfinishedTransactionExecutor.shutdown();
    unfinishedTransactionExecutor.awaitTermination(10, TimeUnit.SECONDS);
    silentChannelExecutor.shutdown();
    silentChannelExecutor.awaitTermination(10, TimeUnit.SECONDS);

    channelGroup.close().awaitUninterruptibly();

    bootstrap.releaseExternalResources();
  }
Exemplo n.º 29
0
 public void stop() {
   try {
     for (ChannelFutureListener listener : closingListeners) {
       try {
         listener.operationComplete(null);
       } catch (Exception e) {
         LOG.error(e);
       }
     }
   } finally {
     try {
       openChannels.close().awaitUninterruptibly();
     } finally {
       channelFactory.releaseExternalResources();
     }
   }
 }
Exemplo n.º 30
0
  // TODO change AbstractService to throw InterruptedException
  @Override
  public synchronized void start() {
    Configuration conf = getConfig();
    ServerBootstrap bootstrap = new ServerBootstrap(selector);
    try {
      pipelineFact = new HttpPipelineFactory(conf);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
    bootstrap.setPipelineFactory(pipelineFact);
    port = conf.getInt(ConfVars.PULLSERVER_PORT.varname, ConfVars.PULLSERVER_PORT.defaultIntVal);
    Channel ch = bootstrap.bind(new InetSocketAddress(port));
    accepted.add(ch);
    port = ((InetSocketAddress) ch.getLocalAddress()).getPort();
    conf.set(ConfVars.PULLSERVER_PORT.varname, Integer.toString(port));
    pipelineFact.PullServer.setPort(port);
    LOG.info(getName() + " listening on port " + port);
    super.start();

    sslFileBufferSize =
        conf.getInt(SUFFLE_SSL_FILE_BUFFER_SIZE_KEY, DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE);
  }