HQ sigar 使用介绍

Hyperic HQ是一个开源(GPL授权)IT资源管理平台。
Hyperic HQ
可以监控和管理:

· 操作系统:AIXHP/UXLinuxSolarisWindowsMac OSXFreeBSD

· Web服务器:ApacheMicrosoft IISSun ONE Web Server

· 应用服务器:BEA WebLogicIBM WebSphereJBossApache GeronimoMacromedia ColdFusionMacromedia JRunMicrosoft .NET RuntimeNovell SilverstreamTomcatCaucho Resin

· 数据库:IBM DB2Microsoft SQL ServerMySQLOraclePostgreSQLSybase Adaptive Server

· 消息中间件: ActiveMQWeblogic MQ

· 微软的产品: MS ExchangeMS ActiveDirectory.NET

· 虚拟产品: VMWareCitrix Metaframe

· 应用平台: LAMPLAM-JJ2EEMX4J

· 其他:网络设备交换机,路由器,网络服务等。 

Hq的通过本地方法来调用操作系统API

Hyperic-Sigar是一个收集系统各项底层信息的工具集.他有如下特点:
1. 收集信息全面
收集CPU,MEM,NETWORK,PROCESS,IOSTAT等
使用Sigar,你完全可以模仿出cpuinfo,meminfo,top,free,ifconfig,ipconfig,netstat,route,df,du,ps,ls等多种unix平台和windows平台的指令.
2.跨平台,支持多数平台
支持的平台包括:windows系列(32系列,IA64系列,AMD64系列),linux系列,freeBsd系列,HPUnix 系列,Sun solaris/Sparc/Sparc64系列,macOs系列,AIX系列等
3.提供的API接口全面
sigar本身由C语言开发而成,提供了丰富的API接口,包括:JAVA,.NET,PERL,PHP,PYTHON,RUBY


 

  • 通过JAVA API接口调用Sigar,获取系统信息的例子

1.先确定基本Sigar库
Sigar JAVA编程只是JAVA API编程,需要调用Sigar的基本库,因此需要把Sigar基本库放在对应的ClassPath下
注意:Sigar为不同平台提供了不同的库文件.典型的:
windows平台:sigar-x86-winnt.dll
linux平台:libsigar-x86-linux.so或
solaris平台: libsigar-x86-solaris.so或libsigar-sparc-solaris.so或libsigar-sparc64-solaris.so
64位平台:分为至强的libsigar-ia64-linux.so和AMD的libsigar-amd64-linux.so,sigar-amd64-winnt.dll

2. 程序代码

public class SystemInfo {
   
    private Sigar sigar ;
   
    private SigarProxy proxy;
   
    private StringBuilder info = new StringBuilder();

    private void sigarInit(boolean isProxy) {
        sigar = new Sigar();
        if(isProxy)
            proxy = SigarProxyCache.newInstance(this.sigar);
    }
   
    private void shutdown() {
        this.sigar.close();
    }
   

   
    public String getInfo() {
        return info.toString();
    }

    public void clearInfo() {
        if ( null != info )
            info.delete(0,info.length());
    }

    private void println(String arg){
        info.append(arg+"\n");
    }
   
    public String sprintf(String format, Object[] items) {
        return new PrintfFormat(format).sprintf(items);
    }

    public void printf(String format, Object[] items) {
        println(sprintf(format, items));
    }
    
    public void cpuInfo() {
        clearInfo();
        println("============Current system Cpu information================");

        try {
           
            sigarInit(false);
           
            org.hyperic.sigar.CpuInfo[] infos =
                this.sigar.getCpuInfoList();

            CpuPerc[] cpus =
                this.sigar.getCpuPercList();

            org.hyperic.sigar.CpuInfo info = infos[0];
            long cacheSize = info.getCacheSize();
            println("Vendor........." + info.getVendor());
            println("Model.........." + info.getModel());
            println("Mhz............" + info.getMhz());
            println("Total CPUs....." + info.getTotalCores());
            println("Physical CPUs.." + info.getTotalSockets());
            println("Cores per CPU.." + info.getCoresPerSocket());


            if (cacheSize != Sigar.FIELD_NOTIMPL) {
                println("Cache size...." + cacheSize);
            }
            println("");

            for (int i=0; i<cpus.length; i++) {
                println("CPU " + i + ".........");
                outputCpuPerc(cpus[i]);
            }

            println("Totals........");
            outputCpuPerc(this.sigar.getCpuPerc());
        } catch (SigarException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            shutdown();
        }
    }   

    private void outputCpuPerc(CpuPerc cpu) {
        println("User Time....." + CpuPerc.format(cpu.getUser()));
        println("Sys Time......" + CpuPerc.format(cpu.getSys()));
        println("Idle Time....." + CpuPerc.format(cpu.getIdle()));
        println("Wait Time....." + CpuPerc.format(cpu.getWait()));
        println("Nice Time....." + CpuPerc.format(cpu.getNice()));
        println("Combined......" + CpuPerc.format(cpu.getCombined()));
        println("Irq Time......" + CpuPerc.format(cpu.getIrq()));
        if (SigarLoader.IS_LINUX) {
            println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq()));
            println("Stolen Time...." + CpuPerc.format(cpu.getStolen()));
        }
        println("");
    }
    private static Long format(long value) {
        return new Long(value / 1024);
    }
   
    public void memInfo() throws SigarException {
        clearInfo();
        println("============Display information about free and used memory================");
       
        try {
            sigarInit(false);
           
            Mem mem   = this.sigar.getMem();
            Swap swap = this.sigar.getSwap();

            Object[] header = new Object[] { "total", "used", "free" };
            printf("s s s", header);
           
            Object[] memRow = new Object[] {
                format(mem.getTotal()),
                format(mem.getUsed()),
                format(mem.getFree())
            };
            printf("Mem:    ldK ldK ldK", memRow);
           
            Object[] memPercent = new Object[3];
            memPercent[0] = "100%";
            double   d   =   mem.getUsedPercent(); 
            d=((int)(d*100))/100;         // 取小数点后两位的简便方法
            memPercent[1] = d + "%";
            d   =   mem.getFreePercent(); 
            d=((int)(d*100))/100;
            memPercent[2] = d + "%";      // 取小数点后两位的简便方法
            printf("MemPer:    ls ls ls", memPercent);
               
            //e.g. linux
            Object[] actualRow = new Object[] {
                format(mem.getActualUsed()),
                format(mem.getActualFree())
            };
            if ((mem.getUsed() != mem.getActualUsed()) ||
                (mem.getFree() != mem.getActualFree()))
            {
                printf("-/+ buffers/cache: " + "ldK dK", actualRow);
            }

            Object[] swapRow = new Object[] {
                format(swap.getTotal()),
                format(swap.getUsed()),
                format(swap.getFree())
            };
            printf("Swap:   ldK ldK ldK", swapRow);
           
            printf("RAM:    ldM", new Object[] { mem.getRam()});
           

        } catch (RuntimeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            shutdown();
        }
    }
   public void dfInfo() throws SigarException {
           clearInfo();
        println("============Report filesystem disk space usage===============");

        try {
                sigarInit(true);
                FileSystem[] fslist = this.proxy.getFileSystemList();
                String[] HEADER = new String[] {
                        "Filesystem",
                        "Size",
                        "Used",
                        "Avail",
                        "Use%",
                        "Mounted on",
                        "Type"
                    };
                printf("        ls ls ls ls ls ls ls",HEADER);
                for (int i=0; i<fslist.length; i++) {
                    singleFsInfo(fslist[i]);
                }
            } catch (RuntimeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                shutdown();
            }

    }

    public void singleFsInfo(FileSystem fs) throws SigarException {
        long used, avail, total, pct;

        try {
            FileSystemUsage usage;
            if (fs instanceof NfsFileSystem) {
                NfsFileSystem nfs = (NfsFileSystem)fs;
                if (!nfs.ping()) {
                    println(nfs.getUnreachableMessage());
                    return;
                }
            }
            usage = this.sigar.getFileSystemUsage(fs.getDirName());

            used = usage.getTotal() - usage.getFree();
            avail = usage.getAvail();
            total = usage.getTotal();

            pct = (long)(usage.getUsePercent() * 100);
        } catch (SigarException e) {
            //e.g. on win32 D:\ fails with "Device not ready"
            //if there is no cd in the drive.
            used = avail = total = pct = 0;
        }

        String usePct;
        if (pct == 0) {
            usePct = "-";
        }
        else {
            usePct = pct + "%";
        }

       
        Object[] items = new Object[] {
                fs.getDevName(),
                Sigar.formatSize(total* 1024),
                Sigar.formatSize(used* 1024),
                Sigar.formatSize(avail* 1024),
                usePct,
                fs.getDirName(),
                fs.getSysTypeName() + "/" + fs.getTypeName()
            };
        printf("        ls ls ls ls ls ls ls",items);
    }
   
   
    public void duInfo(String root) throws SigarException {
           clearInfo();
        println("============Display usage for a directory recursively===============");

        String rootDir = root;
       
        try {
            sigarInit(false);
            printf("        ls       ls ",new Object[]{"size","directory"});
            List<String> rootList = new ArrayList<String>();
            rootList.add(rootDir);
            treePrint(rootList);


        } catch (RuntimeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            shutdown();
        }
    }
   
    public void treePrint(List<String> treeList) throws SigarException{
        for(String temp:treeList){
           
            File dirFile = new File(temp);
            if ( dirFile.isDirectory()){
               
                DirUsage du = this.sigar.getDirUsage(temp);
                Object[] items = new Object[] {
                        Sigar.formatSize(du.getDiskUsage()),
                        temp
                    };
                printf("        ls       ls ",items);
               
                String[] files = dirFile.list();
                List<String> tList = new ArrayList();
                for (int i = 0 ; i < files.length ; i++){
                    String dirFull = temp + "\\" + files[i];
                   
                    if( new File(dirFull).isDirectory()){
                        tList.add(dirFull);
                    }
                }
                treePrint(tList);
            }
        }

       
    }
   
    public static void main(String[] args) throws SigarException {
        SystemInfo one = new SystemInfo();
       
        one.cpuInfo();
        System.out.println(one.getInfo());
       
        one.memInfo();
        System.out.println(one.getInfo());   

        one.dfInfo();
        System.out.println(one.getInfo());
       
        one.duInfo("c:\\downloads");
        System.out.println(one.getInfo());
       
    }

}



3.测试执行
windows平台

D:\Documents and Settings\mac>cd \java\commmandline\sigartest

D:\java\commmandline\sigartest>dir
 驱动器 D 中的卷是 DATA
 卷的序列号是 495F-895B

 D:\java\commmandline\sigartest 的目录

2010-12-02  04:45    <DIR>          .
2010-12-02  04:45    <DIR>          ..
2010-11-30  14:48           418,299 sigar.jar
2010-12-02  04:51               186 runSystemInfo.bat
2010-12-02  04:52               183 runNetInfo.bat
2010-12-02  16:14            89,220 sigartest.jar
2009-03-25  15:58           258,048 sigar-x86-winnt.dll
               5 个文件        765,936 字节
               2 个目录 16,477,224,960 可用字节

D:\java\commmandline\sigartest>type runSystemInfo.bat
java -classpath D:\java\commmandline\sigartest\sigartest.jar;D:\java\commmandlin
e\sigartest\sigar.jar;D:\java\commmandline\sigartest\sigar-x86-winnt.dll com.mac
home.sigar.test.SystemInfo
D:\java\commmandline\sigartest>

linux平台

libsigar-x86-linux.so  runNetInfo.sh  runSystemInfo.sh  sigar.jar  sigartest.jar
[root@oracle sigartest]# cat runSystemInfo.sh
#!/bin/sh
java -classpath sigartest.jar:sigar.jar com.machome.sigar.test.SystemInfo
[root@oracle sigartest]#
[root@oracle sigartest]# cat runSystemInfo.sh
#!/bin/sh
java -classpath sigartest.jar:sigar.jar com.machome.sigar.test.SystemInfo
[root@oracle sigartest]# ./runSystemInfo.sh

执行测试:

============Current system Cpu information================
Vendor.........Intel
Model..........Mobile Intel(R) Pentium(R) 4 - M CPU 2.00GHz
Mhz............1195
Total CPUs.....1
Physical CPUs..1
Cores per CPU..1

CPU 0.........
User Time.....5.9%
Sys Time......8.1%
Idle Time.....85.8%
Wait Time.....0.0%
Nice Time.....0.0%
Combined......14.1%
Irq Time......0.0%

Totals........
User Time.....54.6%
Sys Time......11.2%
Idle Time.....32.2%
Wait Time.....0.0%
Nice Time.....0.0%
Combined......65.9%
Irq Time......1.8%


============Display information about free and used memory================
             total       used       free
Mem:       1015276K     877456K     137820K
MemPer:          100%      86.0%      13.0%
Swap:      2447596K     997476K    1450120K
RAM:           992M

============Report filesystem disk space usage===============
        Filesystem       Size       Used      Avail       Use% Mounted on       Type
               C:\        20G        13G       6.5G        67%        C:\ FAT32/local
               D:\        88G        72G        15G        83%        D:\ FAT32/local
               E:\         0          0          0           -        E:\ cdrom/cdrom
               F:\         0          0          0           -        F:\ cdrom/cdrom

============Display usage for a directory recursively===============
              size        directory
              2.9G       c:\downloads
              180M       c:\downloads\bj
                0        c:\downloads\pic
                0        c:\downloads\music
                0        c:\downloads\video
                0        c:\downloads\Movie
                0        c:\downloads\software
                0        c:\downloads\mp3
                0        c:\downloads\game
                0        c:\downloads\driver
               17M       c:\downloads\ftpserverdir
              8.7M       c:\downloads\ftpserverdir\test1
              488M       c:\downloads\flv

 

该技术在windows上测试通过,不知道其它平台下是否运行正常?

你可能感兴趣的:(oracle,linux,Solaris,AIX,FreeBSD)