Skip to content

Commit d9e5581

Browse files
committed
Return 0 for negative "free" and "total" memory reported by the OS
We've had a situation where the MX bean reported negative values for the free memory of the OS, in those rare cases we want to return a value of 0 rather than blowing up later down the pipeline. In the event that there is a serialization or creation error with regard to memory use, this adds asserts so the failure will occur as soon as possible and give us a better location for investigation. Resolves elastic#42157
1 parent 37835ca commit d9e5581

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

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

+12-2
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,12 @@ public long getFreePhysicalMemorySize() {
7070
return -1;
7171
}
7272
try {
73-
return (long) getFreePhysicalMemorySize.invoke(osMxBean);
73+
final long freeMem = (long) getFreePhysicalMemorySize.invoke(osMxBean);
74+
if (freeMem < 0) {
75+
logger.warn("OS reported a negative free memory value [{}]", freeMem);
76+
return 0;
77+
}
78+
return freeMem;
7479
} catch (Exception e) {
7580
return -1;
7681
}
@@ -84,7 +89,12 @@ public long getTotalPhysicalMemorySize() {
8489
return -1;
8590
}
8691
try {
87-
return (long) getTotalPhysicalMemorySize.invoke(osMxBean);
92+
final long totalMem = (long) getTotalPhysicalMemorySize.invoke(osMxBean);
93+
if (totalMem < 0) {
94+
logger.warn("OS reported a negative total memory value [{}]", totalMem);
95+
return 0;
96+
}
97+
return totalMem;
8898
} catch (Exception e) {
8999
return -1;
90100
}

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

+4
Original file line numberDiff line numberDiff line change
@@ -228,13 +228,17 @@ public static class Mem implements Writeable, ToXContentFragment {
228228
private final long free;
229229

230230
public Mem(long total, long free) {
231+
assert total >= 0 : "expected total memory to be positive, got: " + total;
232+
assert free >= 0 : "expected free memory to be positive, got: " + total;
231233
this.total = total;
232234
this.free = free;
233235
}
234236

235237
public Mem(StreamInput in) throws IOException {
236238
this.total = in.readLong();
239+
assert total >= 0 : "expected total memory to be positive, got: " + total;
237240
this.free = in.readLong();
241+
assert free >= 0 : "expected free memory to be positive, got: " + total;
238242
}
239243

240244
@Override

0 commit comments

Comments
 (0)