Skip to content

Commit c783a20

Browse files
committed
Handle negative free disk space in deciders (#48392)
Today it is possible that the total size of all relocating shards exceeds the total amount of free disk space. For instance, this may be caused by another user of the same disk increasing their disk usage, or may be due to how Elasticsearch double-counts relocations that are nearly complete particularly if there are many concurrent relocations in progress. The `DiskThresholdDecider` treats negative free space similarly to zero free space, but it then fails when rendering the messages that explain its decision. This commit fixes its handling of negative free space. Fixes #48380
1 parent 640d741 commit c783a20

File tree

3 files changed

+194
-47
lines changed

3 files changed

+194
-47
lines changed

server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java

+95-18
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@
1919

2020
package org.elasticsearch.cluster.routing.allocation.decider;
2121

22-
import java.util.Set;
23-
2422
import com.carrotsearch.hppc.cursors.ObjectCursor;
2523
import org.apache.logging.log4j.LogManager;
2624
import org.apache.logging.log4j.Logger;
@@ -44,6 +42,8 @@
4442
import org.elasticsearch.index.Index;
4543
import org.elasticsearch.index.shard.ShardId;
4644

45+
import java.util.Set;
46+
4747
import static org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING;
4848
import static org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING;
4949

@@ -139,12 +139,25 @@ public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, Routing
139139

140140
// subtractLeavingShards is passed as false here, because they still use disk space, and therefore should we should be extra careful
141141
// and take the size into account
142-
DiskUsage usage = getDiskUsage(node, allocation, usages, false);
142+
final DiskUsageWithRelocations usage = getDiskUsage(node, allocation, usages, false);
143143
// First, check that the node currently over the low watermark
144144
double freeDiskPercentage = usage.getFreeDiskAsPercentage();
145145
// Cache the used disk percentage for displaying disk percentages consistent with documentation
146146
double usedDiskPercentage = usage.getUsedDiskAsPercentage();
147147
long freeBytes = usage.getFreeBytes();
148+
if (freeBytes < 0L) {
149+
final long sizeOfRelocatingShards = sizeOfRelocatingShards(node, false, usage.getPath(),
150+
allocation.clusterInfo(), allocation.metaData(), allocation.routingTable());
151+
logger.debug("fewer free bytes remaining than the size of all incoming shards: " +
152+
"usage {} on node {} including {} bytes of relocations, preventing allocation",
153+
usage, node.nodeId(), sizeOfRelocatingShards);
154+
155+
return allocation.decision(Decision.NO, NAME,
156+
"the node has fewer free bytes remaining than the total size of all incoming shards: " +
157+
"free space [%sB], relocating shards [%sB]",
158+
freeBytes + sizeOfRelocatingShards, sizeOfRelocatingShards);
159+
}
160+
148161
ByteSizeValue freeBytesValue = new ByteSizeValue(freeBytes);
149162
if (logger.isTraceEnabled()) {
150163
logger.trace("node [{}] has {}% used disk", node.nodeId(), usedDiskPercentage);
@@ -242,6 +255,7 @@ public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, Routing
242255
// Secondly, check that allocating the shard to this node doesn't put it above the high watermark
243256
final long shardSize = getExpectedShardSize(shardRouting, 0L,
244257
allocation.clusterInfo(), allocation.metaData(), allocation.routingTable());
258+
assert shardSize >= 0 : shardSize;
245259
double freeSpaceAfterShard = freeDiskPercentageAfterShardAssigned(usage, shardSize);
246260
long freeBytesAfterShard = freeBytes - shardSize;
247261
if (freeBytesAfterShard < diskThresholdSettings.getFreeBytesThresholdHigh().getBytes()) {
@@ -268,6 +282,7 @@ public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, Routing
268282
diskThresholdSettings.getHighWatermarkRaw(), usedDiskThresholdHigh, freeSpaceAfterShard);
269283
}
270284

285+
assert freeBytesAfterShard >= 0 : freeBytesAfterShard;
271286
return allocation.decision(Decision.YES, NAME,
272287
"enough disk for shard on node, free: [%s], shard size: [%s], free after allocating shard: [%s]",
273288
freeBytesValue,
@@ -289,7 +304,7 @@ public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAl
289304

290305
// subtractLeavingShards is passed as true here, since this is only for shards remaining, we will *eventually* have enough disk
291306
// since shards are moving away. No new shards will be incoming since in canAllocate we pass false for this check.
292-
final DiskUsage usage = getDiskUsage(node, allocation, usages, true);
307+
final DiskUsageWithRelocations usage = getDiskUsage(node, allocation, usages, true);
293308
final String dataPath = clusterInfo.getDataPath(shardRouting);
294309
// If this node is already above the high threshold, the shard cannot remain (get it off!)
295310
final double freeDiskPercentage = usage.getFreeDiskAsPercentage();
@@ -301,6 +316,17 @@ public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAl
301316
return allocation.decision(Decision.YES, NAME,
302317
"this shard is not allocated on the most utilized disk and can remain");
303318
}
319+
if (freeBytes < 0L) {
320+
final long sizeOfRelocatingShards = sizeOfRelocatingShards(node, false, usage.getPath(),
321+
allocation.clusterInfo(), allocation.metaData(), allocation.routingTable());
322+
logger.debug("fewer free bytes remaining than the size of all incoming shards: " +
323+
"usage {} on node {} including {} bytes of relocations, shard cannot remain",
324+
usage, node.nodeId(), sizeOfRelocatingShards);
325+
return allocation.decision(Decision.NO, NAME,
326+
"the shard cannot remain on this node because the node has fewer free bytes remaining than the total size of all " +
327+
"incoming shards: free space [%s], relocating shards [%s]",
328+
freeBytes + sizeOfRelocatingShards, sizeOfRelocatingShards);
329+
}
304330
if (freeBytes < diskThresholdSettings.getFreeBytesThresholdHigh().getBytes()) {
305331
if (logger.isDebugEnabled()) {
306332
logger.debug("less than the required {} free bytes threshold ({} bytes free) on node {}, shard cannot remain",
@@ -330,8 +356,8 @@ public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAl
330356
"there is enough disk on this node for the shard to remain, free: [%s]", new ByteSizeValue(freeBytes));
331357
}
332358

333-
private DiskUsage getDiskUsage(RoutingNode node, RoutingAllocation allocation,
334-
ImmutableOpenMap<String, DiskUsage> usages, boolean subtractLeavingShards) {
359+
private DiskUsageWithRelocations getDiskUsage(RoutingNode node, RoutingAllocation allocation,
360+
ImmutableOpenMap<String, DiskUsage> usages, boolean subtractLeavingShards) {
335361
DiskUsage usage = usages.get(node.nodeId());
336362
if (usage == null) {
337363
// If there is no usage, and we have other nodes in the cluster,
@@ -343,18 +369,14 @@ private DiskUsage getDiskUsage(RoutingNode node, RoutingAllocation allocation,
343369
}
344370
}
345371

346-
if (diskThresholdSettings.includeRelocations()) {
347-
final long relocatingShardsSize = sizeOfRelocatingShards(node, subtractLeavingShards, usage.getPath(),
348-
allocation.clusterInfo(), allocation.metaData(), allocation.routingTable());
349-
DiskUsage usageIncludingRelocations = new DiskUsage(node.nodeId(), node.node().getName(), usage.getPath(),
350-
usage.getTotalBytes(), usage.getFreeBytes() - relocatingShardsSize);
351-
if (logger.isTraceEnabled()) {
352-
logger.trace("usage without relocations: {}", usage);
353-
logger.trace("usage with relocations: [{} bytes] {}", relocatingShardsSize, usageIncludingRelocations);
354-
}
355-
usage = usageIncludingRelocations;
372+
final DiskUsageWithRelocations diskUsageWithRelocations = new DiskUsageWithRelocations(usage,
373+
diskThresholdSettings.includeRelocations() ? sizeOfRelocatingShards(node, subtractLeavingShards, usage.getPath(),
374+
allocation.clusterInfo(), allocation.metaData(), allocation.routingTable()) : 0);
375+
if (logger.isTraceEnabled()) {
376+
logger.trace("getDiskUsage(subtractLeavingShards={}) returning {}", subtractLeavingShards, diskUsageWithRelocations);
356377
}
357-
return usage;
378+
379+
return diskUsageWithRelocations;
358380
}
359381

360382
/**
@@ -384,7 +406,7 @@ DiskUsage averageUsage(RoutingNode node, ImmutableOpenMap<String, DiskUsage> usa
384406
* @param shardSize Size in bytes of the shard
385407
* @return Percentage of free space after the shard is assigned to the node
386408
*/
387-
double freeDiskPercentageAfterShardAssigned(DiskUsage usage, Long shardSize) {
409+
double freeDiskPercentageAfterShardAssigned(DiskUsageWithRelocations usage, Long shardSize) {
388410
shardSize = (shardSize == null) ? 0 : shardSize;
389411
DiskUsage newUsage = new DiskUsage(usage.getNodeId(), usage.getNodeName(), usage.getPath(),
390412
usage.getTotalBytes(), usage.getFreeBytes() - shardSize);
@@ -452,4 +474,59 @@ public static long getExpectedShardSize(ShardRouting shard, long defaultValue, C
452474
return clusterInfo.getShardSize(shard, defaultValue);
453475
}
454476
}
477+
478+
static class DiskUsageWithRelocations {
479+
480+
private final DiskUsage diskUsage;
481+
private final long relocatingShardSize;
482+
483+
DiskUsageWithRelocations(DiskUsage diskUsage, long relocatingShardSize) {
484+
this.diskUsage = diskUsage;
485+
this.relocatingShardSize = relocatingShardSize;
486+
}
487+
488+
@Override
489+
public String toString() {
490+
return "DiskUsageWithRelocations{" +
491+
"diskUsage=" + diskUsage +
492+
", relocatingShardSize=" + relocatingShardSize +
493+
'}';
494+
}
495+
496+
double getFreeDiskAsPercentage() {
497+
if (getTotalBytes() == 0L) {
498+
return 100.0;
499+
}
500+
return 100.0 * ((double)getFreeBytes() / getTotalBytes());
501+
}
502+
503+
double getUsedDiskAsPercentage() {
504+
return 100.0 - getFreeDiskAsPercentage();
505+
}
506+
507+
long getFreeBytes() {
508+
try {
509+
return Math.subtractExact(diskUsage.getFreeBytes(), relocatingShardSize);
510+
} catch (ArithmeticException e) {
511+
return Long.MAX_VALUE;
512+
}
513+
}
514+
515+
String getPath() {
516+
return diskUsage.getPath();
517+
}
518+
519+
String getNodeId() {
520+
return diskUsage.getNodeId();
521+
}
522+
523+
String getNodeName() {
524+
return diskUsage.getNodeName();
525+
}
526+
527+
long getTotalBytes() {
528+
return diskUsage.getTotalBytes();
529+
}
530+
}
531+
455532
}

server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java

+69-29
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,15 @@
5656
import java.util.HashMap;
5757
import java.util.HashSet;
5858
import java.util.Map;
59+
import java.util.concurrent.atomic.AtomicReference;
5960

6061
import static java.util.Collections.emptyMap;
6162
import static java.util.Collections.singleton;
6263
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
6364
import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING;
6465
import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED;
6566
import static org.elasticsearch.cluster.routing.ShardRoutingState.UNASSIGNED;
67+
import static org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING;
6668
import static org.hamcrest.Matchers.containsString;
6769
import static org.hamcrest.Matchers.equalTo;
6870
import static org.hamcrest.Matchers.nullValue;
@@ -628,7 +630,8 @@ public void testFreeDiskPercentageAfterShardAssigned() {
628630
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 50)); // 50% used
629631
usages.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 0)); // 100% used
630632

631-
Double after = decider.freeDiskPercentageAfterShardAssigned(new DiskUsage("node2", "n2", "/dev/null", 100, 30), 11L);
633+
Double after = decider.freeDiskPercentageAfterShardAssigned(
634+
new DiskThresholdDecider.DiskUsageWithRelocations(new DiskUsage("node2", "n2", "/dev/null", 100, 30), 0L), 11L);
632635
assertThat(after, equalTo(19.0));
633636
}
634637

