public class MachineCollector
  implements Runnable
{
  private static int DEFAULT_INTERVAL = 30;
  private boolean isStopped = false;
  private RandomAccessFile procNetDevReader;
  private RandomAccessFile procMemInfoReader;
  private RandomAccessFile procLoadAvgReader;
  private RandomAccessFile procStatReader;
  private RandomAccessFile procCpuInfoReader;
  private static final Map<String, String> memInterestKey = new HashMap();
  private static final String[] cpuIndexName = { "cpu-place-holder", "cpu_user", "cpu_nice", "cpu_system", "cpu_idle", "cpu_iowait", "cpu_irq", "cpu_softirq", "cpu_steal", "cpu_guest", "cpu_guest_nice" };
  private static final Map<String, Long> cpuPreInfo = new HashMap();
  private static boolean cpuPreInfoEmpty = true;
  private static final Logger logger = Logger.getLogger(MachineCollector.class);
  private static MachineCollector instance = new MachineCollector();
 
  static
  {
    memInterestKey.put("MemTotal", "mem_total");
    memInterestKey.put("MemFree", "mem_free");
    memInterestKey.put("Buffers", "mem_buffer");
    memInterestKey.put("Cached", "mem_cached");
    memInterestKey.put("SwapCached", "swap_cached");
    memInterestKey.put("SwapTotal", "swap_total");
    memInterestKey.put("SwapFree", "swap_free");
  }
 
  public static MachineCollector getInstance()
  {
    return instance;
  }
 
  private MachineCollector()
  {
    try
    {
      this.procNetDevReader = new RandomAccessFile("/proc/net/dev", "r");
      this.procMemInfoReader = new RandomAccessFile("/proc/meminfo", "r");
      this.procLoadAvgReader = new RandomAccessFile("/proc/loadavg", "r");
      this.procStatReader = new RandomAccessFile("/proc/stat", "r");
      this.procCpuInfoReader = new RandomAccessFile("/proc/cpuinfo", "r");
    }
    catch (FileNotFoundException e)
    {
      logger.error("No such file, Is /proc mounted?", e);
    }
  }
 
  public void start()
  {
    if (this.isStopped) {
      return;
    }
    new Thread(this).start();
  }
 
  public void run()
  {
    this.isStopped = false;
    while (!this.isStopped)
    {
      Map<String, Object> info = getInfoFromProcFile();
      
      sendInfoByJson(info);
      try
      {
        Thread.sleep(DEFAULT_INTERVAL * 1000);
      }
      catch (InterruptedException e)
      {
        e.printStackTrace();
      }
    }
  }
 
  public void stop()
  {
    this.isStopped = true;
  }
 
  private Map<String, Object> getInfoFromProcFile()
  {
    Map<String, Object> info = new HashMap();
    
    readMemUsage(info);
    readSysOverload(info);
    readCpuUsage(info);
    readDiskUsage(info);
    
    readCpuInfo(info);

readNetTraffic(info);
    
    return info;
  }
 
  private void readMemUsage(Map<String, Object> info)
  {
    String line = null;
    try
    {
      int keysNotRead = memInterestKey.size();
      this.procMemInfoReader.seek(0L);
      while (((line = this.procMemInfoReader.readLine()) != null) && (keysNotRead != 0))
      {
        int sepIndex = line.indexOf(":");
        
        String key = line.substring(0, sepIndex);
        if (memInterestKey.containsKey(key))
        {
          info.put(memInterestKey.get(key), line.substring(sepIndex + 1, line.length() - 2).trim());
          keysNotRead--;
        }
      }
    }
    catch (Exception e)
    {
      logger.error("read /proc/meminfo error", e);
    }
  }
 
  private void readSysOverload(Map<String, Object> info)
  {
    String line = null;
    String[] terms = null;
    try
    {
      this.procLoadAvgReader.seek(0L);
      line = this.procLoadAvgReader.readLine();
      
      terms = line.trim().split("\\s+");
      
      info.put("load_avg1", terms[0]);
      info.put("load_avg5", terms[1]);
      info.put("load_avg15", terms[2]);
    }
    catch (Exception e)
    {
      logger.error("read /proc/loadavg error", e);
    }
  }
 
  private void readCpuUsage(Map<String, Object> info)
  {
    String line = null;
    String[] terms = null;
    try
    {
      this.procStatReader.seek(0L);
      line = this.procStatReader.readLine();
      if (!line.startsWith("cpu")) {
        return;
      }
      Long total_p = Long.valueOf(0L);
      Long total_n = Long.valueOf(0L);
      if (!cpuPreInfoEmpty) {
        for (Map.Entry<String, Long> et : cpuPreInfo.entrySet()) {
          total_p = Long.valueOf(total_p.longValue() + ((Long)et.getValue()).longValue());
        }
      }
      Map<String, Long> cpuNowInfo = new HashMap();
      
      terms = line.split("\\s+");
      for (int i = 1; i < terms.length; i++)
      {
        long ticks = Long.parseLong(terms[i]);
        total_n = Long.valueOf(total_n.longValue() + ticks);
        
        cpuNowInfo.put(cpuIndexName[i], Long.valueOf(ticks));
      }
      Long total_dif;
      if (cpuPreInfoEmpty)
      {
        cpuPreInfoEmpty = false;
      }
      else
      {
        total_dif = Long.valueOf(total_n.longValue() - total_p.longValue());
        for (Map.Entry<String, Long> et : cpuNowInfo.entrySet())
        {
          Long cpu_p = (Long)cpuPreInfo.get(et.getKey());
          Long cpu_n = (Long)cpuNowInfo.get(et.getKey());

double cpu = (cpu_n.longValue() - cpu_p.longValue()) / total_dif.longValue() * 100.0D;
          
          info.put(et.getKey(), Double.valueOf(cpu));
        }
      }
      for (Map.Entry<String, Long> et : cpuNowInfo.entrySet()) {
        cpuPreInfo.put(et.getKey(), et.getValue());
      }
    }
    catch (Exception e)
    {
      logger.error("read /proc/stat error", e);
    }
  }
 
  private void readCpuInfo(Map<String, Object> info)
  {
    String line = null;
    try
    {
      this.procCpuInfoReader.seek(0L);
      
      int cpuCoreNum = 0;
      while ((line = this.procCpuInfoReader.readLine()) != null) {
        if (line.startsWith("processor")) {
          cpuCoreNum++;
        }
      }
      info.put("cpu_core", Integer.valueOf(cpuCoreNum));
    }
    catch (Exception e)
    {
      logger.error("read /proc/cpuinfo error", e);
    }
  }
 
  private void readDiskUsage(Map<String, Object> info)
  {
    File fsroot = new File("/");
    
    long disk_total = fsroot.getTotalSpace() >> 20;
    long disk_free = fsroot.getFreeSpace() >> 20;
    long disk_usable = fsroot.getUsableSpace() >> 20;
    
    info.put("disk_total", String.valueOf(disk_total));
    info.put("disk_free", String.valueOf(disk_free));
    info.put("disk_usable", String.valueOf(disk_usable));
  }
 
  private void readNetTraffic(Map<String, Object> info)
  {
    String line = null;
    try
    {
      this.procNetDevReader.seek(0L);

this.procNetDevReader.readLine();
      this.procNetDevReader.readLine();
      
      List<Map<String, String>> netinfos = new ArrayList();
      while ((line = this.procNetDevReader.readLine()) != null)
      {
        line = line.trim();
        int sep = line.indexOf(':');
        
        String dev = line.substring(0, sep);
        String rline = line.substring(sep + 1);
        if ((!dev.equals("lo")) && (!dev.startsWith("sit")))
        {
          Map<String, String> netinfo = new HashMap();
          
          String[] terms = rline.trim().split("\\s+");
          
          netinfo.put("dev_name", dev);
          netinfo.put("rx_bytes", terms[0]);
          netinfo.put("rx_packets", terms[1]);
          netinfo.put("tx_bytes", terms[8]);
          netinfo.put("tx_packets", terms[9]);
          
          netinfos.add(netinfo);
        }
      }
      info.put("net_devs", netinfos);
    }
    catch (Exception e)
    {
      logger.error("read /proc/net/dev error", e);
    }
  }
 
  private void sendInfoByJson(Map<String, Object> info)
  {
    if (info.containsKey("cpu_user"))
    {
      String json = JSON.toJSONString(info);
      try
      {
        Message message = new Message();
        message.setBody(json.getBytes(Charset.forName("UTF-8")));
        
        message.setCollectcode(Message.COLLECT_CODE.COLLECT_MACHINE);
        message.setBusinesscode(Message.SUB_COLLECT_CODE.SC_MAC_DEF);
        message.setIp(MonitorModule.ipn);
        
        message.setTimestamp(new Date().getTime());
        message.setBiz_name("".getBytes(Charset.forName("UTF-8")));
        message.setBiz_name_s(0);
        
        message.setTotalLen(message.getBody().length + 24);
        
        Sender.send(message);
      }
      catch (Exception e)
      {
        logger.error("get local ip as int", e);
      }
    }
  }
 
  @Deprecated
  public static Map<String, Number> getInfobyExec()
  {
    result = new HashMap();
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader brStat = null;
    Process process = null;
    try
    {
      process = Runtime.getRuntime().exec("top -b -n 1");
      is = process.getInputStream();
      isr = new InputStreamReader(is, Charset.forName("UTF-8"));
      brStat = new BufferedReader(isr);
      
      String tem = brStat.readLine();
      String[] terms = tem.trim().split("[,:]{1}");
      String loadaverage1 = terms[(terms.length - 3)];
      String loadaverage5 = terms[(terms.length - 2)];
      String loadaverage15 = terms[(terms.length - 1)];
      
      result.put("load_avg1", new Double(loadaverage1));
      result.put("load_avg5", new Double(loadaverage5));
      result.put("load_avg15", new Double(loadaverage15));
      
      tem = brStat.readLine();
      terms = tem.trim().split("[,:]{1}");
      String total_task = terms[1].trim().split(" ")[0];
      String runnung_task = terms[2].trim().split(" ")[0];
      String sleeping_task = terms[3].trim().split(" ")[0];
      String stopped_task = terms[4].trim().split(" ")[0];
      String zombie_task = terms[5].trim().split(" ")[0];
      
      result.put("total_task", new Integer(total_task));
      result.put("runnung_task", new Integer(runnung_task));
      result.put("sleeping_task", new Integer(sleeping_task));
      result.put("stopped_task", new Integer(stopped_task));
      result.put("zombie_task", new Integer(zombie_task));
      
      tem = brStat.readLine();
      terms = tem.trim().split("[,:]{1}");
      String cpu_us = terms[1].split("%")[0];
      String cpu_id = terms[4].split("%")[0];
      
      result.put("cpu_us", new Double(cpu_us));
      result.put("cpu_idle", new Double(cpu_id));
      
      tem = brStat.readLine();
      terms = tem.trim().split("[,:]{1}");
      String mem_total = terms[1].trim().split(" ")[0].replace("k", "");
      String mem_used = terms[2].trim().split(" ")[0].replace("k", "");
      String mem_free = terms[3].trim().split(" ")[0].replace("k", "");
      
      result.put("mem_total", new Long(mem_total));
      result.put("mem_used", new Long(mem_used));
      result.put("mem_free", new Long(mem_free));
      
      tem = brStat.readLine();
      terms = tem.trim().split("[,:]{1}");
      String swap_total = terms[1].trim().split(" ")[0].replace("k", "");
      String swap_used = terms[2].trim().split(" ")[0].replace("k", "");
      String swap_free = terms[3].trim().split(" ")[0].replace("k", "");
      
      result.put("swap_total", new Long(swap_total));
      result.put("swap_used", new Long(swap_used));
      result.put("swap_free", new Long(swap_free));

return result;
    }
    catch (Exception ex)
    {
      logger.error(ex.getMessage(), ex);
    }
    finally
    {
      try
      {
        if (is != null) {
          is.close();
        }
        if (isr != null) {
          isr.close();
        }
        if (brStat != null) {
          brStat.close();
        }
        if (process != null)
        {
          try
          {
            process.waitFor();
          }
          catch (InterruptedException e)
          {
            e.printStackTrace();
          }
          process.destroy();
        }
      }
      catch (IOException ex)
      {
        logger.error(ex.getMessage(), ex);
      }
    }
  }
 
  public static void setInterval(Integer interval)
  {
    DEFAULT_INTERVAL = interval.intValue();
  }
}

