use of org.elasticsearch.index.shard.IndexEventListener in project elasticsearch by elastic.
the class IndexModule method newIndexService.
public IndexService newIndexService(NodeEnvironment environment, NamedXContentRegistry xContentRegistry, IndexService.ShardStoreDeleter shardStoreDeleter, CircuitBreakerService circuitBreakerService, BigArrays bigArrays, ThreadPool threadPool, ScriptService scriptService, ClusterService clusterService, Client client, IndicesQueryCache indicesQueryCache, MapperRegistry mapperRegistry, Consumer<ShardId> globalCheckpointSyncer, IndicesFieldDataCache indicesFieldDataCache) throws IOException {
final IndexEventListener eventListener = freeze();
IndexSearcherWrapperFactory searcherWrapperFactory = indexSearcherWrapper.get() == null ? (shard) -> null : indexSearcherWrapper.get();
eventListener.beforeIndexCreated(indexSettings.getIndex(), indexSettings.getSettings());
final String storeType = indexSettings.getValue(INDEX_STORE_TYPE_SETTING);
final IndexStore store;
if (Strings.isEmpty(storeType) || isBuiltinType(storeType)) {
store = new IndexStore(indexSettings);
} else {
Function<IndexSettings, IndexStore> factory = storeTypes.get(storeType);
if (factory == null) {
throw new IllegalArgumentException("Unknown store type [" + storeType + "]");
}
store = factory.apply(indexSettings);
if (store == null) {
throw new IllegalStateException("store must not be null");
}
}
final QueryCache queryCache;
if (indexSettings.getValue(INDEX_QUERY_CACHE_ENABLED_SETTING)) {
BiFunction<IndexSettings, IndicesQueryCache, QueryCache> queryCacheProvider = forceQueryCacheProvider.get();
if (queryCacheProvider == null) {
queryCache = new IndexQueryCache(indexSettings, indicesQueryCache);
} else {
queryCache = queryCacheProvider.apply(indexSettings, indicesQueryCache);
}
} else {
queryCache = new DisabledQueryCache(indexSettings);
}
return new IndexService(indexSettings, environment, xContentRegistry, new SimilarityService(indexSettings, similarities), shardStoreDeleter, analysisRegistry, engineFactory.get(), circuitBreakerService, bigArrays, threadPool, scriptService, clusterService, client, queryCache, store, eventListener, searcherWrapperFactory, mapperRegistry, indicesFieldDataCache, globalCheckpointSyncer, searchOperationListeners, indexOperationListeners);
}
use of org.elasticsearch.index.shard.IndexEventListener in project elasticsearch by elastic.
the class RelocationIT method testRelocationWhileRefreshing.
@TestLogging("org.elasticsearch.action.bulk:TRACE,org.elasticsearch.action.search:TRACE")
public void testRelocationWhileRefreshing() throws Exception {
int numberOfRelocations = scaledRandomIntBetween(1, rarely() ? 10 : 4);
int numberOfReplicas = randomBoolean() ? 0 : 1;
int numberOfNodes = numberOfReplicas == 0 ? 2 : 3;
logger.info("testRelocationWhileIndexingRandom(numRelocations={}, numberOfReplicas={}, numberOfNodes={})", numberOfRelocations, numberOfReplicas, numberOfNodes);
String[] nodes = new String[numberOfNodes];
logger.info("--> starting [node_0] ...");
nodes[0] = internalCluster().startNode();
logger.info("--> creating test index ...");
prepareCreate("test", Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", numberOfReplicas).put("index.refresh_interval", // we want to control refreshes c
-1)).get();
for (int i = 1; i < numberOfNodes; i++) {
logger.info("--> starting [node_{}] ...", i);
nodes[i] = internalCluster().startNode();
if (i != numberOfNodes - 1) {
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes(Integer.toString(i + 1)).setWaitForGreenStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
}
}
final Semaphore postRecoveryShards = new Semaphore(0);
final IndexEventListener listener = new IndexEventListener() {
@Override
public void indexShardStateChanged(IndexShard indexShard, @Nullable IndexShardState previousState, IndexShardState currentState, @Nullable String reason) {
if (currentState == IndexShardState.POST_RECOVERY) {
postRecoveryShards.release();
}
}
};
for (MockIndexEventListener.TestEventListener eventListener : internalCluster().getInstances(MockIndexEventListener.TestEventListener.class)) {
eventListener.setNewDelegate(listener);
}
logger.info("--> starting relocations...");
// if we have replicas shift those
int nodeShiftBased = numberOfReplicas;
for (int i = 0; i < numberOfRelocations; i++) {
int fromNode = (i % 2);
int toNode = fromNode == 0 ? 1 : 0;
fromNode += nodeShiftBased;
toNode += nodeShiftBased;
List<IndexRequestBuilder> builders1 = new ArrayList<>();
for (int numDocs = randomIntBetween(10, 30); numDocs > 0; numDocs--) {
builders1.add(client().prepareIndex("test", "type").setSource("{}", XContentType.JSON));
}
List<IndexRequestBuilder> builders2 = new ArrayList<>();
for (int numDocs = randomIntBetween(10, 30); numDocs > 0; numDocs--) {
builders2.add(client().prepareIndex("test", "type").setSource("{}", XContentType.JSON));
}
logger.info("--> START relocate the shard from {} to {}", nodes[fromNode], nodes[toNode]);
client().admin().cluster().prepareReroute().add(new MoveAllocationCommand("test", 0, nodes[fromNode], nodes[toNode])).get();
logger.debug("--> index [{}] documents", builders1.size());
indexRandom(false, true, builders1);
// wait for shard to reach post recovery
postRecoveryShards.acquire(1);
logger.debug("--> index [{}] documents", builders2.size());
indexRandom(true, true, builders2);
// verify cluster was finished.
assertFalse(client().admin().cluster().prepareHealth().setWaitForNoRelocatingShards(true).setWaitForEvents(Priority.LANGUID).setTimeout("30s").get().isTimedOut());
logger.info("--> DONE relocate the shard from {} to {}", fromNode, toNode);
logger.debug("--> verifying all searches return the same number of docs");
long expectedCount = -1;
for (Client client : clients()) {
SearchResponse response = client.prepareSearch("test").setPreference("_local").setSize(0).get();
assertNoFailures(response);
if (expectedCount < 0) {
expectedCount = response.getHits().getTotalHits();
} else {
assertEquals(expectedCount, response.getHits().getTotalHits());
}
}
}
}
use of org.elasticsearch.index.shard.IndexEventListener in project elasticsearch by elastic.
the class IndicesLifecycleListenerIT method testBeforeIndexAddedToCluster.
public void testBeforeIndexAddedToCluster() throws Exception {
String node1 = internalCluster().startNode();
String node2 = internalCluster().startNode();
String node3 = internalCluster().startNode();
final AtomicInteger beforeAddedCount = new AtomicInteger(0);
final AtomicInteger allCreatedCount = new AtomicInteger(0);
IndexEventListener listener = new IndexEventListener() {
@Override
public void beforeIndexAddedToCluster(Index index, Settings indexSettings) {
beforeAddedCount.incrementAndGet();
if (MockIndexEventListener.TestPlugin.INDEX_FAIL.get(indexSettings)) {
throw new ElasticsearchException("failing on purpose");
}
}
@Override
public void beforeIndexCreated(Index index, Settings indexSettings) {
allCreatedCount.incrementAndGet();
}
};
internalCluster().getInstance(MockIndexEventListener.TestEventListener.class, node1).setNewDelegate(listener);
internalCluster().getInstance(MockIndexEventListener.TestEventListener.class, node2).setNewDelegate(listener);
internalCluster().getInstance(MockIndexEventListener.TestEventListener.class, node3).setNewDelegate(listener);
client().admin().indices().prepareCreate("test").setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 3, IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1).get();
ensureGreen("test");
assertThat("beforeIndexAddedToCluster called only once", beforeAddedCount.get(), equalTo(1));
assertThat("beforeIndexCreated called on each data node", allCreatedCount.get(), greaterThanOrEqualTo(3));
try {
client().admin().indices().prepareCreate("failed").setSettings("index.fail", true).get();
fail("should have thrown an exception during creation");
} catch (Exception e) {
assertTrue(e.getMessage().contains("failing on purpose"));
ClusterStateResponse resp = client().admin().cluster().prepareState().get();
assertFalse(resp.getState().routingTable().indicesRouting().keys().contains("failed"));
}
}
use of org.elasticsearch.index.shard.IndexEventListener in project elasticsearch by elastic.
the class IndicesLifecycleListenerSingleNodeTests method testStartDeleteIndexEventCallback.
public void testStartDeleteIndexEventCallback() throws Throwable {
IndicesService indicesService = getInstanceFromNode(IndicesService.class);
assertAcked(client().admin().indices().prepareCreate("test").setSettings(SETTING_NUMBER_OF_SHARDS, 1, SETTING_NUMBER_OF_REPLICAS, 0));
ensureGreen();
Index idx = resolveIndex("test");
IndexMetaData metaData = indicesService.indexService(idx).getMetaData();
ShardRouting shardRouting = indicesService.indexService(idx).getShard(0).routingEntry();
final AtomicInteger counter = new AtomicInteger(1);
IndexEventListener countingListener = new IndexEventListener() {
@Override
public void beforeIndexCreated(Index index, Settings indexSettings) {
assertEquals("test", index.getName());
assertEquals(1, counter.get());
counter.incrementAndGet();
}
@Override
public void afterIndexCreated(IndexService indexService) {
assertEquals("test", indexService.index().getName());
assertEquals(2, counter.get());
counter.incrementAndGet();
}
@Override
public void beforeIndexShardCreated(ShardId shardId, Settings indexSettings) {
assertEquals(3, counter.get());
counter.incrementAndGet();
}
@Override
public void afterIndexShardCreated(IndexShard indexShard) {
assertEquals(4, counter.get());
counter.incrementAndGet();
}
@Override
public void afterIndexShardStarted(IndexShard indexShard) {
assertEquals(5, counter.get());
counter.incrementAndGet();
}
@Override
public void beforeIndexRemoved(IndexService indexService, IndexRemovalReason reason) {
assertEquals(DELETED, reason);
assertEquals(6, counter.get());
counter.incrementAndGet();
}
@Override
public void beforeIndexShardDeleted(ShardId shardId, Settings indexSettings) {
assertEquals(7, counter.get());
counter.incrementAndGet();
}
@Override
public void afterIndexShardDeleted(ShardId shardId, Settings indexSettings) {
assertEquals(8, counter.get());
counter.incrementAndGet();
}
@Override
public void afterIndexRemoved(Index index, IndexSettings indexSettings, IndexRemovalReason reason) {
assertEquals(DELETED, reason);
assertEquals(9, counter.get());
counter.incrementAndGet();
}
};
indicesService.removeIndex(idx, DELETED, "simon says");
try {
IndexService index = indicesService.createIndex(metaData, Arrays.asList(countingListener), s -> {
});
assertEquals(3, counter.get());
idx = index.index();
ShardRouting newRouting = shardRouting;
String nodeId = newRouting.currentNodeId();
UnassignedInfo unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "boom");
newRouting = newRouting.moveToUnassigned(unassignedInfo).updateUnassigned(unassignedInfo, RecoverySource.StoreRecoverySource.EMPTY_STORE_INSTANCE);
newRouting = ShardRoutingHelper.initialize(newRouting, nodeId);
IndexShard shard = index.createShard(newRouting);
shard.updateRoutingEntry(newRouting);
assertEquals(5, counter.get());
final DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
shard.markAsRecovering("store", new RecoveryState(newRouting, localNode, null));
shard.recoverFromStore();
newRouting = ShardRoutingHelper.moveToStarted(newRouting);
shard.updateRoutingEntry(newRouting);
assertEquals(6, counter.get());
} finally {
indicesService.removeIndex(idx, DELETED, "simon says");
}
assertEquals(10, counter.get());
}
Aggregations