Ejemplo n.º 1
0
    /** Builds a new instance of the transport client. */
    public TransportClient build() {
      Settings settings = InternalSettingsPreparer.prepareSettings(this.settings);
      settings =
          settingsBuilder()
              .put(
                  NettyTransport.PING_SCHEDULE,
                  "5s") // enable by default the transport schedule ping interval
              .put(settings)
              .put("network.server", false)
              .put("node.client", true)
              .put(CLIENT_TYPE_SETTING, CLIENT_TYPE)
              .build();

      PluginsService pluginsService = new PluginsService(settings, null, null, pluginClasses);
      this.settings = pluginsService.updatedSettings();

      Version version = Version.CURRENT;

      final ThreadPool threadPool = new ThreadPool(settings);
      final NetworkService networkService = new NetworkService(settings);
      final SettingsFilter settingsFilter = new SettingsFilter(settings);
      NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
      boolean success = false;
      try {
        ModulesBuilder modules = new ModulesBuilder();
        modules.add(new Version.Module(version));
        // plugin modules must be added here, before others or we can get crazy injection errors...
        for (Module pluginModule : pluginsService.nodeModules()) {
          modules.add(pluginModule);
        }
        modules.add(new PluginsModule(pluginsService));
        modules.add(new SettingsModule(this.settings, settingsFilter));
        modules.add(new NetworkModule(networkService, this.settings, true, namedWriteableRegistry));
        modules.add(new ClusterNameModule(this.settings));
        modules.add(new ThreadPoolModule(threadPool));
        modules.add(
            new SearchModule(settings, namedWriteableRegistry) {
              @Override
              protected void configure() {
                // noop
              }
            });
        modules.add(new ActionModule(true));
        modules.add(new CircuitBreakerModule(this.settings));

        pluginsService.processModules(modules);

        Injector injector = modules.createInjector();
        injector.getInstance(TransportService.class).start();
        TransportClient transportClient = new TransportClient(injector);
        success = true;
        return transportClient;
      } finally {
        if (!success) {
          ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS);
        }
      }
    }
Ejemplo n.º 2
0
 @Override
 public Iterable<? extends Module> spawnModules() {
   List<Module> modules = Lists.newArrayList();
   Collection<Class<? extends Module>> modulesClasses = pluginsService.modules();
   for (Class<? extends Module> moduleClass : modulesClasses) {
     modules.add(createModule(moduleClass, settings));
   }
   modules.addAll(pluginsService.modules(settings));
   return modules;
 }
 public void testOnModuleExceptionsArePropagated() {
   Settings settings = Settings.builder().put("path.home", createTempDir()).build();
   PluginsService service = newPluginsService(settings, FailOnModule.class);
   try {
     service.processModule(new BrokenModule());
     fail("boom");
   } catch (ElasticsearchException ex) {
     assertEquals("failed to invoke onModule", ex.getMessage());
     assertEquals("boom", ex.getCause().getCause().getMessage());
   }
 }
 public void testAdditionalSettingsClash() {
   Settings settings = Settings.builder().put("path.home", createTempDir()).build();
   PluginsService service =
       newPluginsService(
           settings, AdditionalSettingsPlugin1.class, AdditionalSettingsPlugin2.class);
   try {
     service.updatedSettings();
     fail("Expected exception when building updated settings");
   } catch (IllegalArgumentException e) {
     String msg = e.getMessage();
     assertTrue(msg, msg.contains("Cannot have additional setting [foo.bar]"));
     assertTrue(msg, msg.contains("plugin [additional-settings1]"));
     assertTrue(msg, msg.contains("plugin [additional-settings2]"));
   }
 }
Ejemplo n.º 5
0
    /** Builds a new instance of the transport client. */
    public TransportClient build() {
      final PluginsService pluginsService = newPluginService(providedSettings);
      final Settings settings = pluginsService.updatedSettings();

      Version version = Version.CURRENT;

      final ThreadPool threadPool = new ThreadPool(settings);
      final NetworkService networkService = new NetworkService(settings);
      NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
      boolean success = false;
      try {
        ModulesBuilder modules = new ModulesBuilder();
        modules.add(new Version.Module(version));
        // plugin modules must be added here, before others or we can get crazy injection errors...
        for (Module pluginModule : pluginsService.nodeModules()) {
          modules.add(pluginModule);
        }
        modules.add(new PluginsModule(pluginsService));
        modules.add(new SettingsModule(settings));
        modules.add(new NetworkModule(networkService, settings, true, namedWriteableRegistry));
        modules.add(new ClusterNameModule(settings));
        modules.add(new ThreadPoolModule(threadPool));
        modules.add(
            new SearchModule(settings, namedWriteableRegistry) {
              @Override
              protected void configure() {
                // noop
              }
            });
        modules.add(new ActionModule(false, true));
        modules.add(new CircuitBreakerModule(settings));

        pluginsService.processModules(modules);

        Injector injector = modules.createInjector();
        final TransportService transportService = injector.getInstance(TransportService.class);
        transportService.start();
        transportService.acceptIncomingRequests();

        TransportClient transportClient = new TransportClient(injector);
        success = true;
        return transportClient;
      } finally {
        if (!success) {
          ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS);
        }
      }
    }
Ejemplo n.º 6
0
  /** check a candidate plugin for jar hell before installing it */
  private void jarHellCheck(Path candidate, boolean isolated) throws IOException {
    // create list of current jars in classpath
    final List<URL> jars = new ArrayList<>(Arrays.asList(JarHell.parseClassPath()));

    // read existing bundles. this does some checks on the installation too.
    List<Bundle> bundles = PluginsService.getPluginBundles(environment.pluginsFile());

    // if we aren't isolated, we need to jarhellcheck against any other non-isolated plugins
    // thats always the first bundle
    if (isolated == false) {
      jars.addAll(bundles.get(0).urls);
    }

    // add plugin jars to the list
    Path pluginJars[] = FileSystemUtils.files(candidate, "*.jar");
    for (Path jar : pluginJars) {
      jars.add(jar.toUri().toURL());
    }

    // check combined (current classpath + new jars to-be-added)
    try {
      JarHell.checkJarHell(jars.toArray(new URL[jars.size()]));
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }
Ejemplo n.º 7
0
  @Override
  public Node stop() {
    if (!lifecycle.moveToStopped()) {
      return this;
    }
    ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
    logger.info("{{}}[{}]: stopping ...", Version.full(), JvmInfo.jvmInfo().pid());

    if (settings.getAsBoolean("http.enabled", true)) {
      injector.getInstance(HttpServer.class).stop();
    }
    injector.getInstance(RoutingService.class).stop();
    injector.getInstance(ClusterService.class).stop();
    injector.getInstance(DiscoveryService.class).stop();
    injector.getInstance(MonitorService.class).stop();
    injector.getInstance(GatewayService.class).stop();
    injector.getInstance(SearchService.class).stop();
    injector.getInstance(RiversManager.class).stop();
    injector.getInstance(IndicesClusterStateService.class).stop();
    injector.getInstance(IndicesService.class).stop();
    injector.getInstance(RestController.class).stop();
    injector.getInstance(TransportService.class).stop();
    injector.getInstance(JmxService.class).close();

    for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
      injector.getInstance(plugin).stop();
    }

    logger.info("{{}}[{}]: stopped", Version.full(), JvmInfo.jvmInfo().pid());

    return this;
  }
Ejemplo n.º 8
0
  @Override
  protected void configure() {
    bind(PluginsService.class).toInstance(pluginsService);

    Collection<Class<? extends Module>> modules = pluginsService.modules();
    for (Class<? extends Module> module : modules) {
      createModule(module, settings).configure(binder());
    }
  }
 public void testAdditionalSettings() {
   Settings settings =
       Settings.builder()
           .put("path.home", createTempDir())
           .put("my.setting", "test")
           .put(
               IndexModule.INDEX_STORE_TYPE_SETTING.getKey(),
               IndexModule.Type.SIMPLEFS.getSettingsKey())
           .build();
   PluginsService service = newPluginsService(settings, AdditionalSettingsPlugin1.class);
   Settings newSettings = service.updatedSettings();
   assertEquals("test", newSettings.get("my.setting")); // previous settings still exist
   assertEquals("1", newSettings.get("foo.bar")); // added setting exists
   assertEquals(
       IndexModule.Type.SIMPLEFS.getSettingsKey(),
       newSettings.get(
           IndexModule.INDEX_STORE_TYPE_SETTING
               .getKey())); // does not override pre existing settings
 }
 public void testExistingPluginMissingDescriptor() throws Exception {
   Path pluginsDir = createTempDir();
   Files.createDirectory(pluginsDir.resolve("plugin-missing-descriptor"));
   try {
     PluginsService.getPluginBundles(pluginsDir);
     fail();
   } catch (IllegalStateException e) {
     assertTrue(
         e.getMessage(),
         e.getMessage().contains("Could not load plugin descriptor for existing plugin"));
   }
 }
Ejemplo n.º 11
0
  @Override
  public Node stop() {
    if (!lifecycle.moveToStopped()) {
      return this;
    }
    ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
    logger.info("stopping ...");

    injector.getInstance(TribeService.class).stop();
    injector.getInstance(ResourceWatcherService.class).stop();
    if (settings.getAsBoolean("http.enabled", true)) {
      injector.getInstance(HttpServer.class).stop();
    }

    injector.getInstance(MappingUpdatedAction.class).stop();
    injector.getInstance(RiversManager.class).stop();

    injector.getInstance(SnapshotsService.class).stop();
    // stop any changes happening as a result of cluster state changes
    injector.getInstance(IndicesClusterStateService.class).stop();
    // we close indices first, so operations won't be allowed on it
    injector.getInstance(IndexingMemoryController.class).stop();
    injector.getInstance(IndicesTTLService.class).stop();
    injector.getInstance(IndicesService.class).stop();
    // sleep a bit to let operations finish with indices service
    //        try {
    //            Thread.sleep(500);
    //        } catch (InterruptedException e) {
    //            // ignore
    //        }
    injector.getInstance(RoutingService.class).stop();
    injector.getInstance(ClusterService.class).stop();
    injector.getInstance(DiscoveryService.class).stop();
    injector.getInstance(MonitorService.class).stop();
    injector.getInstance(GatewayService.class).stop();
    injector.getInstance(SearchService.class).stop();
    injector.getInstance(RestController.class).stop();
    injector.getInstance(TransportService.class).stop();

    for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
      injector.getInstance(plugin).stop();
    }

    logger.info("stopped");

    return this;
  }
Ejemplo n.º 12
0
  public Node start() {
    if (!lifecycle.moveToStarted()) {
      return this;
    }

    ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
    logger.info("starting ...");

    // hack around dependency injection problem (for now...)
    injector
        .getInstance(Discovery.class)
        .setAllocationService(injector.getInstance(AllocationService.class));

    for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
      injector.getInstance(plugin).start();
    }

    injector.getInstance(MappingUpdatedAction.class).start();
    injector.getInstance(IndicesService.class).start();
    injector.getInstance(IndexingMemoryController.class).start();
    injector.getInstance(IndicesClusterStateService.class).start();
    injector.getInstance(IndicesTTLService.class).start();
    injector.getInstance(RiversManager.class).start();
    injector.getInstance(SnapshotsService.class).start();
    injector.getInstance(TransportService.class).start();
    injector.getInstance(ClusterService.class).start();
    injector.getInstance(RoutingService.class).start();
    injector.getInstance(SearchService.class).start();
    injector.getInstance(MonitorService.class).start();
    injector.getInstance(RestController.class).start();
    DiscoveryService discoService = injector.getInstance(DiscoveryService.class).start();
    discoService.waitForInitialState();

    // gateway should start after disco, so it can try and recovery from gateway on "start"
    injector.getInstance(GatewayService.class).start();

    if (settings.getAsBoolean("http.enabled", true)) {
      injector.getInstance(HttpServer.class).start();
    }
    injector.getInstance(ResourceWatcherService.class).start();
    injector.getInstance(TribeService.class).start();

    logger.info("started");

    return this;
  }
Ejemplo n.º 13
0
  public InternalNode(Settings pSettings, boolean loadConfigSettings)
      throws ElasticSearchException {
    Tuple<Settings, Environment> tuple =
        InternalSettingsPerparer.prepareSettings(pSettings, loadConfigSettings);

    ESLogger logger = Loggers.getLogger(Node.class, tuple.v1().get("name"));
    logger.info("{{}}[{}]: initializing ...", Version.full(), JvmInfo.jvmInfo().pid());

    this.pluginsService = new PluginsService(tuple.v1(), tuple.v2());
    this.settings = pluginsService.updatedSettings();
    this.environment = tuple.v2();

    ModulesBuilder modules = new ModulesBuilder();
    modules.add(new PluginsModule(settings, pluginsService));
    modules.add(new SettingsModule(settings));
    modules.add(new NodeModule(this));
    modules.add(new NetworkModule());
    modules.add(new NodeCacheModule(settings));
    modules.add(new ScriptModule());
    modules.add(new JmxModule(settings));
    modules.add(new EnvironmentModule(environment));
    modules.add(new NodeEnvironmentModule());
    modules.add(new ClusterNameModule(settings));
    modules.add(new ThreadPoolModule(settings));
    modules.add(new TimerModule());
    modules.add(new DiscoveryModule(settings));
    modules.add(new ClusterModule(settings));
    modules.add(new RestModule(settings));
    modules.add(new TransportModule(settings));
    if (settings.getAsBoolean("http.enabled", true)) {
      modules.add(new HttpServerModule(settings));
    }
    modules.add(new RiversModule(settings));
    modules.add(new IndicesModule(settings));
    modules.add(new SearchModule());
    modules.add(new TransportActionModule());
    modules.add(new MonitorModule(settings));
    modules.add(new GatewayModule(settings));
    modules.add(new NodeClientModule());

    injector = modules.createInjector();

    client = injector.getInstance(Client.class);

    logger.info("{{}}[{}]: initialized", Version.full(), JvmInfo.jvmInfo().pid());
  }
Ejemplo n.º 14
0
  public Node start() {
    if (!lifecycle.moveToStarted()) {
      return this;
    }

    ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
    logger.info("{{}}[{}]: starting ...", Version.full(), JvmInfo.jvmInfo().pid());

    for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
      injector.getInstance(plugin).start();
    }

    injector.getInstance(IndicesService.class).start();
    injector.getInstance(IndexingMemoryBufferController.class).start();
    injector.getInstance(IndicesClusterStateService.class).start();
    injector.getInstance(RiversManager.class).start();
    injector.getInstance(ClusterService.class).start();
    injector.getInstance(RoutingService.class).start();
    injector.getInstance(SearchService.class).start();
    injector.getInstance(MonitorService.class).start();
    injector.getInstance(RestController.class).start();
    injector.getInstance(TransportService.class).start();
    DiscoveryService discoService = injector.getInstance(DiscoveryService.class).start();

    // gateway should start after disco, so it can try and recovery from gateway on "start"
    injector.getInstance(GatewayService.class).start();

    if (settings.getAsBoolean("http.enabled", true)) {
      injector.getInstance(HttpServer.class).start();
    }
    injector
        .getInstance(JmxService.class)
        .connectAndRegister(
            discoService.nodeDescription(), injector.getInstance(NetworkService.class));

    logger.info("{{}}[{}]: started", Version.full(), JvmInfo.jvmInfo().pid());

    return this;
  }
Ejemplo n.º 15
0
 @Override
 public void processModule(Module module) {
   pluginsService.processModule(module);
 }
Ejemplo n.º 16
0
  // During concurrent close() calls we want to make sure that all of them return after the node has
  // completed it's shutdown cycle.
  // If not, the hook that is added in Bootstrap#setup() will be useless: close() might not be
  // executed, in case another (for example api) call
  // to close() has already set some lifecycles to stopped. In this case the process will be
  // terminated even if the first call to close() has not finished yet.
  public synchronized void close() {
    if (lifecycle.started()) {
      stop();
    }
    if (!lifecycle.moveToClosed()) {
      return;
    }

    ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
    logger.info("closing ...");

    StopWatch stopWatch = new StopWatch("node_close");
    stopWatch.start("tribe");
    injector.getInstance(TribeService.class).close();
    stopWatch.stop().start("http");
    if (settings.getAsBoolean("http.enabled", true)) {
      injector.getInstance(HttpServer.class).close();
    }

    stopWatch.stop().start("rivers");
    injector.getInstance(RiversManager.class).close();

    stopWatch.stop().start("snapshot_service");
    injector.getInstance(SnapshotsService.class).close();
    stopWatch.stop().start("client");
    Releasables.close(injector.getInstance(Client.class));
    stopWatch.stop().start("indices_cluster");
    injector.getInstance(IndicesClusterStateService.class).close();
    stopWatch.stop().start("indices");
    injector.getInstance(IndicesFilterCache.class).close();
    injector.getInstance(IndicesFieldDataCache.class).close();
    injector.getInstance(IndexingMemoryController.class).close();
    injector.getInstance(IndicesTTLService.class).close();
    injector.getInstance(IndicesService.class).close();
    stopWatch.stop().start("routing");
    injector.getInstance(RoutingService.class).close();
    stopWatch.stop().start("cluster");
    injector.getInstance(ClusterService.class).close();
    stopWatch.stop().start("discovery");
    injector.getInstance(DiscoveryService.class).close();
    stopWatch.stop().start("monitor");
    injector.getInstance(MonitorService.class).close();
    stopWatch.stop().start("gateway");
    injector.getInstance(GatewayService.class).close();
    stopWatch.stop().start("search");
    injector.getInstance(SearchService.class).close();
    stopWatch.stop().start("rest");
    injector.getInstance(RestController.class).close();
    stopWatch.stop().start("transport");
    injector.getInstance(TransportService.class).close();
    stopWatch.stop().start("percolator_service");
    injector.getInstance(PercolatorService.class).close();

    for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
      stopWatch.stop().start("plugin(" + plugin.getName() + ")");
      injector.getInstance(plugin).close();
    }

    stopWatch.stop().start("script");
    injector.getInstance(ScriptService.class).close();

    stopWatch.stop().start("thread_pool");
    // TODO this should really use ThreadPool.terminate()
    injector.getInstance(ThreadPool.class).shutdown();
    try {
      injector.getInstance(ThreadPool.class).awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      // ignore
    }
    stopWatch.stop().start("thread_pool_force_shutdown");
    try {
      injector.getInstance(ThreadPool.class).shutdownNow();
    } catch (Exception e) {
      // ignore
    }
    stopWatch.stop();

    if (logger.isTraceEnabled()) {
      logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint());
    }

    injector.getInstance(NodeEnvironment.class).close();
    injector.getInstance(PageCacheRecycler.class).close();
    Injectors.close(injector);

    CachedStreams.clear();

    logger.info("closed");
  }
Ejemplo n.º 17
0
  public InternalNode(Settings preparedSettings, boolean loadConfigSettings)
      throws ElasticsearchException {
    final Settings pSettings =
        settingsBuilder()
            .put(preparedSettings)
            .put(Client.CLIENT_TYPE_SETTING, CLIENT_TYPE)
            .build();
    Tuple<Settings, Environment> tuple =
        InternalSettingsPreparer.prepareSettings(pSettings, loadConfigSettings);
    tuple = new Tuple<>(TribeService.processSettings(tuple.v1()), tuple.v2());

    // The only place we can actually fake the version a node is running on:
    Version version = pSettings.getAsVersion("tests.mock.version", Version.CURRENT);

    ESLogger logger = Loggers.getLogger(Node.class, tuple.v1().get("name"));
    logger.info(
        "version[{}], pid[{}], build[{}/{}]",
        version,
        JvmInfo.jvmInfo().pid(),
        Build.CURRENT.hashShort(),
        Build.CURRENT.timestamp());

    logger.info("initializing ...");

    if (logger.isDebugEnabled()) {
      Environment env = tuple.v2();
      logger.debug(
          "using home [{}], config [{}], data [{}], logs [{}], work [{}], plugins [{}]",
          env.homeFile(),
          env.configFile(),
          Arrays.toString(env.dataFiles()),
          env.logsFile(),
          env.workFile(),
          env.pluginsFile());
    }

    this.pluginsService = new PluginsService(tuple.v1(), tuple.v2());
    this.settings = pluginsService.updatedSettings();
    // create the environment based on the finalized (processed) view of the settings
    this.environment = new Environment(this.settings());

    CompressorFactory.configure(settings);
    final NodeEnvironment nodeEnvironment;
    try {
      nodeEnvironment = new NodeEnvironment(this.settings, this.environment);
    } catch (IOException ex) {
      throw new ElasticsearchIllegalStateException("Failed to created node environment", ex);
    }

    boolean success = false;
    try {
      ModulesBuilder modules = new ModulesBuilder();
      modules.add(new Version.Module(version));
      modules.add(new PageCacheRecyclerModule(settings));
      modules.add(new CircuitBreakerModule(settings));
      modules.add(new BigArraysModule(settings));
      modules.add(new PluginsModule(settings, pluginsService));
      modules.add(new SettingsModule(settings));
      modules.add(new NodeModule(this));
      modules.add(new NetworkModule());
      modules.add(new ScriptModule(settings));
      modules.add(new EnvironmentModule(environment));
      modules.add(new NodeEnvironmentModule(nodeEnvironment));
      modules.add(new ClusterNameModule(settings));
      modules.add(new ThreadPoolModule(settings));
      modules.add(new DiscoveryModule(settings));
      modules.add(new ClusterModule(settings));
      modules.add(new RestModule(settings));
      modules.add(new TransportModule(settings));
      if (settings.getAsBoolean(HTTP_ENABLED, true)) {
        modules.add(new HttpServerModule(settings));
      }
      modules.add(new RiversModule(settings));
      modules.add(new IndicesModule(settings));
      modules.add(new SearchModule());
      modules.add(new ActionModule(false));
      modules.add(new MonitorModule(settings));
      modules.add(new GatewayModule(settings));
      modules.add(new NodeClientModule());
      modules.add(new ShapeModule());
      modules.add(new PercolatorModule());
      modules.add(new ResourceWatcherModule());
      modules.add(new RepositoriesModule());
      modules.add(new TribeModule());
      modules.add(new BenchmarkModule(settings));

      injector = modules.createInjector();

      client = injector.getInstance(Client.class);
      success = true;
    } finally {
      if (!success) {
        nodeEnvironment.close();
      }
    }

    logger.info("initialized");
  }
  private void deleteShard(
      int shardId, boolean delete, boolean snapshotGateway, boolean deleteGateway)
      throws ElasticSearchException {
    Injector shardInjector;
    IndexShard indexShard;
    synchronized (this) {
      Map<Integer, Injector> tmpShardInjectors = newHashMap(shardsInjectors);
      shardInjector = tmpShardInjectors.remove(shardId);
      if (shardInjector == null) {
        if (!delete) {
          return;
        }
        throw new IndexShardMissingException(new ShardId(index, shardId));
      }
      shardsInjectors = ImmutableMap.copyOf(tmpShardInjectors);
      if (delete) {
        logger.debug("deleting shard_id [{}]", shardId);
      }

      Map<Integer, IndexShard> tmpShardsMap = newHashMap(shards);
      indexShard = tmpShardsMap.remove(shardId);
      shards = ImmutableMap.copyOf(tmpShardsMap);
    }

    ShardId sId = new ShardId(index, shardId);

    indicesLifecycle.beforeIndexShardClosed(sId, indexShard, delete);

    for (Class<? extends CloseableIndexComponent> closeable : pluginsService.shardServices()) {
      try {
        shardInjector.getInstance(closeable).close(delete);
      } catch (Exception e) {
        logger.debug("failed to clean plugin shard service [{}]", e, closeable);
      }
    }

    try {
      // now we can close the translog service, we need to close it before the we close the shard
      shardInjector.getInstance(TranslogService.class).close();
    } catch (Exception e) {
      // ignore
    }

    // close shard actions
    if (indexShard != null) {
      shardInjector.getInstance(IndexShardManagement.class).close();
    }

    // this logic is tricky, we want to close the engine so we rollback the changes done to it
    // and close the shard so no operations are allowed to it
    if (indexShard != null) {
      indexShard.close();
    }
    try {
      shardInjector.getInstance(Engine.class).close();
    } catch (Exception e) {
      // ignore
    }

    try {
      // now, we can snapshot to the gateway, it will be only the translog
      if (snapshotGateway) {
        shardInjector.getInstance(IndexShardGatewayService.class).snapshotOnClose();
      }
    } catch (Exception e) {
      // ignore
    }
    try {
      shardInjector.getInstance(IndexShardGatewayService.class).close(deleteGateway);
    } catch (Exception e) {
      // ignore
    }
    try {
      // now we can close the translog
      shardInjector.getInstance(Translog.class).close(delete);
    } catch (Exception e) {
      // ignore
    }

    // call this before we close the store, so we can release resources for it
    indicesLifecycle.afterIndexShardClosed(sId, delete);

    // if we delete or have no gateway or the store is not persistent, clean the store...
    Store store = shardInjector.getInstance(Store.class);
    if (delete || indexGateway.type().equals(NoneGateway.TYPE) || !indexStore.persistent()) {
      try {
        store.fullDelete();
      } catch (IOException e) {
        logger.warn("failed to clean store on shard deletion", e);
      }
    }
    // and close it
    try {
      store.close();
    } catch (IOException e) {
      logger.warn("failed to close store on shard deletion", e);
    }

    Injectors.close(injector);

    // delete the shard location if needed
    if (delete || indexGateway.type().equals(NoneGateway.TYPE)) {
      FileSystemUtils.deleteRecursively(nodeEnv.shardLocation(sId));
    }
  }
Ejemplo n.º 19
0
  public void close() {
    if (lifecycle.started()) {
      stop();
    }
    if (!lifecycle.moveToClosed()) {
      return;
    }

    ESLogger logger = Loggers.getLogger(Node.class, settings.get("name"));
    logger.info("{{}}[{}]: closing ...", Version.full(), JvmInfo.jvmInfo().pid());

    StopWatch stopWatch = new StopWatch("node_close");
    stopWatch.start("http");
    if (settings.getAsBoolean("http.enabled", true)) {
      injector.getInstance(HttpServer.class).close();
    }
    stopWatch.stop().start("client");
    injector.getInstance(Client.class).close();
    stopWatch.stop().start("routing");
    injector.getInstance(RoutingService.class).close();
    stopWatch.stop().start("cluster");
    injector.getInstance(ClusterService.class).close();
    stopWatch.stop().start("discovery");
    injector.getInstance(DiscoveryService.class).close();
    stopWatch.stop().start("monitor");
    injector.getInstance(MonitorService.class).close();
    stopWatch.stop().start("gateway");
    injector.getInstance(GatewayService.class).close();
    stopWatch.stop().start("search");
    injector.getInstance(SearchService.class).close();
    stopWatch.stop().start("indexers");
    injector.getInstance(RiversManager.class).close();
    stopWatch.stop().start("indices_cluster");
    injector.getInstance(IndicesClusterStateService.class).close();
    stopWatch.stop().start("indices");
    injector.getInstance(IndicesService.class).close();
    stopWatch.stop().start("rest");
    injector.getInstance(RestController.class).close();
    stopWatch.stop().start("transport");
    injector.getInstance(TransportService.class).close();

    for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
      stopWatch.stop().start("plugin(" + plugin.getName() + ")");
      injector.getInstance(plugin).close();
    }

    stopWatch.stop().start("node_cache");
    injector.getInstance(NodeCache.class).close();

    stopWatch.stop().start("script");
    injector.getInstance(ScriptService.class).close();

    stopWatch.stop().start("timer");
    injector.getInstance(TimerService.class).close();
    stopWatch.stop().start("thread_pool");
    injector.getInstance(ThreadPool.class).shutdown();
    try {
      injector.getInstance(ThreadPool.class).awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      // ignore
    }
    stopWatch.stop().start("thread_pool_force_shutdown");
    try {
      injector.getInstance(ThreadPool.class).shutdownNow();
    } catch (Exception e) {
      // ignore
    }
    stopWatch.stop();

    ThreadLocals.clearReferencesThreadLocals();

    if (logger.isTraceEnabled()) {
      logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint());
    }

    injector.getInstance(NodeEnvironment.class).close();
    Injectors.close(injector);

    logger.info("{{}}[{}]: closed", Version.full(), JvmInfo.jvmInfo().pid());
  }