转:基于web的资源视图(cpu、内存、流量)显示方案

基于web的资源视图(cpu、内存、流量)显示方案 2012-08-08 12:35:55

标签: web
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。 http://speakingbaicai.blog.51cto.com/5667326/958314

本人第一次写blog,努力中。

言归正传。这篇博客完成的工作是在网页上以图表的方式,显示cpu、内存、流量等资源信息。先上一副效果图:

使用工具与环境:

web架构:基于python的django

画图工具:基于js的画图工具 highcharts 链接http://www.highcharts.com/

页面的基本显示由html代码负责,没啥可说的。html代码如下:

  1. <!DOCTYPE html> 
  2. <html lang="en"> 
  3. <head> 
  4.   <title>计算机资源视图</title> 
  5.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
  6.   <link rel="stylesheet" type="text/css" href="/media/css/basic.css"/> 
  7.   <script type="text/javascript" src="/media/js/jquery-1.4.2.min.js" ></script> 
  8.   <script type="text/javascript" src="/media/jschart/highcharts.js"></script> 
  9.   <script type="text/javascript" src="/media/jschart/modules/exporting.js"></script> 
  10.   <script type="text/javascript" src="/media/mjs/physical.js"></script> 
  11. </head> 
  12. <body> 
  13.  
  14.    <!--  #charts --> 
  15.    <charts> 
  16.      <div class="charts"> 
  17.        <div class="chartshead"><span>主控节点 资源视图</span></div> 
  18.        <div id="cpu"></div> 
  19.        <div id="mem"></div> 
  20.        <div id="rx"></div> 
  21.        <div id="tx"></div> 
  22.  
  23.          <br style="clear:both"/> 
  24.       </div> 
  25.    </charts> 
  26. </body> 
  27. </html> 

