Friday, August 26, 2011

Easy to monitor CPU, memory, disk, and network states using SIGAR

  1. Firstly, download the SIGAR API (e.g., hyperic-sigar-1.6.4.zip) from http://support.hyperic.com/display/SIGAR/Home
  2. After unzipping hyperic-sigar-1.6.4, you can find two required folders (i.e., include and lib).
  3. You have to put these folders into your workspace, and import these jar files. 
    • the lib folder and include folder should be put in the same level (e.g., workspace/projectName/). 
  4. Use the following simple code, you can get system performance: 
import org.hyperic.sigar.Cpu;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.NetStat;
import org.hyperic.sigar.Sigar;

public class PerformanceMonitor {

    private static Sigar sigar = new Sigar();

    public PerformanceMonitor() {
    }
    public static void main(String[] args) throws Exception {

        // For Disk
        System.out.println("-----Disk Info-----");
        FileSystem fileSystemList[] = sigar.getFileSystemList();
        for (int f = 0; f < fileSystemList.length; f++) {
            String devName = fileSystemList[f].getDevName();
            int devType = fileSystemList[f].getType();
            //Only get the physical disk
            if (devType == FileSystem.TYPE_LOCAL_DISK) {
                System.out.println("Disk " + devName);
                System.out.println(sigar.getDirUsage(devName));
                System.out.println(sigar.getDiskUsage(devName));
                System.out.println(sigar.getFileSystemUsage(devName));
            }
        }

        // For CPU
        System.out.println("-----CPU Info-----");
        System.out.println(sigar.getCpuPerc());
        System.out.println(sigar.getCpu());
        CpuInfo cpuInfoList[] = sigar.getCpuInfoList();
        Cpu cpuList[] = sigar.getCpuList();
        for (int c = 0; c < cpuInfoList.length; c++) {
            System.out.println("CPU " + c);
            System.out.println(cpuInfoList[c].toString());
            System.out.println(cpuList[c].toString());
        }

        // For Memory
        System.out.println("-----Memory Info-----");
        System.out.println(sigar.getMem());

        // For Network
        System.out.println("-----Network Info-----");
        System.out.println(sigar.getNetInfo());
        NetStat thisNetState = sigar.getNetStat();
        System.out.println("in-bound " + thisNetState.getAllInboundTotal()
                + " out-bound " + thisNetState.getAllOutboundTotal());
    }
}


1 comment: