Search in sources :

Example 1 with ObjectLongMap

use of com.carrotsearch.hppc.ObjectLongMap in project elasticsearch by elastic.

the class ReplicaShardAllocator method findMatchingNodes.

private MatchingNodes findMatchingNodes(ShardRouting shard, RoutingAllocation allocation, TransportNodesListShardStoreMetaData.StoreFilesMetaData primaryStore, AsyncShardFetch.FetchResult<NodeStoreFilesMetaData> data, boolean explain) {
    ObjectLongMap<DiscoveryNode> nodesToSize = new ObjectLongHashMap<>();
    Map<String, NodeAllocationResult> nodeDecisions = explain ? new HashMap<>() : null;
    for (Map.Entry<DiscoveryNode, NodeStoreFilesMetaData> nodeStoreEntry : data.getData().entrySet()) {
        DiscoveryNode discoNode = nodeStoreEntry.getKey();
        TransportNodesListShardStoreMetaData.StoreFilesMetaData storeFilesMetaData = nodeStoreEntry.getValue().storeFilesMetaData();
        // we don't have any files at all, it is an empty index
        if (storeFilesMetaData.isEmpty()) {
            continue;
        }
        RoutingNode node = allocation.routingNodes().node(discoNode.getId());
        if (node == null) {
            continue;
        }
        // check if we can allocate on that node...
        // we only check for NO, since if this node is THROTTLING and it has enough "same data"
        // then we will try and assign it next time
        Decision decision = allocation.deciders().canAllocate(shard, node, allocation);
        long matchingBytes = -1;
        if (explain) {
            matchingBytes = computeMatchingBytes(primaryStore, storeFilesMetaData);
            ShardStoreInfo shardStoreInfo = new ShardStoreInfo(matchingBytes);
            nodeDecisions.put(node.nodeId(), new NodeAllocationResult(discoNode, shardStoreInfo, decision));
        }
        if (decision.type() == Decision.Type.NO) {
            continue;
        }
        if (matchingBytes < 0) {
            matchingBytes = computeMatchingBytes(primaryStore, storeFilesMetaData);
        }
        nodesToSize.put(discoNode, matchingBytes);
        if (logger.isTraceEnabled()) {
            if (matchingBytes == Long.MAX_VALUE) {
                logger.trace("{}: node [{}] has same sync id {} as primary", shard, discoNode.getName(), storeFilesMetaData.syncId());
            } else {
                logger.trace("{}: node [{}] has [{}/{}] bytes of re-usable data", shard, discoNode.getName(), new ByteSizeValue(matchingBytes), matchingBytes);
            }
        }
    }
    return new MatchingNodes(nodesToSize, nodeDecisions);
}
Also used : ObjectLongHashMap(com.carrotsearch.hppc.ObjectLongHashMap) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) TransportNodesListShardStoreMetaData(org.elasticsearch.indices.store.TransportNodesListShardStoreMetaData) AllocateUnassignedDecision(org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision) Decision(org.elasticsearch.cluster.routing.allocation.decider.Decision) ShardStoreInfo(org.elasticsearch.cluster.routing.allocation.NodeAllocationResult.ShardStoreInfo) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) HashMap(java.util.HashMap) ObjectLongHashMap(com.carrotsearch.hppc.ObjectLongHashMap) Map(java.util.Map) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) NodeAllocationResult(org.elasticsearch.cluster.routing.allocation.NodeAllocationResult) NodeStoreFilesMetaData(org.elasticsearch.indices.store.TransportNodesListShardStoreMetaData.NodeStoreFilesMetaData)

Example 2 with ObjectLongMap

use of com.carrotsearch.hppc.ObjectLongMap in project crate by crate.

the class TableStatsServiceTest method testRowsToTableStatConversion.

@Test
public void testRowsToTableStatConversion() throws InterruptedException, ExecutionException, TimeoutException {
    CompletableFuture<ObjectLongMap<TableIdent>> statsFuture = new CompletableFuture<>();
    TableStatsService.TableStatsResultReceiver receiver = new TableStatsService.TableStatsResultReceiver(statsFuture::complete);
    receiver.setNextRow(new RowN(new Object[] { 1L, "custom", "foo" }));
    receiver.setNextRow(new RowN(new Object[] { 2L, "doc", "foo" }));
    receiver.setNextRow(new RowN(new Object[] { 3L, "bar", "foo" }));
    receiver.allFinished(false);
    ObjectLongMap<TableIdent> stats = statsFuture.get(10, TimeUnit.SECONDS);
    assertThat(stats.size(), is(3));
    assertThat(stats.get(new TableIdent("bar", "foo")), is(3L));
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) RowN(io.crate.data.RowN) TableIdent(io.crate.metadata.TableIdent) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) Test(org.junit.Test) CrateUnitTest(io.crate.test.integration.CrateUnitTest)

Example 3 with ObjectLongMap

use of com.carrotsearch.hppc.ObjectLongMap in project crate by crate.

the class IndexShard method maybeSyncGlobalCheckpoint.

/**
 * Syncs the global checkpoint to the replicas if the global checkpoint on at least one replica is behind the global checkpoint on the
 * primary.
 */
public void maybeSyncGlobalCheckpoint(final String reason) {
    verifyNotClosed();
    assert shardRouting.primary() : "only call maybeSyncGlobalCheckpoint on primary shard";
    if (replicationTracker.isPrimaryMode() == false) {
        return;
    }
    assert assertPrimaryMode();
    // only sync if there are no operations in flight, or when using async durability
    final SeqNoStats stats = getEngine().getSeqNoStats(replicationTracker.getGlobalCheckpoint());
    final boolean asyncDurability = indexSettings().getTranslogDurability() == Translog.Durability.ASYNC;
    if (stats.getMaxSeqNo() == stats.getGlobalCheckpoint() || asyncDurability) {
        final ObjectLongMap<String> globalCheckpoints = getInSyncGlobalCheckpoints();
        final long globalCheckpoint = replicationTracker.getGlobalCheckpoint();
        // async durability means that the local checkpoint might lag (as it is only advanced on fsync)
        // periodically ask for the newest local checkpoint by syncing the global checkpoint, so that ultimately the global
        // checkpoint can be synced. Also take into account that a shard might be pending sync, which means that it isn't
        // in the in-sync set just yet but might be blocked on waiting for its persisted local checkpoint to catch up to
        // the global checkpoint.
        final boolean syncNeeded = (asyncDurability && (stats.getGlobalCheckpoint() < stats.getMaxSeqNo() || replicationTracker.pendingInSync())) || // check if the persisted global checkpoint
        StreamSupport.stream(globalCheckpoints.values().spliterator(), false).anyMatch(v -> v.value < globalCheckpoint);
        // only sync if index is not closed and there is a shard lagging the primary
        if (syncNeeded && indexSettings.getIndexMetadata().getState() == IndexMetadata.State.OPEN) {
            logger.trace("syncing global checkpoint for [{}]", reason);
            globalCheckpointSyncer.run();
        }
    }
}
Also used : Query(org.apache.lucene.search.Query) UpgradeRequest(org.elasticsearch.action.admin.indices.upgrade.post.UpgradeRequest) LongSupplier(java.util.function.LongSupplier) BigArrays(org.elasticsearch.common.util.BigArrays) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) RecoveryStats(org.elasticsearch.index.recovery.RecoveryStats) ReferenceManager(org.apache.lucene.search.ReferenceManager) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) UsageTrackingQueryCachingPolicy(org.apache.lucene.search.UsageTrackingQueryCachingPolicy) EngineConfig(org.elasticsearch.index.engine.EngineConfig) WriteStateException(org.elasticsearch.gateway.WriteStateException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Map(java.util.Map) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) QueryCachingPolicy(org.apache.lucene.search.QueryCachingPolicy) CheckedRunnable(org.elasticsearch.common.CheckedRunnable) EnumSet(java.util.EnumSet) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) Booleans(io.crate.common.Booleans) CountDownLatch(java.util.concurrent.CountDownLatch) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Exceptions(io.crate.exceptions.Exceptions) Logger(org.apache.logging.log4j.Logger) RestStatus(org.elasticsearch.rest.RestStatus) ReplicationTracker(org.elasticsearch.index.seqno.ReplicationTracker) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) IndexCommit(org.apache.lucene.index.IndexCommit) StoreStats(org.elasticsearch.index.store.StoreStats) Tuple(io.crate.common.collections.Tuple) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) IndexModule(org.elasticsearch.index.IndexModule) CodecService(org.elasticsearch.index.codec.CodecService) ArrayList(java.util.ArrayList) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) XContentHelper(org.elasticsearch.common.xcontent.XContentHelper) RetentionLease(org.elasticsearch.index.seqno.RetentionLease) RetentionLeases(org.elasticsearch.index.seqno.RetentionLeases) IndexCache(org.elasticsearch.index.cache.IndexCache) Store(org.elasticsearch.index.store.Store) BiConsumer(java.util.function.BiConsumer) StreamSupport(java.util.stream.StreamSupport) IndicesService(org.elasticsearch.indices.IndicesService) TranslogConfig(org.elasticsearch.index.translog.TranslogConfig) Nullable(javax.annotation.Nullable) EngineException(org.elasticsearch.index.engine.EngineException) SourceToParse(org.elasticsearch.index.mapper.SourceToParse) AsyncIOProcessor(org.elasticsearch.common.util.concurrent.AsyncIOProcessor) SequenceNumbers(org.elasticsearch.index.seqno.SequenceNumbers) SetOnce(org.apache.lucene.util.SetOnce) IdFieldMapper(org.elasticsearch.index.mapper.IdFieldMapper) IndexService(org.elasticsearch.index.IndexService) IOUtils(io.crate.common.io.IOUtils) IOException(java.io.IOException) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) Segment(org.elasticsearch.index.engine.Segment) AtomicLong(java.util.concurrent.atomic.AtomicLong) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse) CounterMetric(org.elasticsearch.common.metrics.CounterMetric) ActionListener(org.elasticsearch.action.ActionListener) ElasticsearchException(org.elasticsearch.ElasticsearchException) SafeCommitInfo(org.elasticsearch.index.engine.SafeCommitInfo) TimeoutException(java.util.concurrent.TimeoutException) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) VersionType(org.elasticsearch.index.VersionType) StoreFileMetadata(org.elasticsearch.index.store.StoreFileMetadata) Settings(org.elasticsearch.common.settings.Settings) ResyncTask(org.elasticsearch.index.shard.PrimaryReplicaSyncer.ResyncTask) Locale(java.util.Locale) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ActionRunnable(org.elasticsearch.action.ActionRunnable) Releasable(org.elasticsearch.common.lease.Releasable) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) RefreshFailedEngineException(org.elasticsearch.index.engine.RefreshFailedEngineException) CheckIndex(org.apache.lucene.index.CheckIndex) UNASSIGNED_SEQ_NO(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) ReadOnlyEngine(org.elasticsearch.index.engine.ReadOnlyEngine) Engine(org.elasticsearch.index.engine.Engine) Objects(java.util.Objects) MapperService(org.elasticsearch.index.mapper.MapperService) TranslogStats(org.elasticsearch.index.translog.TranslogStats) List(java.util.List) Version(org.elasticsearch.Version) MeanMetric(org.elasticsearch.common.metrics.MeanMetric) RetentionLeaseStats(org.elasticsearch.index.seqno.RetentionLeaseStats) MappingMetadata(org.elasticsearch.cluster.metadata.MappingMetadata) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) RetentionLeaseSyncer(org.elasticsearch.index.seqno.RetentionLeaseSyncer) TimeValue(io.crate.common.unit.TimeValue) Optional(java.util.Optional) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) CommitStats(org.elasticsearch.index.engine.CommitStats) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CheckedConsumer(org.elasticsearch.common.CheckedConsumer) Index(org.elasticsearch.index.Index) Lucene(org.elasticsearch.common.lucene.Lucene) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) HashSet(java.util.HashSet) ForceMergeRequest(org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest) RootObjectMapper(org.elasticsearch.index.mapper.RootObjectMapper) MetadataSnapshot(org.elasticsearch.index.store.Store.MetadataSnapshot) IndexSettings(org.elasticsearch.index.IndexSettings) Mapping(org.elasticsearch.index.mapper.Mapping) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) PrintStream(java.io.PrintStream) Repository(org.elasticsearch.repositories.Repository) Uid(org.elasticsearch.index.mapper.Uid) RecoveryTarget(org.elasticsearch.indices.recovery.RecoveryTarget) EngineFactory(org.elasticsearch.index.engine.EngineFactory) IndexingMemoryController(org.elasticsearch.indices.IndexingMemoryController) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) Closeable(java.io.Closeable) Assertions(org.elasticsearch.Assertions) Translog(org.elasticsearch.index.translog.Translog) Collections(java.util.Collections) RunOnce(org.elasticsearch.common.util.concurrent.RunOnce) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats)

Aggregations

ObjectLongMap (com.carrotsearch.hppc.ObjectLongMap)3 Map (java.util.Map)2 ByteSizeValue (org.elasticsearch.common.unit.ByteSizeValue)2 ObjectLongHashMap (com.carrotsearch.hppc.ObjectLongHashMap)1 Booleans (io.crate.common.Booleans)1 Tuple (io.crate.common.collections.Tuple)1 IOUtils (io.crate.common.io.IOUtils)1 TimeValue (io.crate.common.unit.TimeValue)1 RowN (io.crate.data.RowN)1 Exceptions (io.crate.exceptions.Exceptions)1 TableIdent (io.crate.metadata.TableIdent)1 CrateUnitTest (io.crate.test.integration.CrateUnitTest)1 Closeable (java.io.Closeable)1 IOException (java.io.IOException)1 PrintStream (java.io.PrintStream)1 ClosedByInterruptException (java.nio.channels.ClosedByInterruptException)1 StandardCharsets (java.nio.charset.StandardCharsets)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 EnumSet (java.util.EnumSet)1