Skip to content

Commit 9042d23

Browse files
committed
Report used memory as zero when total memory cannot be obtained (elastic#56412)
1 parent 8c1a535 commit 9042d23

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

+14
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.Version;
2325
import org.elasticsearch.common.io.stream.StreamInput;
2426
import org.elasticsearch.common.io.stream.StreamOutput;
@@ -225,6 +227,8 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws
225227

226228
public static class Mem implements Writeable, ToXContentFragment {
227229

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

@@ -253,6 +257,16 @@ public ByteSizeValue getTotal() {
253257
}
254258

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

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

+7
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)