agent: Use FileInputStream for reading files instead of cat

Cat'ing a file and parsing that output is not reliable and this can be done
by using Java's native methods for that.
This commit is contained in:
Wido den Hollander 2013-02-01 15:01:52 +01:00
parent c9e764818b
commit 4709756bd5

View File

@ -4592,19 +4592,43 @@ ServerResource {
private Pair<Double, Double> getNicStats(String nicName) { private Pair<Double, Double> getNicStats(String nicName) {
double rx = 0.0; double rx = 0.0;
OutputInterpreter.OneLineParser rxParser = new OutputInterpreter.OneLineParser(); File rxFile = new File("/sys/class/net/" + nicName + "/statistics/rx_bytes");
String result = executeBashScript("cat /sys/class/net/" + nicName try {
+ "/statistics/rx_bytes", rxParser); FileInputStream rxStream = new FileInputStream(rxFile);
if (result == null && rxParser.getLine() != null) { StringBuffer rxContent = new StringBuffer("");
rx = Double.parseDouble(rxParser.getLine()); byte[] rxBuffer = new byte[1024];
int rxLength;
while ((rxLength = rxStream.read(rxBuffer)) != -1) {
rxContent.append(new String(rxBuffer));
}
rx = Double.parseDouble(rxContent.toString());
} catch (final FileNotFoundException e) {
throw new CloudRuntimeException("Cannot find the file: "
+ rxFile.getAbsolutePath(), e);
} catch (final IOException e) {
throw new CloudRuntimeException("IOException in reading "
+ rxFile.getAbsolutePath(), e);
} }
double tx = 0.0; double tx = 0.0;
OutputInterpreter.OneLineParser txParser = new OutputInterpreter.OneLineParser(); File txFile = new File("/sys/class/net/" + nicName + "/statistics/tx_bytes");
result = executeBashScript("cat /sys/class/net/" + nicName try {
+ "/statistics/tx_bytes", txParser); FileInputStream txStream = new FileInputStream(txFile);
if (result == null && txParser.getLine() != null) { StringBuffer txContent = new StringBuffer("");
tx = Double.parseDouble(txParser.getLine()); byte[] txBuffer = new byte[1024];
int txLength;
while((txLength = txStream.read(txBuffer)) != -1) {
txContent.append(new String(txBuffer));
}
tx = Double.parseDouble(txContent.toString());
} catch (final FileNotFoundException e) {
throw new CloudRuntimeException("Cannot find the file: "
+ txFile.getAbsolutePath(), e);
} catch (final IOException e) {
throw new CloudRuntimeException("IOException in reading "
+ txFile.getAbsolutePath(), e);
} }
return new Pair<Double, Double>(rx, tx); return new Pair<Double, Double>(rx, tx);