forked from opensearch-project/OpenSearch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualShardRoutingHelper.java
More file actions
66 lines (54 loc) · 2.41 KB
/
VirtualShardRoutingHelper.java
File metadata and controls
66 lines (54 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
package org.opensearch.cluster.metadata;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.common.annotation.PublicApi;
import java.util.Map;
/**
* Resolves virtual shard routing to physical shard IDs.
*/
@PublicApi(since = "3.6.0")
public final class VirtualShardRoutingHelper {
private VirtualShardRoutingHelper() {}
private static final Logger logger = LogManager.getLogger(VirtualShardRoutingHelper.class);
/**
* Custom Metadata key for storing virtual shard routing overrides.
*/
public static final String VIRTUAL_SHARDS_CUSTOM_METADATA_KEY = "virtual_shards_routing";
/**
* Resolves the physical shard for a virtual shard id.
*/
public static int resolvePhysicalShardId(IndexMetadata indexMetadata, int vShardId) {
int numVirtualShards = indexMetadata.getNumberOfVirtualShards();
int numPhysicalShards = indexMetadata.getNumberOfShards();
if (numVirtualShards < numPhysicalShards || numVirtualShards % numPhysicalShards != 0) {
throw new IllegalArgumentException(
"Virtual shards must be enabled and be a multiple of the number of physical shards to resolve routing."
);
}
vShardId = Math.floorMod(vShardId, numVirtualShards);
Map<String, String> overrides = indexMetadata.getCustomData(VIRTUAL_SHARDS_CUSTOM_METADATA_KEY);
if (overrides != null) {
String pShardIdStr = overrides.get(String.valueOf(vShardId));
if (pShardIdStr != null) {
try {
int pShardId = Integer.parseInt(pShardIdStr);
if (pShardId >= 0 && pShardId < numPhysicalShards) {
return pShardId;
}
logger.trace("Invalid override value [{}] for vShard [{}]: out of bounds", pShardId, vShardId);
} catch (NumberFormatException e) {
logger.trace("Invalid override value [{}] for vShard [{}]: not a number", pShardIdStr, vShardId);
}
}
}
int virtualShardsPerPhysical = numVirtualShards / numPhysicalShards;
return vShardId / virtualShardsPerPhysical;
}
}