Skip to content

Instantly share code, notes, and snippets.

@frjufvjn
Last active August 19, 2020 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frjufvjn/b3f52a3d90db8555d5357fb5db9772b3 to your computer and use it in GitHub Desktop.
Save frjufvjn/b3f52a3d90db8555d5357fb5db9772b3 to your computer and use it in GitHub Desktop.
Linx free command In Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author PJW
* @see - 리눅스 장비에서 free 명령어 호출을 통해 메모리 정보를 도출한다.
*/
public class TcagntTest {
public static void main(String[] args) {
new TcagntTest().getInfoMemory();
}
/*------------------------------------------------------------------------------------------------
* type 1
total used free shared buffers cached
Mem: 8047828 3509936 4537892 35384 886380 1268628
-/+ buffers/cache: 1354928 6692900
Swap: 8260604 0 8260604
type 2
total used free shared buff/cache available
Mem: 16688792 8310040 8149400 17720 229352 8245020
Swap: 50331648 110664 50220984
------------------------------------------------------------------------------------------------*/
// AS-IS 코드에 정의된 SEND할때 필요한 맵
private Map<String,Object> hsmHwInfo = new HashMap<>();
// 명령어 반환 결과중 각 결과값 열의 위치를 지정 선언
private static Map<String, String> typeOneMap = new HashMap<>();
private static Map<String, String> typeTwoMap = new HashMap<>();
public TcagntTest() {
typeOneMap.put("11", "memoryTotal");
typeOneMap.put("13", "memoryFree");
typeOneMap.put("12", "memoryUsed");
typeOneMap.put("15", "memoryBuffers");
typeOneMap.put("16", "memoryCached");
typeOneMap.put("31", "swapTotal");
typeOneMap.put("33", "swapFree");
typeTwoMap.put("11", "memoryTotal");
typeTwoMap.put("13", "memoryFree");
typeTwoMap.put("16", "memoryAvailable");
typeTwoMap.put("21", "swapTotal");
typeTwoMap.put("23", "swapFree");
}
public void getInfoMemory() {
long start = System.currentTimeMillis();
String type = "1";
String cmd = "free";
List<String> arguments = new ArrayList<String>();
arguments.add(0, cmd);
System.out.println("Command arguments: {}"+ arguments);
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectErrorStream(true);
Process process = null;
// IOException errorDuringExecution = null;
BufferedReader reader = null;
try {
process = processBuilder.start();
process.waitFor();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
// hsmHwInfo.clear();
int lineNo = 0;
String line;
if (process.exitValue() != 0) {
while ((line = reader.readLine()) != null) {
System.out.println("[process.exitValue != 0 ] " + line);
lineNo++;
}
}
else {
// 정상케이스
while ((line = reader.readLine()) != null) {
System.out.println("[process.exitValue == 0 ] " + line);
// 칼럼이 노출되는 첫번째 행에서 타입을 구분해내도록 처리
if ( lineNo == 0 && line.indexOf("available") != -1 ) {
type = "2";
}
String[] splited = line.split(" ");
// typeXXXMap에 정의된 위치에 따라서 필요한 값을 추출
int colPosition = 0;
for (int i=0; i<splited.length; i++) {
if ( !"".equals(splited[i]) ) {
String posKey = String.valueOf(lineNo) + String.valueOf(colPosition);
if ( "2".equals(type) ) {
if (typeTwoMap.containsKey(posKey)) {
System.out.println("pos:" + colPosition + " value: " + splited[i]
+ " item: " + typeTwoMap.get(posKey));
hsmHwInfo.put(typeTwoMap.get(posKey), splited[i]);
}
} else {
if (typeOneMap.containsKey(posKey)) {
System.out.println("pos:" + colPosition + " value: " + splited[i]
+ " item: " + typeOneMap.get(posKey));
hsmHwInfo.put(typeOneMap.get(posKey), splited[i]);
}
}
colPosition++;
}
}
lineNo++;
}
/**
* @see - 위에서 추출된 요소들을 모아서 결과값을 담는다.
* */
this.setResponse(type);
}
System.out.println("type : " + type);
} catch (IOException e) {
// errorDuringExecution = e;
System.err.println("Error while running command. IOException \n"+ e.getMessage());
} catch (InterruptedException e) {
System.err.println("Error while running command. InterruptedException \n"+ e.getMessage());
Thread.currentThread().interrupt();
} finally {
arguments.clear();
if (process != null) {
System.out.println("process destroy.....");
process.destroy();
process = null;
}
if(reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
System.err.println("Error while reader close. IOException \n"+ e.getMessage());
}
}
System.out.println("elapsed : " + (System.currentTimeMillis() - start) + "ms");
/*if (errorDuringExecution != null) {
throw errorDuringExecution;
}*/
}
}
/**
* @param type
* @see - 위에서 추출된 요소들을 모아서 사용률 값을 계산하고 결과값을 담는다.
*/
private void setResponse(String type) {
System.out.println("Final Memory Result -------------------------------------------------");
Set<String> keys = hsmHwInfo.keySet();
for (String key : keys) {
System.out.println("key:"+key + " value:"+ hsmHwInfo.get(key));
}
Double memoryUsage = 0.0;
if ("2".equals(type)) {
Double _tot = Double.valueOf(hsmHwInfo.get("memoryTotal").toString());
Double _avail = Double.valueOf(hsmHwInfo.get("memoryAvailable").toString());
memoryUsage = Math.floor((_tot - _avail) / _tot * 1000) / 10;
} else {
// (used-buffers-cached)/total
Double _used = Double.valueOf(hsmHwInfo.get("memoryUsed").toString());
Double _buffers = Double.valueOf(hsmHwInfo.get("memoryBuffers").toString());
Double _cached = Double.valueOf(hsmHwInfo.get("memoryCached").toString());
Double _total = Double.valueOf(hsmHwInfo.get("memoryTotal").toString());
memoryUsage = Math.floor((_used - _buffers - _cached) / _total * 1000) / 10;
}
Double swapUsage = 0.0;
Double _swapTot = Double.valueOf(hsmHwInfo.get("swapTotal").toString());
Double _swapFree = Double.valueOf(hsmHwInfo.get("swapFree").toString());
swapUsage = Math.floor((_swapTot - _swapFree) / _swapTot * 1000) / 10;
System.out.println("memoryUsage --> " + memoryUsage);
System.out.println("swapUsage --> " + swapUsage);
hsmHwInfo.put("memoryUsage", memoryUsage);
hsmHwInfo.put("swapUsage", swapUsage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment