使用Sigar采系统信息

 

简介
Sigar(System Information Gatherer And Reporter),开源的跨平台系统信息收集工具,C语言实现。
可以监控服务器性能信息,例如cpu、mem、disk等使用信息。

 

下载 
Hyperic-hq官方网站:http://www.hyperic.com
Sigar.jar下载地址:http://sigar.hyperic.com

 

使用

Maven下载Sigar.jar
<dependency>
    <groupId>org.fusesource</groupId>
    <artifactId>sigar</artifactId>
    <version>1.6.4</version>
</dependency>

非Maven:直接拷贝下载压缩包中的Sigar.jar 到你的项目lib目录


 
 源码

 Sigar中提供的基本类

/*
 * Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
 * This file is part of SIGAR.
 * 
 * SIGAR is free software; you can redistribute it and/or modify
 * it under the terms version 2 of the GNU General Public License as
 * published by the Free Software Foundation. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

package com.study.sigar;

import java.io.PrintStream;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarProxy;
import org.hyperic.sigar.SigarException;

import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.pager.PageControl;
import org.hyperic.sigar.pager.PageFetchException;
import org.hyperic.sigar.pager.StaticPageFetcher;

import org.hyperic.sigar.util.GetlineCompleter;
import org.hyperic.sigar.util.PrintfFormat;

import org.hyperic.sigar.shell.CollectionCompleter;
import org.hyperic.sigar.shell.ProcessQueryCompleter;
import org.hyperic.sigar.shell.ShellCommandBase;
import org.hyperic.sigar.shell.ShellCommandExecException;
import org.hyperic.sigar.shell.ShellCommandUsageException;

public abstract class SigarCommandBase extends ShellCommandBase implements GetlineCompleter {

    protected Shell shell;
    protected PrintStream out = System.out;
    protected PrintStream err = System.err;
    protected Sigar sigar;
    protected SigarProxy proxy;
    protected List output = new ArrayList();
    private CollectionCompleter completer;
    private GetlineCompleter ptqlCompleter;
    private Collection completions = new ArrayList();
    private PrintfFormat formatter;
    private ArrayList printfItems = new ArrayList();

    public SigarCommandBase(Shell shell) {
        this.shell = shell;
        this.out   = shell.getOutStream();
        this.err   = shell.getErrStream();
        this.sigar = shell.getSigar();
        this.proxy = shell.getSigarProxy();
        
        //provide simple way for handlers to implement tab completion
        this.completer = new CollectionCompleter(shell);
        if (isPidCompleter()) {
            this.ptqlCompleter = new ProcessQueryCompleter(shell);
        }
    }

    public SigarCommandBase() {
        this(new Shell());
        this.shell.setPageSize(PageControl.SIZE_UNLIMITED);
    }

    public void setOutputFormat(String format) {
        this.formatter = new PrintfFormat(format);
    }

    public PrintfFormat getFormatter() {
        return this.formatter;
    }

    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 printf(Object[] items) {
        PrintfFormat formatter = getFormatter();
        if (formatter == null) {
            //see flushPrintfItems
            this.printfItems.add(items);
        }
        else {
            println(formatter.sprintf(items));
        }
    }

    public void printf(List items) {
        printf((Object[])items.toArray(new Object[0]));
    }

    public void println(String line) {
        if (this.shell.isInteractive()) {
            this.output.add(line);
        }
        else {
            this.out.println(line);
        }
    }

    private void flushPrintfItems() {
        if (this.printfItems.size() == 0) {
            return;
        }

        //no format was specified, just line up the columns
        int[] max = null;

        for (Iterator it=this.printfItems.iterator();
             it.hasNext();)
        {
            Object[] items = (Object[])it.next();
            if (max == null) {
                max = new int[items.length];
                Arrays.fill(max, 0);
            }
            for (int i=0; i<items.length; i++) {
                int len = items[i].toString().length();
                if (len > max[i]) {
                    max[i] = len;
                }
            }
        }

        StringBuffer format = new StringBuffer();
        for (int i=0; i<max.length; i++) {
            format.append("%-" + max[i] + "s");
            if (i < max.length-1) {
                format.append("    ");
            }
        }

        for (Iterator it=this.printfItems.iterator();
             it.hasNext();)
        {
            printf(format.toString(), (Object[])it.next());
        }
        this.printfItems.clear();
    }

    public void flush() {
        flushPrintfItems();

        try {
            this.shell.performPaging(new StaticPageFetcher(this.output));
        } catch(PageFetchException e) {
            this.err.println("Error paging: " + e.getMessage());
        } finally {
            this.output.clear();
        }
    }

    public abstract void output(String[] args)
        throws SigarException;

    protected boolean validateArgs(String[] args) {
        return args.length == 0;
    }

    public void processCommand(String[] args) 
        throws ShellCommandUsageException, ShellCommandExecException 
    {
        if (!validateArgs(args)) {
            throw new ShellCommandUsageException(getSyntax());
        }

        try {
            output(args);
        } catch (SigarException e) {
            throw new ShellCommandExecException(e.getMessage());
        }
    }

    public Collection getCompletions() {
        return this.completions;
    }

    public GetlineCompleter getCompleter() {
        return null;
    }

    public boolean isPidCompleter() {
        return false;
    }

    public String completePid(String line) {
        if ((line.length() >= 1) &&
            Character.isDigit(line.charAt(0)))
        {
            return line;
        }

        return this.ptqlCompleter.complete(line);
    }

    public String complete(String line) {
        if (isPidCompleter()) {
            return completePid(line);
        }
        GetlineCompleter c = getCompleter();
        if (c != null) {
            return c.complete(line);
        }

        this.completer.setCollection(getCompletions());
        return this.completer.complete(line);
    }
}

  采集系统信息

package com.study.sigar;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.HashMap;

import org.apache.log4j.Logger;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NfsFileSystem;
import org.hyperic.sigar.SigarException;

/**
 * @Title:
 * @author Administrator
 * @version 1.0
 */
