Report used memory as zero when total memory cannot be obtained (#56412)

This commit is contained in:
Dan Hermann 2020-05-12 07:43:51 -05:00 committed by GitHub
parent a9425a0240
commit dfdd7e4fce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -19,6 +19,8 @@
package org.elasticsearch.monitor.os;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
@ -225,6 +227,8 @@ public class OsStats implements Writeable, ToXContentFragment {
public static class Mem implements Writeable, ToXContentFragment {
private static final Logger logger = LogManager.getLogger(Mem.class);
private final long total;
private final long free;
@ -253,6 +257,16 @@ public class OsStats implements Writeable, ToXContentFragment {
}
public ByteSizeValue getUsed() {
if (total == 0) {
// The work in https://github.com/elastic/elasticsearch/pull/42725 established that total memory
// can be reported as negative in some cases. In those cases, we force it to zero in which case
// we can no longer correctly report the used memory as (total-free) and should report it as zero.
//
// We intentionally check for (total == 0) rather than (total - free < 0) so as not to hide
// cases where (free > total) which would be a different bug.
logger.warn("cannot compute used memory when total memory is 0 and free memory is " + free);
return new ByteSizeValue(0);
}
return new ByteSizeValue(total - free);
}

View File

@ -25,6 +25,8 @@ import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
public class OsStatsTests extends ESTestCase {
public void testSerialization() throws IOException {
@ -81,4 +83,9 @@ public class OsStatsTests extends ESTestCase {
}
}
public void testGetUsedMemoryWithZeroTotal() {
OsStats.Mem mem = new OsStats.Mem(0, 1);
assertThat(mem.getUsed().getBytes(), equalTo(0L));
}
}