Search in sources :

Example 1 with ConcurrentMap

use of java.util.concurrent.ConcurrentMap in project elasticsearch by elastic.

the class AbstractIndicesClusterStateServiceTestCase method assertClusterStateMatchesNodeState.

/**
     * Checks if cluster state matches internal state of IndicesClusterStateService instance
     *
     * @param state cluster state used for matching
     */
public void assertClusterStateMatchesNodeState(ClusterState state, IndicesClusterStateService indicesClusterStateService) {
    MockIndicesService indicesService = (MockIndicesService) indicesClusterStateService.indicesService;
    ConcurrentMap<ShardId, ShardRouting> failedShardsCache = indicesClusterStateService.failedShardsCache;
    RoutingNode localRoutingNode = state.getRoutingNodes().node(state.getNodes().getLocalNodeId());
    if (localRoutingNode != null) {
        if (enableRandomFailures == false) {
            assertThat("failed shard cache should be empty", failedShardsCache.values(), empty());
        }
        // check that all shards in local routing nodes have been allocated
        for (ShardRouting shardRouting : localRoutingNode) {
            Index index = shardRouting.index();
            IndexMetaData indexMetaData = state.metaData().getIndexSafe(index);
            MockIndexShard shard = indicesService.getShardOrNull(shardRouting.shardId());
            ShardRouting failedShard = failedShardsCache.get(shardRouting.shardId());
            if (enableRandomFailures) {
                if (shard == null && failedShard == null) {
                    fail("Shard with id " + shardRouting + " expected but missing in indicesService and failedShardsCache");
                }
                if (failedShard != null && failedShard.isSameAllocation(shardRouting) == false) {
                    fail("Shard cache has not been properly cleaned for " + failedShard);
                }
            } else {
                if (shard == null) {
                    fail("Shard with id " + shardRouting + " expected but missing in indicesService");
                }
            }
            if (shard != null) {
                AllocatedIndex<? extends Shard> indexService = indicesService.indexService(index);
                assertTrue("Index " + index + " expected but missing in indicesService", indexService != null);
                // index metadata has been updated
                assertThat(indexService.getIndexSettings().getIndexMetaData(), equalTo(indexMetaData));
                // shard has been created
                if (enableRandomFailures == false || failedShard == null) {
                    assertTrue("Shard with id " + shardRouting + " expected but missing in indexService", shard != null);
                    // shard has latest shard routing
                    assertThat(shard.routingEntry(), equalTo(shardRouting));
                }
                if (shard.routingEntry().primary() && shard.routingEntry().active()) {
                    IndexShardRoutingTable shardRoutingTable = state.routingTable().shardRoutingTable(shard.shardId());
                    Set<String> activeIds = shardRoutingTable.activeShards().stream().map(r -> r.allocationId().getId()).collect(Collectors.toSet());
                    Set<String> initializingIds = shardRoutingTable.getAllInitializingShards().stream().map(r -> r.allocationId().getId()).collect(Collectors.toSet());
                    assertThat(shard.routingEntry() + " isn't updated with active aIDs", shard.activeAllocationIds, equalTo(activeIds));
                    assertThat(shard.routingEntry() + " isn't updated with init aIDs", shard.initializingAllocationIds, equalTo(initializingIds));
                }
            }
        }
    }
    // all other shards / indices have been cleaned up
    for (AllocatedIndex<? extends Shard> indexService : indicesService) {
        assertTrue(state.metaData().getIndexSafe(indexService.index()) != null);
        boolean shardsFound = false;
        for (Shard shard : indexService) {
            shardsFound = true;
            ShardRouting persistedShardRouting = shard.routingEntry();
            ShardRouting shardRouting = localRoutingNode.getByShardId(persistedShardRouting.shardId());
            if (shardRouting == null) {
                fail("Shard with id " + persistedShardRouting + " locally exists but missing in routing table");
            }
            if (shardRouting.equals(persistedShardRouting) == false) {
                fail("Local shard " + persistedShardRouting + " has stale routing" + shardRouting);
            }
        }
        if (shardsFound == false) {
            if (enableRandomFailures) {
                // check if we have shards of that index in failedShardsCache
                // if yes, we might not have cleaned the index as failedShardsCache can be populated by another thread
                assertFalse(failedShardsCache.keySet().stream().noneMatch(shardId -> shardId.getIndex().equals(indexService.index())));
            } else {
                fail("index service for index " + indexService.index() + " has no shards");
            }
        }
    }
}
Also used : ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ShardId(org.elasticsearch.index.shard.ShardId) Callback(org.elasticsearch.common.util.Callback) Shard(org.elasticsearch.indices.cluster.IndicesClusterStateService.Shard) Nullable(org.elasticsearch.common.Nullable) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) ConcurrentMap(java.util.concurrent.ConcurrentMap) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) TimeValue(org.elasticsearch.common.unit.TimeValue) Map(java.util.Map) IndexSettings(org.elasticsearch.index.IndexSettings) IndicesService(org.elasticsearch.indices.IndicesService) ESTestCase(org.elasticsearch.test.ESTestCase) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) IndexShardState(org.elasticsearch.index.shard.IndexShardState) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Iterator(java.util.Iterator) AllocatedIndex(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndex) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IOException(java.io.IOException) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) Collectors(java.util.stream.Collectors) MapBuilder.newMapBuilder(org.elasticsearch.common.collect.MapBuilder.newMapBuilder) Consumer(java.util.function.Consumer) List(java.util.List) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) AllocatedIndices(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) Index(org.elasticsearch.index.Index) AllocatedIndex(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndex) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardId(org.elasticsearch.index.shard.ShardId) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Shard(org.elasticsearch.indices.cluster.IndicesClusterStateService.Shard) IndexShard(org.elasticsearch.index.shard.IndexShard)

Example 2 with ConcurrentMap

use of java.util.concurrent.ConcurrentMap in project vert.x by eclipse.

the class FakeClusterManager method getAsyncMultiMap.

@Override
public <K, V> void getAsyncMultiMap(String name, Handler<AsyncResult<AsyncMultiMap<K, V>>> resultHandler) {
    ConcurrentMap map = asyncMultiMaps.get(name);
    if (map == null) {
        map = new ConcurrentHashMap<>();
        ConcurrentMap prevMap = asyncMultiMaps.putIfAbsent(name, map);
        if (prevMap != null) {
            map = prevMap;
        }
    }
    @SuppressWarnings("unchecked") ConcurrentMap<K, ChoosableSet<V>> theMap = map;
    vertx.runOnContext(v -> resultHandler.handle(Future.succeededFuture(new FakeAsyncMultiMap<>(theMap))));
}
Also used : ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 3 with ConcurrentMap

use of java.util.concurrent.ConcurrentMap in project vert.x by eclipse.

the class FakeClusterManager method getAsyncMap.

@Override
public <K, V> void getAsyncMap(String name, Handler<AsyncResult<AsyncMap<K, V>>> resultHandler) {
    ConcurrentMap map = asyncMaps.get(name);
    if (map == null) {
        map = new ConcurrentHashMap<>();
        ConcurrentMap prevMap = asyncMaps.putIfAbsent(name, map);
        if (prevMap != null) {
            map = prevMap;
        }
    }
    @SuppressWarnings("unchecked") ConcurrentMap<K, V> theMap = map;
    vertx.runOnContext(v -> resultHandler.handle(Future.succeededFuture(new FakeAsyncMap<>(theMap))));
}
Also used : ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 4 with ConcurrentMap

use of java.util.concurrent.ConcurrentMap in project crate by crate.

the class JobExecutionContextTest method testFailureClosesAllSubContexts.

@Test
public void testFailureClosesAllSubContexts() throws Exception {
    String localNodeId = "localNodeId";
    RoutedCollectPhase collectPhase = Mockito.mock(RoutedCollectPhase.class);
    Routing routing = Mockito.mock(Routing.class);
    when(routing.containsShards(localNodeId)).thenReturn(false);
    when(collectPhase.routing()).thenReturn(routing);
    when(collectPhase.maxRowGranularity()).thenReturn(RowGranularity.DOC);
    JobExecutionContext.Builder builder = new JobExecutionContext.Builder(UUID.randomUUID(), coordinatorNode, Collections.emptyList(), mock(JobsLogs.class));
    JobCollectContext jobCollectContext = new JobCollectContext(collectPhase, mock(MapSideDataCollectOperation.class), localNodeId, mock(RamAccountingContext.class), new TestingBatchConsumer(), mock(SharedShardContexts.class));
    TestingBatchConsumer batchConsumer = new TestingBatchConsumer();
    PageDownstreamContext pageDownstreamContext = spy(new PageDownstreamContext(Loggers.getLogger(PageDownstreamContext.class), "n1", 2, "dummy", batchConsumer, PassThroughPagingIterator.oneShot(), new Streamer[] { IntegerType.INSTANCE.streamer() }, mock(RamAccountingContext.class), 1));
    builder.addSubContext(jobCollectContext);
    builder.addSubContext(pageDownstreamContext);
    JobExecutionContext jobExecutionContext = builder.build();
    Exception failure = new Exception("failure!");
    jobCollectContext.close(failure);
    // other contexts must be killed with same failure
    verify(pageDownstreamContext, times(1)).innerKill(failure);
    final Field subContexts = JobExecutionContext.class.getDeclaredField("subContexts");
    subContexts.setAccessible(true);
    int size = ((ConcurrentMap<Integer, ExecutionSubContext>) subContexts.get(jobExecutionContext)).size();
    assertThat(size, is(0));
}
Also used : RamAccountingContext(io.crate.breaker.RamAccountingContext) MapSideDataCollectOperation(io.crate.operation.collect.MapSideDataCollectOperation) ConcurrentMap(java.util.concurrent.ConcurrentMap) Routing(io.crate.metadata.Routing) JobCollectContext(io.crate.operation.collect.JobCollectContext) Field(java.lang.reflect.Field) SharedShardContexts(io.crate.action.job.SharedShardContexts) Streamer(io.crate.Streamer) TestingBatchConsumer(io.crate.testing.TestingBatchConsumer) JobsLogs(io.crate.operation.collect.stats.JobsLogs) RoutedCollectPhase(io.crate.planner.node.dql.RoutedCollectPhase) Test(org.junit.Test) CrateUnitTest(io.crate.test.integration.CrateUnitTest)

Example 5 with ConcurrentMap

use of java.util.concurrent.ConcurrentMap in project buck by facebook.

the class DefaultFileHashCache method verify.

@Override
public FileHashCacheVerificationResult verify() throws IOException {
    List<String> errors = new ArrayList<>();
    ConcurrentMap<Path, HashCodeAndFileType> cacheMap = loadingCache.asMap();
    for (Map.Entry<Path, HashCodeAndFileType> entry : cacheMap.entrySet()) {
        Path path = entry.getKey();
        HashCodeAndFileType cached = entry.getValue();
        HashCodeAndFileType current = getHashCodeAndFileType(path);
        if (!cached.equals(current)) {
            errors.add(path.toString());
        }
    }
    return FileHashCacheVerificationResult.builder().setCachesExamined(1).setFilesExamined(cacheMap.size()).addAllVerificationErrors(errors).build();
}
Also used : ArchiveMemberPath(com.facebook.buck.io.ArchiveMemberPath) Path(java.nio.file.Path) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Aggregations

ConcurrentMap (java.util.concurrent.ConcurrentMap)450 Map (java.util.Map)125 Test (org.junit.Test)111 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)83 HashMap (java.util.HashMap)75 ArrayList (java.util.ArrayList)58 Set (java.util.Set)41 URL (com.alibaba.dubbo.common.URL)32 List (java.util.List)26 Collectors (java.util.stream.Collectors)22 IOException (java.io.IOException)21 HashSet (java.util.HashSet)21 Collection (java.util.Collection)19 UsageCount (org.apache.felix.framework.ServiceRegistry.UsageCount)19 Bundle (org.osgi.framework.Bundle)19 CountDownLatch (java.util.concurrent.CountDownLatch)18 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)16 Arrays (java.util.Arrays)15 Field (java.lang.reflect.Field)14 Iterator (java.util.Iterator)13