@@ -653,18 +656,19 @@ public void testShardRelocationsTakenIntoAccount() {
653656
final ClusterInfo clusterInfo = new DevNullClusterInfo(usages, usages, shardSizes);
654657

655658
DiskThresholdDecider decider = makeDecider(diskSettings);
659+
final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
656660
AllocationDeciders deciders = new AllocationDeciders(
657-
new HashSet<>(Arrays.asList(new SameShardAllocationDecider(
658-
Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)
659-
), decider)));
661+
new HashSet<>(Arrays.asList(
662+
new SameShardAllocationDecider(Settings.EMPTY, clusterSettings),
663+
new EnableAllocationDecider(
664+
Settings.builder().put(CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), "none").build(), clusterSettings),
665+
decider)));
660666

661-
ClusterInfoService cis = () -> {
662-
logger.info("--> calling fake getClusterInfo");
663-
return clusterInfo;
664-
};
667+
final AtomicReference<ClusterInfo> clusterInfoReference = new AtomicReference<>(clusterInfo);
668+
final ClusterInfoService cis = clusterInfoReference::get;
665669

666670
AllocationService strategy = new AllocationService(deciders, new TestGatewayAllocator(),
667-
new BalancedShardsAllocator(Settings.EMPTY), cis);
671+
new BalancedShardsAllocator(Settings.EMPTY), cis);
668672

669673
MetaData metaData = MetaData.builder()
670674
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1))
@@ -702,30 +706,66 @@ Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLU
702706
.add(newNode("node3"))
703707
).build();
704708

705-
AllocationCommand relocate1 = new MoveAllocationCommand("test", 0, "node2", "node3");
706-
AllocationCommands cmds = new AllocationCommands(relocate1);
709+
{
710+
AllocationCommand moveAllocationCommand = new MoveAllocationCommand("test", 0, "node2", "node3");
711+
AllocationCommands cmds = new AllocationCommands(moveAllocationCommand);
707712

708-
clusterState = strategy.reroute(clusterState, cmds, false, false).getClusterState();
709-
logShardStates(clusterState);
713+
clusterState = strategy.reroute(clusterState, cmds, false, false).getClusterState();
714+
logShardStates(clusterState);
715+
}
716+
717+
final ImmutableOpenMap.Builder<String, DiskUsage> overfullUsagesBuilder = ImmutableOpenMap.builder();
718+
overfullUsagesBuilder.put("node1", new DiskUsage("node1", "n1", "/dev/null", 100, 40)); // 60% used
719+
overfullUsagesBuilder.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 40)); // 60% used
720+
overfullUsagesBuilder.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 0)); // 100% used
721+
final ImmutableOpenMap<String, DiskUsage> overfullUsages = overfullUsagesBuilder.build();
722+
723+
final ImmutableOpenMap.Builder<String, Long> largerShardSizesBuilder = ImmutableOpenMap.builder();
724+
largerShardSizesBuilder.put("[test][0][p]", 14L);
725+
largerShardSizesBuilder.put("[test][0][r]", 14L);
726+
largerShardSizesBuilder.put("[test2][0][p]", 2L);
727+
largerShardSizesBuilder.put("[test2][0][r]", 2L);
728+
final ImmutableOpenMap<String, Long> largerShardSizes = largerShardSizesBuilder.build();
710729

711-
AllocationCommand relocate2 = new MoveAllocationCommand("test2", 0, "node2", "node3");
712-
cmds = new AllocationCommands(relocate2);
713-
714-
try {
715-
// The shard for the "test" index is already being relocated to
716-
// node3, which will put it over the low watermark when it
717-
// completes, with shard relocations taken into account this should
718-
// throw an exception about not being able to complete
719-
strategy.reroute(clusterState, cmds, false, false);
720-
fail("should not have been able to reroute the shard");
721-
} catch (IllegalArgumentException e) {
722-
assertThat("can't be allocated because there isn't enough room: " + e.getMessage(),
723-
e.getMessage(),
724-
containsString("the node is above the low watermark cluster setting " +
725-
"[cluster.routing.allocation.disk.watermark.low=0.7], using more disk space than the maximum " +
726-
"allowed [70.0%], actual free: [26.0%]"));
730+
final ClusterInfo overfullClusterInfo = new DevNullClusterInfo(overfullUsages, overfullUsages, largerShardSizes);
731+
732+
{
733+
AllocationCommand moveAllocationCommand = new MoveAllocationCommand("test2", 0, "node2", "node3");
734+
AllocationCommands cmds = new AllocationCommands(moveAllocationCommand);
735+
736+
final ClusterState clusterStateThatRejectsCommands = clusterState;
737+
738+
assertThat(expectThrows(IllegalArgumentException.class,
739+
() -> strategy.reroute(clusterStateThatRejectsCommands, cmds, false, false)).getMessage(),
740+
containsString("the node is above the low watermark cluster setting " +
741+
"[cluster.routing.allocation.disk.watermark.low=0.7], using more disk space than the maximum " +
742+
"allowed [70.0%], actual free: [26.0%]"));
743+
744+
clusterInfoReference.set(overfullClusterInfo);
745+
746+
assertThat(expectThrows(IllegalArgumentException.class,
747+
() -> strategy.reroute(clusterStateThatRejectsCommands, cmds, false, false)).getMessage(),
748+
containsString("the node has fewer free bytes remaining than the total size of all incoming shards"));
749+
750+
clusterInfoReference.set(clusterInfo);
727751
}
728752

753+
{
754+
AllocationCommand moveAllocationCommand = new MoveAllocationCommand("test2", 0, "node2", "node3");
755+
AllocationCommands cmds = new AllocationCommands(moveAllocationCommand);
756+
757+
logger.info("--> before starting: {}", clusterState);
758+
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
759+
logger.info("--> after starting: {}", clusterState);
760+
clusterState = strategy.reroute(clusterState, cmds, false, false).getClusterState();
761+
logger.info("--> after running another command: {}", clusterState);
762+
logShardStates(clusterState);
763+
764+
clusterInfoReference.set(overfullClusterInfo);
765+
766+
clusterState = strategy.reroute(clusterState, "foo");
767+
logger.info("--> after another reroute: {}", clusterState);
768+
}
729769
}
730770

731771
public void testCanRemainWithShardRelocatingAway() {

0 commit comments

Comments
 (0)