您的位置:首页 > 运维架构

基于SNMP和JRobin的监控

2012-12-17 16:14 363 查看
SNMP4J模拟SNMPGET

[java] view
plaincopy

public class Snmp_Test_1 {  

      

    private static final Logger logger = Logger.getLogger(Snmp_Test_1.class);    

    private static String protocol = "udp"; // 监控时使用的协议    

    private static String port = "161"; // 监控时使用的端口    

        public static String snmpGet(String ipAddress, String community, String oid) {  

            String resultStat = null; // 监控结果状态  

              

            StringBuffer address = new StringBuffer();  

            address.append(protocol);  

            address.append(":");  

            address.append(ipAddress);  

            address.append("/");  

            address.append(port);  

            //udp:xxx.xxx.xxx.xxx/161  

              

            Address targetAddress = GenericAddress.parse(address.toString());  

            PDU pdu = new PDU();  

            pdu.add(new VariableBinding(new OID(oid)));  

            pdu.setType(PDU.GET);  

            // 创建共同体对象CommunityTarget  

            CommunityTarget target = new CommunityTarget();  

            target.setCommunity(new OctetString(community));  

            target.setAddress(targetAddress);  

            target.setVersion(SnmpConstants.version1);  

            target.setTimeout(2000); // 超时时间  

            target.setRetries(1); // 重复次数  

              

            /**公共的SNMP首部包含:版本(已在共同体中),共同体,PDU*/  

            DefaultUdpTransportMapping udpTransportMap = null;  

            Snmp snmp = null;  

            try {  

                // 发送同步消息  

                udpTransportMap = new DefaultUdpTransportMapping();  

                udpTransportMap.listen(); // 开启监听线程基于socket  

                snmp = new Snmp(udpTransportMap);  

                ResponseEvent response = snmp.send(pdu, target);  

                PDU resposePdu = response.getResponse();  

                if (resposePdu == null) {  

                    logger.info(ipAddress + ": Request timed out.");  

                } else {  

                    Object obj = resposePdu.getVariableBindings().firstElement();  

                    VariableBinding variable = (VariableBinding) obj;  

                    resultStat = variable.getVariable().toString();  

                }  

            } catch (Exception e) {  

                e.printStackTrace();  

            } finally {  

                if (snmp != null) {  

                    try {  

                        snmp.close();  

                    } catch (IOException e) {  

                        snmp = null;  

                    }  

                }  

                if (udpTransportMap != null) {  

                    try {  

                        udpTransportMap.close();  

                    } catch (IOException e) {  

                        udpTransportMap = null;  

                    }  

                }  

            }  

              

            return resultStat;  

        }  

      

}  

 

JRobin类:

[java] view
plaincopy

public class CPU_Monitor_Test {  

      

    private static final Logger logger = Logger.getLogger(CPU_Monitor_Test.class);  

    private int step = 30;  

    private String rrdPath = "./test.rrd";  

    private int width = 600;  

    private int height = 150;  

    private long begintime = org.jrobin.core.Util.getTimestamp();  

      

    public CPU_Monitor_Test() throws RrdException, IOException {  

          

        logger.info("now into CPU_Monitor_Test");  

        RrdDb rrdDb = null;  

        File file = new File(rrdPath);  

        if(file.exists()){  

            try {  

                rrdDb = new RrdDb(rrdPath);  

            } catch (Exception e) {  

            }  

        }else{  

            logger.info("the rrd is not exists! creat new rrd file .");  

        }  

          

        if (rrdDb == null) {  

            RrdDef rrdDef = new RrdDef(rrdPath , step);  

            rrdDef.addDatasource("cpu", "GAUGE", 2 * step, 0, Double.NaN);  

            rrdDef.addArchive("AVERAGE", 0.5, 1, 60);  

            rrdDef.addArchive("AVERAGE", 0.5, 6, 70);  

            rrdDef.addArchive("AVERAGE", 0.5, 24, 79);  

            rrdDef.addArchive("AVERAGE", 0.5, 288, 77);  

            rrdDef.addArchive("MAX", 0.5, 1, 60);  

            rrdDef.addArchive("MAX", 0.5, 6, 70);  

            rrdDef.addArchive("MAX", 0.5, 24, 79);  

            rrdDef.addArchive("MAX", 0.5, 288, 77);  

            rrdDb = new RrdDb(rrdDef); //create  

        }  

        if (rrdDb != null)  

            rrdDb.close();    

          

        logger.info("CPU_Monitor_Test init cuccess!");  

    }  

      

    public CPU_Monitor_Test updateData() throws Exception {  

          

        logger.info("begin updateData");  

        RrdDbPool pool = RrdDbPool.getInstance();  

        RrdDb rrdDb = null;  

        try {  

            rrdDb = pool.requestRrdDb(rrdPath);  

            long lastUpdateTime = rrdDb.getLastUpdateTime();  

            long nowTime = org.jrobin.core.Util.getTimestamp();  

            if (nowTime > lastUpdateTime) {  

            Sample sample = rrdDb.createSample(nowTime);  

            sample.setValue("cpu", Double.valueOf(Snmp_Test_1.snmpGet("127.0.0.1", "public",   

                    "1.3.6.1.2.1.25.3.3.1.2.3")));  

            sample.update();  

            logger.info("updateData success");  

            }  

            return this;  

        }   

        finally {  

            pool.release(rrdDb);   

        }  

    }  

      

    public void generateGraph() throws IOException, RrdException {  

          

        RrdGraphDef def = new RrdGraphDef();  

        def.setTimeSpan(begintime,org.jrobin.core.Util.getTimestamp());  

        def.setWidth(width);  

        def.setHeight(height);  

        def.setFilename("./test.png");  

        def.setVerticalLabel("used %");  

        def.setTitle("测试:监控CPU");  

        def.datasource("cpu", rrdPath, "cpu", "AVERAGE");  

        def.area("cpu", Color.RED, "cpu traffic");  

          

        def.gprint("cpu", "MIN", "%3f Min");  

        def.gprint("cpu", "AVERAGE",  "%3f Avg");  

        def.gprint("cpu", "MAX", "%3f Max");  

        def.gprint("cpu", "LAST", "%3f Last//r");  

        def.print("cpu", "MIN", "min cpu = %.3f");  

        def.print("cpu", "AVERAGE", "avg cpu = %.3f");  

        def.print("cpu", "MAX", "max cpu = %.3f");  

        def.print("cpu", "LAST", "last cpu = %.3f");  

          

        def.setPoolUsed(false);  

        def.setImageFormat("png");  

          

        def.setSmallFont(new Font("Monospaced", Font.PLAIN, 11));  

        def.setLargeFont(new Font("SansSerif", Font.BOLD, 14));   

        RrdGraph g = new RrdGraph(def);  

        logger.info("generateGraph:"+g.getRrdGraphInfo().getFilename());  

          

    }  

      

    public void sleepAndRun(int num) throws Exception{  

        try {  

            while(--num >0){  

                TimeUnit.SECONDS.sleep(Long.valueOf(step));  

                this.updateData();                

            }  

        } catch (InterruptedException e) {  

            e.printStackTrace();  

        }  

        this.generateGraph();   

    }  

      

      

      

      

    public static void main(String[] args) {  

        try {  

            new CPU_Monitor_Test().updateData().sleepAndRun(30);  

        } catch (RrdException e) {  

            e.printStackTrace();  

        } catch (IOException e) {  

            e.printStackTrace();  

        } catch (Exception e) {  

            e.printStackTrace();  

        }  

    }  

}  

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: