1 17 package org.apache.activemq.tool.sampler.plugins; 18 19 import java.util.concurrent.atomic.AtomicBoolean ; 20 21 import java.io.BufferedReader ; 22 import java.io.InputStreamReader ; 23 import java.io.IOException ; 24 import java.util.StringTokenizer ; 25 26 public class LinuxCpuSamplerPlugin implements CpuSamplerPlugin, Runnable { 27 28 private Process vmstatProcess; 29 private String vmstat; 30 private String result = ""; 31 private final Object mutex = new Object (); 32 private AtomicBoolean stop = new AtomicBoolean (false); 33 34 public LinuxCpuSamplerPlugin(long intervalInMs) { 35 vmstat = "vmstat -n " + (int)(intervalInMs / 1000); 36 } 37 38 public void start() { 39 stop.set(false); 40 Thread t = new Thread (this); 41 t.start(); 42 } 43 44 public void stop() { 45 stop.set(true); 46 try { 47 vmstatProcess.waitFor(); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 } 52 53 public void run() { 54 55 try { 56 vmstatProcess = Runtime.getRuntime().exec(vmstat); 57 BufferedReader br = new BufferedReader (new InputStreamReader (vmstatProcess.getInputStream()), 1024); 58 59 br.readLine(); 61 String header = br.readLine(); 62 String data; 63 64 while (!stop.get()) { 65 data = br.readLine(); 66 if (data != null) { 67 String csvData = convertToCSV(header, data); 68 synchronized (mutex) { 69 result = csvData; 70 } 71 } 72 } 73 br.close(); 74 vmstatProcess.destroy(); 75 76 } catch (IOException ioe) { 77 ioe.printStackTrace(); 78 } 79 } 80 81 public String getCpuUtilizationStats() { 82 String data; 83 synchronized (mutex) { 84 data = result; 85 result = ""; 86 } 87 return data; 88 } 89 90 public String getVmstat() { 91 return vmstat; 92 } 93 94 public void setVmstat(String vmstat) { 95 this.vmstat = vmstat; 96 } 97 98 protected String convertToCSV(String header, String data) { 99 StringTokenizer headerTokens = new StringTokenizer (header, " "); 100 StringTokenizer dataTokens = new StringTokenizer (data, " "); 101 102 String csv = ""; 103 while (headerTokens.hasMoreTokens()) { 104 csv += (headerTokens.nextToken() + "=" + dataTokens.nextToken() + ","); 105 } 106 107 return csv; 108 } 109 } 110 | Popular Tags |