public class SigarCollect extends SigarCommandBase {

	private Logger log = Logger.getLogger(SigarCollect.class);
	
	private HashMap info = new HashMap();
	
	// Probe Name
	
	public static void main(String[] args) throws Exception {
		new SigarCollect().processCommand(args);
	}
	
	public static void collect() throws Exception {
		String[] args = new String[]{};
		new SigarCollect().processCommand(args);
	}
	
	public void output(String[] args) throws SigarException {
		info.clear();
		log.info("Sigar collect probe host info...");
		
		//IP MAC
		NetInterfaceConfig config = this.sigar.getNetInterfaceConfig(null);
		info.put("CollectorIP", config.getAddress());
		info.put("Mac", config.getHwaddr());

		//采集机名称
		org.hyperic.sigar.NetInfo netInfo = this.sigar.getNetInfo();
		info.put("CollectorName", netInfo.getHostName());

		//内存大小单位G
		Mem mem   = this.sigar.getMem();
		info.put("hMemory", mem.getTotal()/1024/1024/1024);
		//Mem占用百分比
		String sMemory = format( mem.getUsedPercent());
		info.put("Memory", sMemory);
		
		//CPU占用百分比
        CpuPerc cpu = sigar.getCpuPerc();
        String sCpu = format(cpu.getCombined() * 100);
		info.put("Cpu", sCpu);
		
		//CPU大小 格式如 3*4Core2.67GHz
		org.hyperic.sigar.CpuInfo[] cpuInfos = this.sigar.getCpuInfoList();
		org.hyperic.sigar.CpuInfo cpuInfo = cpuInfos[0];
		info.put("hCPU",  cpuInfo.getModel());

		//磁盘/文件系统
		outputFile();
		
		info.put("Time_stamp", System.currentTimeMillis() + "");
		log.info("Collected probe host info " + info);
	}

	/**
	 * 采文件系统
	 */
	public void outputFile() throws SigarException {
		FileSystem[] fslist = this.proxy.getFileSystemList();
		double totalSize = 0l;
		double totalUsed = 0l;
		for (int i = 0; i < fslist.length; i++) {
			FileSystem fs = fslist[i];
			try {
				FileSystemUsage usage = null;
				if (fs instanceof NfsFileSystem) {
					NfsFileSystem nfs = (NfsFileSystem) fs;
					if (!nfs.ping()) {
						log.warn(nfs.getUnreachableMessage());
						return;
					}
				}
				try {
					usage = this.sigar.getFileSystemUsage(fs.getDirName());
				} catch(Exception e){
					continue;
				}
				totalSize += Double.parseDouble(usage.getTotal() + ""); // 总大小
				totalUsed += Double.parseDouble(usage.getUsed() + "");  // 总已使用
			} catch (Exception e) {
				log.error("Get host file system info error", e);
			}
		}
		
		//磁盘占用百分比
		double percent = (double)(totalUsed/totalSize*100);
		String sPercent = format(percent);
		info.put("Disk", sPercent);
		
		//磁盘大小单位G
		double dTotalFileSize = totalSize/1024/1024;
		long iTotalFileSize = Math.round(dTotalFileSize);
		info.put("hDisk", iTotalFileSize);
	
	}
	/**
	 * 保留2位小数
	 * @param d
	 * @return
	 */
	private String format(double d) {
		DecimalFormat fnum = new DecimalFormat("##0.00");
		String dd = fnum.format(d);
		return dd;
	}
	
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值