org.elasticsearch.common.component.Lifecycle类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(9.9k)|赞(0)|评价(0)|浏览(87)

本文整理了Java中org.elasticsearch.common.component.Lifecycle类的一些代码示例,展示了Lifecycle类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Lifecycle类的具体详情如下:
包路径:org.elasticsearch.common.component.Lifecycle
类名称:Lifecycle

Lifecycle介绍

[英]Lifecycle state. Allows the following transitions:

  • INITIALIZED -> STARTED, STOPPED, CLOSED
  • STARTED -> STOPPED
  • STOPPED -> STARTED, CLOSED
  • CLOSED ->

Also allows to stay in the same state. For example, when calling stop on a component, the following logic can be applied:

public void stop() { 
if (!lifecycleState.moveToStopped()) { 
return; 
} 
// continue with stop logic 
}

Note, closed is only allowed to be called when stopped, so make sure to stop the component first. Here is how the logic can be applied:

public void close() { 
if (lifecycleState.started()) { 
stop(); 
} 
if (!lifecycleState.moveToClosed()) { 
return; 
} 
// perform close logic here 
}

[中]生命周期状态。允许以下转换:
*初始化->启动、停止、关闭
*开始->停止
*停止->启动,关闭
*关闭->
也允许保持在相同的状态。例如,在组件上调用stop时,可以应用以下逻辑:

public void stop() { 
if (!lifecycleState.moveToStopped()) { 
return; 
} 
// continue with stop logic 
}

注意,closed仅允许在停止时调用,因此请确保首先停止组件。以下是如何应用逻辑:

public void close() { 
if (lifecycleState.started()) { 
stop(); 
} 
if (!lifecycleState.moveToClosed()) { 
return; 
} 
// perform close logic here 
}

代码示例

代码示例来源:origin: org.elasticsearch/elasticsearch

@Override
public synchronized void close() throws IOException {
  if (lifecycle.started()) {
    stop();
  if (!lifecycle.moveToClosed()) {
    return;
  logger.info("closing ...");
  List<Closeable> toClose = new ArrayList<>();
  StopWatch stopWatch = new StopWatch("node_close");
  toClose.add(injector.getInstance(PageCacheRecycler.class));
  if (logger.isTraceEnabled()) {
    logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint());

代码示例来源:origin: org.elasticsearch/elasticsearch

/**
 * Returns {@code true} if the node is closed.
 */
public boolean isClosed() {
  return lifecycle.closed();
}

代码示例来源:origin: org.elasticsearch/elasticsearch

@SuppressWarnings({"unchecked"})
@Override
public void start() {
  if (!lifecycle.canMoveToStarted()) {
    return;
  }
  for (LifecycleListener listener : listeners) {
    listener.beforeStart();
  }
  doStart();
  lifecycle.moveToStarted();
  for (LifecycleListener listener : listeners) {
    listener.afterStart();
  }
}

代码示例来源:origin: org.elasticsearch/elasticsearch

@Override
public void close() {
  lifecycle.moveToStopped();
  lifecycle.moveToClosed();
}

代码示例来源:origin: org.elasticsearch/elasticsearch

@SuppressWarnings({"unchecked"})
@Override
public void stop() {
  if (!lifecycle.canMoveToStopped()) {
    return;
  }
  for (LifecycleListener listener : listeners) {
    listener.beforeStop();
  }
  lifecycle.moveToStopped();
  doStop();
  for (LifecycleListener listener : listeners) {
    listener.afterStop();
  }
}

代码示例来源:origin: org.elasticsearch/elasticsearch

protected void runTask(UpdateTask task) {
  if (!lifecycle.started()) {
    logger.debug("processing [{}]: ignoring, cluster applier service not started", task.source);
    return;
  logger.debug("processing [{}]: execute", task.source);
  final ClusterState previousClusterState = state.get();
  } catch (Exception e) {
    TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(currentTimeInNanos() - startTimeNS)));
    if (logger.isTraceEnabled()) {
      logger.trace(() -> new ParameterizedMessage(
          "failed to execute cluster state applier in [{}], state:\nversion [{}], source [{}]\n{}{}{}",

代码示例来源:origin: org.elasticsearch/elasticsearch

protected void runTasks(TaskInputs taskInputs) {
  final String summary = taskInputs.summary;
  if (!lifecycle.started()) {
    logger.debug("processing [{}]: ignoring, master service not started", summary);
    return;
  logger.debug("processing [{}]: execute", summary);
  final ClusterState previousClusterState = state();
    logger.debug("failing [{}]: local node is no longer master", summary);
    taskInputs.onNoLongerMaster();
    return;

代码示例来源:origin: floragunncom/search-guard-ssl

@Override
protected final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  if(this.lifecycle.started()) {
    
    if(cause instanceof DecoderException && cause != null) {
      cause = cause.getCause();
    }
    
    errorHandler.logError(cause, true);
    
    if(cause instanceof NotSslRecordException) {
      logger.warn("Someone ({}) speaks http plaintext instead of ssl, will close the channel", ctx.channel().remoteAddress());
      ctx.channel().close();
      return;
    } else if (cause instanceof SSLException) {
      logger.error("SSL Problem "+cause.getMessage(),cause);
      ctx.channel().close();
      return;
    } else if (cause instanceof SSLHandshakeException) {
      logger.error("Problem during handshake "+cause.getMessage());
      ctx.channel().close();
      return;
    }
    
  }
  
  super.exceptionCaught(ctx, cause);
}

代码示例来源:origin: org.elasticsearch/elasticsearch

if (!lifecycle.moveToStarted()) {
  return this;
logger.info("starting ...");
pluginLifecycleComponents.forEach(LifecycleComponent::start);
  ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext());
  if (clusterState.nodes().getMasterNodeId() == null) {
    logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout);
    final CountDownLatch latch = new CountDownLatch(1);
    observer.waitForNextChange(new ClusterStateObserver.Listener() {
logger.info("started");

代码示例来源:origin: org.elasticsearch/elasticsearch

protected void performReroute(String reason) {
  try {
    if (lifecycle.stopped()) {
      return;
      logger.trace("already has pending reroute, ignoring {}", reason);
      return;
    logger.trace("rerouting {}", reason);
    clusterService.submitStateUpdateTask(CLUSTER_UPDATE_TASK_SOURCE + "(" + reason + ")",
      new ClusterStateUpdateTask(Priority.HIGH) {
    rerouting.set(false);
    ClusterState state = clusterService.state();
    logger.warn(() -> new ParameterizedMessage("failed to reroute routing table, current state:\n{}", state), e);

代码示例来源:origin: org.elasticsearch/elasticsearch

private Node stop() {
  if (!lifecycle.moveToStopped()) {
    return this;
  logger.info("stopping ...");
  logger.info("stopped");

代码示例来源:origin: org.elasticsearch/elasticsearch

public void onException(TcpChannel channel, Exception e) {
  if (!lifecycle.started()) {
    logger.trace(() -> new ParameterizedMessage(
      "close connection exception caught on transport layer [{}], disconnecting from relevant node", channel), e);
    logger.trace(() -> new ParameterizedMessage("connect exception caught on transport layer [{}]", channel), e);
    logger.trace(() -> new ParameterizedMessage("bind exception caught on transport layer [{}]", channel), e);

代码示例来源:origin: org.elasticsearch/elasticsearch

@Override
public void close() {
  if (lifecycle.started()) {
    stop();
  }
  if (!lifecycle.canMoveToClosed()) {
    return;
  }
  for (LifecycleListener listener : listeners) {
    listener.beforeClose();
  }
  lifecycle.moveToClosed();
  try {
    doClose();
  } catch (IOException e) {
    // TODO: we need to separate out closing (ie shutting down) services, vs releasing runtime transient
    // structures. Shutting down services should use IOUtils.close
    logger.warn("failed to close " + getClass().getName(), e);
  }
  for (LifecycleListener listener : listeners) {
    listener.afterClose();
  }
}

代码示例来源:origin: com.strapdata.elasticsearch/elasticsearch

if (!lifecycle.moveToStarted()) {
  return this;
logger.info("activating ...");
logger.info("activated ...");
return this;

代码示例来源:origin: org.apache.servicemix.bundles/org.apache.servicemix.bundles.elasticsearch

@Override
public void close() {
  if (isClosing.compareAndSet(false, true)) {
    try {
      if (lifecycle.stopped()) {
        /* We set SO_LINGER timeout to 0 to ensure that when we shutdown the node we don't
         * have a gazillion connections sitting in TIME_WAIT to free up resources quickly.
         * This is really the only part where we close the connection from the server side
         * otherwise the client (node) initiates the TCP closing sequence which doesn't cause
         * these issues. Setting this by default from the beginning can have unexpected
         * side-effects an should be avoided, our protocol is designed in a way that clients
         * close connection which is how it should be*/
        channels.forEach(c -> {
          try {
            c.setSoLinger(0);
          } catch (IOException e) {
            logger.warn(new ParameterizedMessage("unexpected exception when setting SO_LINGER on channel {}", c), e);
          }
        });
      }
      boolean block = lifecycle.stopped() && Transports.isTransportThread(Thread.currentThread()) == false;
      TcpChannel.closeChannels(channels, block);
    } finally {
      // Call the super method to trigger listeners
      super.close();
    }
  }
}

代码示例来源:origin: com.strapdata.elasticsearch/elasticsearch

/**
 * entry point for incoming messages
 *
 * @param version the version used to serialize the message
 * @param data message data
 * @param action the action associated with this message (only used for error handling when data is not parsable)
 * @param requestId requestId if the message is request (only used for error handling when data is not parsable)
 * @param sourceTransport the source transport to respond to.
 */
public void receiveMessage(Version version, byte[] data, String action, @Nullable Long requestId, LocalTransport sourceTransport) {
  try {
    workers().execute(() -> {
      ThreadContext threadContext = threadPool.getThreadContext();
      try (ThreadContext.StoredContext context = threadContext.stashContext()) {
        processReceivedMessage(data, action, sourceTransport, version, requestId);
      }
    });
  } catch (EsRejectedExecutionException e)  {
    assert lifecycle.started() == false;
    logger.trace("received request but shutting down. ignoring. action [{}], request id [{}]", action, requestId);
  }
}

代码示例来源:origin: org.elasticsearch/elasticsearch

/**
 * Checks if changes (adding / removing) indices, shards and so on are allowed.
 *
 * @throws IllegalStateException if no changes allowed.
 */
private void ensureChangesAllowed() {
  if (lifecycle.started() == false) {
    throw new IllegalStateException("Can't make changes to indices service, node is closed");
  }
}

代码示例来源:origin: org.fusesource.insight/insight-elasticsearch

public void close() {
  if (lifecycle.started()) {
    stop();
  if (!lifecycle.moveToClosed()) {
    return;

代码示例来源:origin: harbby/presto-connectors

@Override
public void close() {
  if (lifecycle.started()) {
    stop();
  }
  if (!lifecycle.canMoveToClosed()) {
    return;
  }
  for (LifecycleListener listener : listeners) {
    listener.beforeClose();
  }
  lifecycle.moveToClosed();
  doClose();
  for (LifecycleListener listener : listeners) {
    listener.afterClose();
  }
}

代码示例来源:origin: org.elasticsearch/elasticsearch

final Map<T, ClusterStateTaskListener> tasks, final ClusterStateTaskConfig config,
                  final ClusterStateTaskExecutor<T> executor) {
if (!lifecycle.started()) {
  return;
  if (!lifecycle.stoppedOrClosed()) {
    throw e;

相关文章