画图主要是使用js代码,使用ajax机制定时异步获得数据,然后在图上添加数据点。每5秒添加一个新点。js代码如下:

  1.         var chart_cpu; 
  2.         var chart_mem; 
  3.         var chart_rx;  
  4.         var chart_tx;  
  5.         var maxmem; 
  6.         var mem; 
  7.         var pre_cpu = 0 
  8.         var pre_cpu_total = 0 
  9.         var pre_rb = 0 
  10.         var pre_tb = 0 
  11.         var flag = 1 
  12.       var timeout = 5000 
  13.       //var para = window.location.search;       
  14.         //更新 
  15.         function requestData() { 
  16.          var stime = new Date(); 
  17.             $.ajax({ 
  18.             //async: false, 
  19.                 url:'/ajax/jsonmgt',  
  20.                 success: function(point) {               
  21.                // add 4 points 
  22.                var x = (new Date()).getTime() + 8*3600*1000; // 当前时间  
  23.                var out = eval("(" + point + ")"
  24.                //var out = eval( point ) 
  25.                maxmem = out[0] 
  26.                mem = out[1] 
  27.                cpu_use = out[2] 
  28.                cpu_total = out[3] 
  29.                rb = out[4] 
  30.                tb = out[5] 
  31.                memrate = mem/maxmem * 100 
  32.                     //cpu 
  33.                     d_cpu = cpu_use - pre_cpu 
  34.                     d_cpu_total = cpu_total - pre_cpu_total 
  35.                     pre_cpu = cpu_use 
  36.                     pre_cpu_total = cpu_total 
  37.                     cpurate = d_cpu/d_cpu_total *100 
  38.                if(cpurate == 100) 
  39.                   cpurate = 99.9 
  40.                     //rb tb 
  41.                     d_rb = rb - pre_rb 
  42.                     d_tb = tb - pre_tb 
  43.                     pre_rb = rb 
  44.                     pre_tb = tb 
  45.                     rkb = d_rb/1024 
  46.                     tkb = d_tb/1024 
  47.                     if(flag == 1){ 
  48.                      rkb = 0 
  49.                     tkb = 0 
  50.                     cpurate = 0 
  51.                         memrate = 0 
  52.                     flag =0 
  53.                     } 
  54.                     //add points 
  55.                chart_cpu.series[0].addPoint([x,cpurate], truetrue); 
  56.                chart_mem.series[0].addPoint([x,memrate], truetrue); 
  57.                chart_rx.series[0].addPoint([x,rkb], truetrue); 
  58.                chart_tx.series[0].addPoint([x,tkb], truetrue); 
  59.                var etime = new Date(); 
  60.                d_date=etime.getTime()-stime.getTime(); 
  61.                     setTimeout(requestData, timeout - d_date);   
  62.                 }, 
  63.                 cache: false 
  64.             }); 
  65.         } 
  66.          
  67. //cpu 
  68. $(document).ready(function(){  
  69.     chart_cpu = new Highcharts.Chart({  
  70.         chart: {  
  71.             renderTo: 'cpu'//图表放置的容器,DIV  
  72.             defaultSeriesType: 'spline'//图表类型为曲线图  
  73.             backgroundColor:'#DFFDFD'
  74.             events: {  
  75.                 //load: requestData 
  76.                                }  
  77.                       },  
  78.         title: {  
  79.             text: 'CPU负载'      //图表标题  
  80.                       },  
  81.         xAxis: { //设置X轴  
  82.             title: { text: '时间'   },   
  83.             type: 'datetime',       //X轴为日期时间类型  
  84.             tickPixelInterval: 150  //X轴标签间隔  
  85.                       },  
  86.         yAxis: { //设置Y轴  
  87.             title: { text: 'CPU使用率'   }, 
  88.             labels: { 
  89.                   formatter: function() { 
  90.                             return this.value +'%'
  91.                               } 
  92.                                  }, 
  93.             max: 100, //Y轴最大值  
  94.             min: 0  //Y轴最小值  
  95.                       },  
  96.         tooltip: {//当鼠标悬置数据点时的提示框  
  97.             formatter: function() { //格式化提示信息  
  98.                 return Highcharts.dateFormat('%H:%M:%S'this.x) +' '+   
  99.                 Highcharts.numberFormat(this.y, 2)+'%';  
  100.                                 }  
  101.                       },  
  102.         legend: {  
  103.             enabled: false  //设置图例不可见  
  104.                       },  
  105.         exporting: {  
  106.             enabled: false  //设置导出按钮不可用  
  107.                       },  
  108.         
  109.         series: [{  
  110.             data: (function() { //设置默认数据,  
  111.                 var data = [],  
  112.                 time = (new Date()).getTime() + 8*3600*1000,  
  113.                 i;  
  114.   
  115.                 for (i = -19; i < 0; i++) {  
  116.                     data.push({  
  117.                         x: time + i * timeout,   
  118.                         y: 0 * 100  
  119.                                                       });  
  120.                                            }  
  121.                 return data;  
  122.                                  })()  
  123.                        }]  
  124.            });  
  125. });  
  126. //mem 
  127. $(function() {  
  128.     chart_mem = new Highcharts.Chart({  
  129.         chart: {  
  130.             renderTo: 'mem'//图表放置的容器,DIV  
  131.             defaultSeriesType: 'spline'//图表类型为曲线图  
  132.             backgroundColor:'#DFFDFD'
  133.             events: {  
  134.  
  135.                                  }  
  136.                       },  
  137.         title: {  
  138.             text: '内存负载'  //图表标题  
  139.                       },  
  140.         xAxis: { //设置X轴  
  141.             title: { text: '时间'   },   
  142.             type: 'datetime',  //X轴为日期时间类型  
  143.             tickPixelInterval: 150  //X轴标签间隔  
  144.                      },  
  145.         yAxis: { //设置Y轴  
  146.             title: { text: '内存使用记录'   }, 
  147.             labels: { 
  148.                   formatter: function() { 
  149.                             return this.value + '%'
  150.                               } 
  151.                                  }, 
  152.             max: 100, //Y轴最大值  
  153.             min: 0  //Y轴最小值  
  154.  
  155.                       },  
  156.         tooltip: {//当鼠标悬置数据点时的提示框  
  157.             formatter: function() { //格式化提示信息  
  158.                 return Highcharts.dateFormat('%H:%M:%S'this.x) +' '+   
  159.                 Highcharts.numberFormat(this.y, 2) + '%' + ' ' + 
  160.                      Highcharts.numberFormat(mem,0) + 'MB'
  161.                                 }  
  162.                       },  
  163.         legend: {  
  164.             enabled: false  //设置图例不可见  
  165.                      },  
  166.         exporting: {  
  167.             enabled: false  //设置导出按钮不可用  
  168.                      },  
  169.         
  170.         series: [{  
  171.             data: (function() { //设置默认数据,  
  172.                 var data = [],  
  173.                 time = (new Date()).getTime()+8*3600*1000,  
  174.                 i;  
  175.   
  176.                 for (i = -19; i < 0; i++) {  
  177.                     data.push({  
  178.                         x: time + i * timeout,   
  179.                         y: 0  
  180.                                                       });  
  181.                                             }  
  182.                 return data;  
  183.                                  })()  
  184.                       }]  
  185.          });  
  186. });  
  187. //rx 
  188. $(function() {  
  189.     chart_rx = new Highcharts.Chart({  
  190.         chart: {  
  191.             renderTo: 'rx'//图表放置的容器,DIV  
  192.             defaultSeriesType: 'spline'//图表类型为曲线图  
  193.             backgroundColor:'#DFFDFD',   //背景颜色 
  194.             events: {  
  195.               
  196.                                  }  
  197.                       },  
  198.         title: {  
  199.             text: '网络接收流量'  //图表标题  
  200.                      },  
  201.         xAxis: { //设置X轴  
  202.             title: { text: '时间'   },   
  203.             type: 'datetime',  //X轴为日期时间类型  
  204.             tickPixelInterval: 150  //X轴标签间隔  
  205.                       },  
  206.         yAxis: { //设置Y轴  
  207.             title: { text: '接收网络流量'   }, 
  208.             labels: { 
  209.                   formatter: function() { 
  210.                             return this.value +'kb/s'
  211.                               } 
  212.                                  }, 
  213.             //max: 200, //Y轴最大值  
  214.             min: 0  //Y轴最小值  
  215.                       },  
  216.         tooltip: {//当鼠标悬置数据点时的提示框  
  217.             formatter: function() { //格式化提示信息  
  218.                 return Highcharts.dateFormat('%H:%M:%S'this.x) +' '+   
  219.                 Highcharts.numberFormat(this.y, 2)+'kb/s';  
  220.                                 }  
  221.                       },  
  222.         legend: {  
  223.             enabled: false  //设置图例不可见  
  224.                       },  
  225.         exporting: {  
  226.             enabled: false  //设置导出按钮不可用  
  227.                      },  
  228.         
  229.         series: [{  
  230.             data: (function() { //设置默认数据,  
  231.                 var data = [],  
  232.                 time = (new Date()).getTime() + 8*3600*1000,  
  233.                 i;  
  234.   
  235.                 for (i = -19; i < 0; i++) {  
  236.                     data.push({  
  237.                         x: time + i * timeout,   
  238.                         y: 0  
  239.                                                       });  
  240.                                            }  
  241.                 return data;  
  242.                                 })()  
  243.                      }]  
  244.           });  
  245. });  
  246. //tx 
  247. $(function() {  
  248.     chart_tx = new Highcharts.Chart({  
  249.         chart: {  
  250.             renderTo: 'tx'//图表放置的容器,DIV  
  251.             defaultSeriesType: 'spline'//图表类型为曲线图  
  252.             backgroundColor:'#DFFDFD'
  253.             events: {  
  254.                  load: requestData 
  255.                                  }  
  256.                       },  
  257.         title: {  
  258.             text: '网络发送流量'  //图表标题  
  259.                      },  
  260.         xAxis: { //设置X轴  
  261.             title: { text: '时间'   },   
  262.             type: 'datetime',  //X轴为日期时间类型  
  263.             tickPixelInterval: 150  //X轴标签间隔  
  264.                       },  
  265.         yAxis: { //设置Y轴  
  266.             title: { text: '发送网络流量'   }, 
  267.             labels: { 
  268.                   formatter: function() { 
  269.                             return this.value +'kb/s'
  270.                               } 
  271.                                  }, 
  272.             //max: 200, //Y轴最大值  
  273.             min: 0  //Y轴最小值  
  274.                       },  
  275.         tooltip: {//当鼠标悬置数据点时的提示框  
  276.             formatter: function() { //格式化提示信息  
  277.                 return Highcharts.dateFormat('%H:%M:%S'this.x) +' '+   
  278.                 Highcharts.numberFormat(this.y, 2)+'kb/s';  
  279.                                 }  
  280.                       },  
  281.         legend: {  
  282.             enabled: false  //设置图例不可见  
  283.                       },  
  284.         exporting: {  
  285.             enabled: false  //设置导出按钮不可用  
  286.                      },  
  287.         
  288.         series: [{  
  289.             data: (function() { //设置默认数据,  
  290.                 var data = [],  
  291.                 time = (new Date()).getTime() + 8*3600*1000,  
  292.                 i;  
  293.   
  294.                 for (i = -19; i < 0; i++) {  
  295.                     data.push({  
  296.                         x: time + i * timeout,   
  297.                         y: 0 
  298.                                                       });  
  299.                                            }  
  300.                 return data;  
  301.                                 })()  
  302.                      }]  
  303.           });  
  304. })

使用ajax,就需要有数据源定期提供数据。使用c语言写一个程序(取名mgtinfo.c)抓取瞬时的cpu、内存、流量。代码如下:

  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3. #include <sys/stat.h> 
  4. typedef struct        //定义一个cpu occupy的结构体 
  5.     char name[20];      //定义一个char类型的数组名name有20个元素 
  6.     long user; //定义一个无符号的int类型的user 
  7.     long nice; //定义一个无符号的int类型的nice 
  8.     long system;//定义一个无符号的int类型的system 
  9.     long idle; //定义一个无符号的int类型的idle 
  10. }CPU_OCCUPY; 
  11. typedef struct        //定义一个mem occupy的结构体 
  12.     char name[20];      //定义一个char类型的数组名name有20个元素 
  13.     long total;  
  14.     //char name2[20]; 
  15.     char unit[20]; 
  16.     long free; 
  17.     long buffers;   
  18.     long cached;                         
  19. }MEM_OCCUPY; 
  20. typedef struct        //定义一个cpu occupy的结构体 
  21.     char name[20];      //定义一个char类型的数组名name有20个元素 
  22.     long rb, rpkt, r_err, r_drop, r_fifo, r_frame, r_compr, r_mcast;  
  23.     long tb, tpkt, t_err, t_drop, t_fifo, t_coll, t_carrier, t_compr;  
  24. }NET_OCCUPY; 
  25. int get_memoccupy (MEM_OCCUPY *mem) //对无类型get函数含有一个形参结构体类弄的指针O 
  26.     FILE *fd;           
  27.     int n;              
  28.     char buf[256];    
  29.     MEM_OCCUPY *m; 
  30.     m=mem; 
  31.      long MemFree, Buffers, Cached;                                                                                                     
  32.     fd = fopen ("/proc/meminfo""r");  
  33.     fgets (buf, sizeof(buf), fd);  
  34.     sscanf (buf, "%s %ld %s", &m->name, &m->total, &m->unit);  
  35.     fgets (buf, sizeof(buf), fd);  
  36.     sscanf (buf, "%s %ld %s", m->name, &m->free, m->unit);  
  37.     fgets (buf, sizeof(buf), fd);  
  38.     sscanf (buf, "%s %ld %s", m->name, &m->buffers, m->unit);  
  39.     fgets (buf, sizeof(buf), fd);  
  40.     sscanf (buf, "%s %ld %s", m->name, &m->cached, m->unit);  
  41.     fclose(fd);     //关闭文件fd 
  42.     return 0; 
  43. int get_cpuoccupy (CPU_OCCUPY *cpust) //对无类型get函数含有一个形参结构体类弄的指针O 
  44. {    
  45.     FILE *fd;          
  46.     int n;             
  47.     char buf[256];  
  48.     CPU_OCCUPY *cpu_occupy; 
  49.     cpu_occupy=cpust; 
  50.           
  51.      if ((fd = fopen ("/proc/stat""r")) != NULL){  
  52.             while (fgets (buf, sizeof(buf), fd)){  
  53.                 if( *buf == 'c' && *(buf + 1) == 'p'break;  
  54.                 }  
  55.            fclose (fd);  
  56.       }  
  57.     else    
  58.          printf("read file failed\n");                                                                                              
  59.     sscanf (buf, "cpu %ld %ld %ld %ld", &cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle); 
  60.      //printf("%ld\n", cpu_occupy->user); 
  61.      return 0;     
  62.  
  63. int get_netoccupy (NET_OCCUPY *net) //对无类型get函数含有一个形参结构体类弄的指针O 
  64.     FILE *fd;                     
  65.     char buf[256];    
  66.     NET_OCCUPY *net_occupy; 
  67.     net_occupy = net; 
  68.      //long MemFree, Buffers, Cached; 
  69.                                                                                                                
  70.     fd = fopen ("/proc/net/dev""r");  
  71.        
  72.     fgets (buf, sizeof(buf), fd);  
  73.     fgets (buf, sizeof(buf), fd);  
  74.     fgets (buf, sizeof(buf), fd);  
  75.     fgets (buf, sizeof(buf), fd);  
  76.     //printf("%s",buf); 
  77.     sscanf (buf, "%s %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld", &net_occupy->name, &net_occupy->rb ,&net_occupy->rpkt, &net_occupy->r_err, &net_occupy->r_drop, &net_occupy->r_fifo ,&net_occupy->r_frame, &net_occupy->r_compr, &net_occupy->r_mcast, &net_occupy->tb, &net_occupy->tpkt); 
  78.     fclose(fd);     //关闭文件fd 
  79.     return 0; 
  80. int cal_cpuoccupy (CPU_OCCUPY *o, CPU_OCCUPY *n)  
  81. {    
  82.     unsigned long od, nd;     
  83.     unsigned long id, sd; 
  84.     int cpu_use = 0;    
  85.     od = (unsigned long) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间再赋给od 
  86.     nd = (unsigned long) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间再赋给od  
  87.     id = (unsigned long) (n->user - o->user);    //用户第一次和第二次的时间之差再赋给id 
  88.     sd = (unsigned long) (n->system - o->system);//系统第一次和第二次的时间之差再赋给sd 
  89.     if((nd-od) != 0) 
  90.     cpu_use = (int)((sd+id)*10000)/(nd-od); //((用户+系统)乖100)除(第一次和第二次的时间差)再赋给g_cpu_used 
  91.     else cpu_use = 0; 
  92.     return cpu_use; 
  93. int main() 
  94.     CPU_OCCUPY cpu_stat; 
  95.     MEM_OCCUPY mem_stat; 
  96.     NET_OCCUPY net_stat; 
  97.     long cpu_use, cpu_total; 
  98.     //获取内存 
  99.     get_memoccupy ((MEM_OCCUPY *)&mem_stat); 
  100.     //第一次获取cpu使用情况 
  101.     get_cpuoccupy((CPU_OCCUPY *)&cpu_stat); 
  102.      cpu_use = cpu_stat.user + cpu_stat.nice + cpu_stat.system; 
  103.      cpu_total=cpu_stat.user + cpu_stat.nice + cpu_stat.system + cpu_stat.idle; 
  104.     //printf("%ld,%ld,%ld,%ld\n",cpu_stat.user,cpu_stat.nice,cpu_stat.system,cpu_stat.idle); 
  105.      get_netoccupy((NET_OCCUPY *)&net_stat); 
  106.     printf("%ld,%ld,%ld,%ld,%ld,%ld\n",mem_stat.total/1024,(mem_stat.total-mem_stat.free-mem_stat.buffers-mem_stat.cached)/1024,cpu_use,cpu_total,net_stat.rb,net_stat.tb);   
  107.     return 0; 
  108. }  

在django中,需要写一个函数jsonmgt,作为ajax请求的响应。每次执行,jsonmgt调用mgtinfo.c,获得瞬时cpu、内存、流量后,以json数据形式返回给页面。页面再用上面贴的js代码添加数据点绘图。

  1. # time data 
  2. def jsonmgt( request ): 
  3.     print "calulate data" 
  4.     cmd="cmd/./mgtinfo"  
  5.     output = os.popen(cmd,'r'
  6.     ret = output.read() 
  7.     info = ret.split(','
  8.     maxmem = string.atof(info[0]) 
  9.     mem = string.atof(info[1]) 
  10.     cpu_use = string.atof(info[2]) 
  11.     cpu_total = string.atof(info[3]) 
  12.     rb = string.atof(info[4]) 
  13.     tb = string.atof(info[5]) 
  14.     output.close() 
  15.     data = [maxmem,mem,cpu_use,cpu_total,rb,tb] 
  16.     data = simplejson.dumps( data, cls = QuerySetEncoder ) 
  17.     return HttpResponse( data ) 
  18. # django ajax 
  19. class QuerySetEncoder( simplejson.JSONEncoder ): 
  20.     """ 
  21.         Encoding QuerySet into JSON format. 
  22.     """ 
  23.     def default( self, object ): 
  24.         try
  25.             return serializers.serialize( "python", object,ensure_ascii = False ) 
  26.         except
  27.             return simplejson.JSONEncoder.default( self, object ) 

 

本文出自 “说话的白菜” 博客,请务必保留此出处http://speakingbaicai.blog.51cto.com/5667326/958314

转载于:https://www.cnblogs.com/4admin2root/articles/2705861.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值