Skip to content

Commit a64c322

Browse files
authored
Report used memory as zero when total memory cannot be obtained (#56435)
1 parent 1244018 commit a64c322

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

server/src/main/java/org/elasticsearch/monitor/os/OsStats.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
package org.elasticsearch.monitor.os;
2121

22+
import org.apache.logging.log4j.LogManager;
23+
import org.apache.logging.log4j.Logger;
2224
import org.elasticsearch.common.io.stream.StreamInput;
2325
import org.elasticsearch.common.io.stream.StreamOutput;
2426
import org.elasticsearch.common.io.stream.Writeable;
@@ -224,6 +226,8 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws
224226

225227
public static class Mem implements Writeable, ToXContentFragment {
226228

229+
private static final Logger logger = LogManager.getLogger(Mem.class);
230+
227231
private final long total;
228232
private final long free;
229233

@@ -252,6 +256,16 @@ public ByteSizeValue getTotal() {
252256
}
253257

254258
public ByteSizeValue getUsed() {
259+
if (total == 0) {
260+
// The work in https://github.com/elastic/elasticsearch/pull/42725 established that total memory
261+
// can be reported as negative in some cases. In those cases, we force it to zero in which case
262+
// we can no longer correctly report the used memory as (total-free) and should report it as zero.
263+
//
264+
// We intentionally check for (total == 0) rather than (total - free < 0) so as not to hide
265+
// cases where (free > total) which would be a different bug.
266+
logger.warn("cannot compute used memory when total memory is 0 and free memory is " + free);
267+
return new ByteSizeValue(0);
268+
}
255269
return new ByteSizeValue(total - free);
256270
}
257271

server/src/test/java/org/elasticsearch/monitor/os/OsStatsTests.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525

2626
import java.io.IOException;
2727

28+
import static org.hamcrest.Matchers.equalTo;
29+
2830
public class OsStatsTests extends ESTestCase {
2931

3032
public void testSerialization() throws IOException {
@@ -81,4 +83,9 @@ public void testSerialization() throws IOException {
8183
}
8284
}
8385

86+
public void testGetUsedMemoryWithZeroTotal() {
87+
OsStats.Mem mem = new OsStats.Mem(0, 1);
88+
assertThat(mem.getUsed().getBytes(), equalTo(0L));
89+
}
90+
8491
}

0 commit comments

Comments
 (0)