java 收集linux信息的更多相关文章

  1. shell脚本批量收集linux服务器的硬件信息快速实现

    安装ansible批量管理系统.(没有的话,ssh远程命令循环也可以) 在常用的数据库里面新建一张表,用你要收集的信息作为列名,提供可以用shell插入.

  2. 10 个用于收集硬件信息的 Linux 命令

    知道自己的Linux系统运行在什么样的硬件组件上总是好的,因为如果涉及到在系统上安装软件包和驱动程序的话,这将有助于你处理兼容性问题. 因此,下面我们将给出一些非常有用的命令,它们可以帮助你提取你的L ...

  3. [2017-2018上Java助教]个人信息收集

    在本学期的Java课程中,我们要收集的信息如下 1.学号 .码云地址 3.博客园地址 请各位同学自行创建,并按照如下的格式评论在这篇博客下方 学号+https://git.oschina.net/as ...

  4. Linux检查和收集硬件信息的常用命令总结

    Linux检查和收集硬件信息的常用命令总结 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Linux基础真的很重要,基础不牢,地动山摇.这句话我是听老男孩创始人冉总说的一句话,起初 ...

  5. linux信息收集篇之sosreport

    sosreport是一个类型于supportconfig 的工具,sosreport是python编写的一个工具,适用于centos(和redhat一样,包名为sos).ubuntu(其下包名为sos ...

  6. 最简单的方法是使用标准的 Linux GUI 程序之一: i-nex 收集硬件信息,并且类似于 Windows 下流行的 CPU-Z 的显示。 HardInfo 显示硬件具体信息,甚至包括一组八个的流行的性能基准程序,你可以用它们评估你的系统性能。 KInfoCenter 和 Lshw 也能够显示硬件的详细信息,并且可以从许多软件仓库中获取。

    最简单的方法是使用标准的 Linux GUI 程序之一: i-nex 收集硬件信息,并且类似于 Windows 下流行的 CPU-Z 的显示. HardInfo 显示硬件具体信息,甚至包括一组八个的流 ...

  7. Oracle 判断 并 手动收集 统计信息 脚本

    CREATE OR REPLACE PROCEDURE SchameB.PRC_GATHER_STATS AUTHID CURRENT_USER IS BEGIN SYS.DBMS_STATS.GAT ...

  8. Java在linux下调用C/C++生成的so文件

    1.CplusUtil.java是java web工程中的一个工具类内容如下:CplusUtil.java package cn.undoner.utils; /** * Created by ${& ...

  9. 基于 Web 的数据挖掘--自动抽取用 HTML、XML 和 Java 编写的信息

    简介: 不可否认,万维网是到目前为止世界上最丰富和最密集的信息来源.但是,它的结构使它很难用系统的方法来利用信息.本文描述的方法和工具将使那些熟悉 Web 最常用技术的开发人员能快速而便捷地获取他们所 ...

随机推荐

  1. 每天一个Linux命令(54)chkconfig命令

        chkconfig命令检查.设置系统的各种服务.     (1)用法:     用法:  chkconfig  [必要参数]  [服务]     (2)功能:     功能:  chkconf ...

  2. arcgis flex aqi 3大util

    第一:webMapUtil 主要用来根据id或者json创建map,跟webmap相关 第二:GeometryUtil 主要用来计算面积,长度,还有判断是否相交等,跟geometry相关. 第三:We ...

  3. 利用 :before 特性实现图片按比例显示

    好吧,想不到自称布局小沙弥的我会被图片按比例显示给尴尬到. 设计师跟我说,这里的图要按 750x330 的,好吧,但这图是屏宽呀,屏幕宽度会变化的,那高度也会不定咯, 要么裁图片(工作量大),要么给定 ...

  4. [SCOI2013]火柴棍数字(背包)

    题目 做饭 由于越高位越好,我们先得出能组成的最高位 \(f[i][j][k]\)表示从低到高位第\(i\)位,手里拿着\(j\)根火柴,第\(i\)位是否为\(0\)所需要的最少火柴 我们转移仅需得 ...

  5. php数组函数-array_combine()

    array_combine()函数通过合并两个数组来创建一个新数组,其中一个数组是键名,另一个数组的值为键值. 如果其中一个数组为空,或者两个数组的元素个数不同,则该函数返回 false. array ...

  6. iptable防火墙面试题

    第1章 (一)基础口试题 1.1 详述 iptales 工作流程以及规则过滤顺序? 1.防火墙是一层层过滤的.实际是按照配置规则的顺序从上到下,从前到后进行过滤的. 2.如果匹配上了规则,即明确表明是 ...

  7. Oracle 数据库 INTERVAL DAY TO SECOND类型的使用

    INTERVAL DAY TO SECOND类型可以用来存储单位为天和秒的时间间隔.下面这条语句创建一个名为promotions的表,用来存储促销信息.promotions表包含了一个INTERVAL ...

  8. springmvc文件上传的基本描述

    SpringMVC的文件上传,底层也是使用的Apache的Commons-fileupload 可以分为三步: 1.导入依赖包 <!-- 文件上传的依赖 --> <dependenc ...

  9. Owin and Startup class

    https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection ...

  10. python中的import一个注意事项

    import math def foo(): import math x = math.pi # 如果math在下面import会出错,因为import是个写的过程(添加到sys.modules中), ...