Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-read from start if a read from proc doesn't fill the buffer #4716

Merged
merged 3 commits into from
Oct 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 15 additions & 16 deletions Stats/src/main/java/io/deephaven/stats/StatsCPUCollector.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
package io.deephaven.stats;

import io.deephaven.base.verify.Assert;
import io.deephaven.configuration.Configuration;
import io.deephaven.internal.log.LoggerFactory;
import io.deephaven.io.logger.Logger;
Expand Down Expand Up @@ -223,29 +224,27 @@ private boolean peekNextLong() {
*/
private void readToBuffer(FileChannel fileChannel, String fileName) throws IOException {
statBuffer.clear();
int nb = 0;
fileChannel.position(0);

// Filesystem entries in /proc can only be read all at once to avoid races, so using too big of a buffer isn't a
// problem, but too small is. Attempt to read with the current buffer. If we filled the buffer we resize it and
// read again from start.
while (true) {
final int thisNb = fileChannel.read(statBuffer);
final int nb = fileChannel.read(statBuffer);
rcaudy marked this conversation as resolved.
Show resolved Hide resolved

if (thisNb == -1) {
break;
if (nb <= 0) {
// zero bytes read is an error, -1 is EOF
throw new IOException(fileName + " could not be read, or was empty");
}
nb += thisNb;
if (!statBuffer.hasRemaining()) {
// allocate larger read-buffer, and continue reading
ByteBuffer resized = ByteBuffer.allocate(statBuffer.capacity() * 2);
resized.put(statBuffer.flip());
statBuffer = resized;
if (statBuffer.hasRemaining()) {
Assert.eq(statBuffer.position(), "statBuffer.position()", nb, "nb");
statBuffer.flip();
return;
}
}

if (nb == 0) {
throw new IOException(fileName + " zero read");
} else {
// Success, set position and limit to the data read
statBuffer.flip();
// allocate larger read-buffer, and read again from start
statBuffer = ByteBuffer.allocate(statBuffer.capacity() * 2);
fileChannel.position(0);
}
}

Expand Down
Loading