原文地址:http://blog.csdn.net/chenjiazhu/article/details/77648100
该服务器监控平台分为三部分:
1. 监控管理平台:配置监控任务、配置监控服务器、启动关闭监控、结果展示
2. linux机器监控客户端:获取当前linux机器的监控指标,发送给监控管理平台
3. windows机器监控客户端:获取当前windows机器的监控指标,发送给监控管理平台
监控管理平台
界面如下:
监控任务
任务详情页
监控指标详情页
监控管理平台采用ssh2实现数据增删改查(没啥特别,不详细介绍)
图表展示采用hichart,图表上点,最多展示100个,如果采样点太多会影响加载速度,所以读取数据时用存储过程读取最多100个点
CREATE DEFINER=`root`@`%` PROCEDURE `sp_getMonitorInfo_2`(IN d_itemId INT, IN d_configId INT, d_count_num INT ) begin set @count := 0; set @num := 0; set @count := (select count(1) FROM better.MonitorInfo where itemId=d_itemId and configId=d_configId); IF @count<d_count_num*2 THEN SELECT id,cpu,cpu1,cpu2,cpu3,diskRead,diskWrite,memory,networkReceive,networkSend,time,configId,itemId FROM MonitorInfo where itemId=d_itemId and configId=d_configId; ELSE SET @num := round(@count/d_count_num,0); set @i := 0; select * from ( select @i :=@i + 1 as tmp_id,id,cpu,cpu1,cpu2,cpu3,diskRead,diskWrite,memory,networkReceive,networkSend,time,configId,itemId from MonitorInfo where itemId=d_itemId and configId=d_configId) aa where aa.tmp_id%@num=0; END IF; end
Linux监控客户端
Linux监控客户端实现采用读取/proc这个伪文件系统获取对应指标,并计算出监控的数值,返回给监控管理平台
这些数字指明了CPU执行不同的任务所消耗的时间(从系统启动开始累计到当前时刻)。时间单位是USER_HZ或jiffies(通常是百分之一秒)。
这些数据列的含义如下,我们从左至右逐一认识:
•user:正常的进程在用户态下执行时间累积
•nice: NICED的进程在用户态下执行时间列
•system:进程在内核态的执行时间累积
•idle:空闲时间累积
•iowait :等待I / O完成时间累积
•irq :硬中断时间
•softirq:软中断时间
“intr”这行给出自系统启动以来的所有中断信息。第一个数字记录所有的中断的次数;然后每个数对应一个特定的中断自系统启动以来所发生的次数。
“ctxt”给出了自系统启动以来CPU发生的上下文交换的次数。
“btime”给出了从系统启动到现在为止的时间,单位为秒。
“processes (total_forks) 自系统启动以来所创建的任务的个数目。
“procs_running”:当前运行队列的任务的数目。
“procs_blocked”:当前被阻塞的任务的数目,等待I/O完成次数。
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; public class CpuUsage { private static Logger log = LoggerFactory.getLogger(CpuUsage.class); private static CpuUsage INSTANCE = new CpuUsage(); private static long idleCpuTimeTemp = 0; private static long userCpuTimeTemp = 0; private static long systemCpuTimeTemp = 0; private static long softirqCpuTimeTemp = 0; private static long totalCpuTimeTemp = 0; private CpuUsage() { } public static CpuUsage getInstance() { return INSTANCE; } /** * Purpose:采集CPU使用率 * * @param args * @return float,CPU使用率,小于1 */ public int[] get() { // log.info("开始收集cpu使用率"); int result[] = new int[8]; int idleCpuUsage = 0, userCpuUsage = 0, systemCpuUsage = 0, softirqCpuUsage = 0; String fileName = "/proc/stat"; File file = new File(fileName ); BufferedReader reader = null; try { //System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String line = null; int count = 0; long idleCpuTime1 = 0, userCpuTime1 = 0, systemCpuTime1 = 0, softirqCpuTime1 = 0, totalCpuTime1 = 0; // 分别为系统启动后空闲的CPU时间和总的CPU时间 while ((line = reader.readLine()) != null) { // log.info("line:" + line); if (line.startsWith("cpu ")) { line = line.trim(); String[] temp = line.split("\s+"); idleCpuTime1 = Long.parseLong(temp[4]); userCpuTime1 = Long.parseLong(temp[1]); systemCpuTime1 = Long.parseLong(temp[3]); softirqCpuTime1 = Long.parseLong(temp[7]); for (String s : temp) { if (!s.equals("cpu")) { totalCpuTime1 += Long.parseLong(s); } } break; } } reader.close(); if((totalCpuTime1 - totalCpuTimeTemp)!=0) { if (idleCpuTimeTemp != 0) { idleCpuUsage = (int) (((idleCpuTime1 - idleCpuTimeTemp) * 100 / (totalCpuTime1 - totalCpuTimeTemp)) + 0.5); } if (userCpuTimeTemp != 0) { userCpuUsage = (int) (((userCpuTime1 - userCpuTimeTemp) * 100 / (totalCpuTime1 - totalCpuTimeTemp)) + 0.5); } if (systemCpuTimeTemp != 0) { systemCpuUsage = (int) (((systemCpuTime1 - systemCpuTimeTemp) * 100 / (totalCpuTime1 - totalCpuTimeTemp)) + 0.5); } if (softirqCpuTimeTemp != 0) { softirqCpuUsage = (int) (((softirqCpuTime1 - softirqCpuTimeTemp) * 100 / (totalCpuTime1 - totalCpuTimeTemp)) + 0.5); } } result[3] = idleCpuUsage; result[2] = userCpuUsage; result[0] = systemCpuUsage; result[1] = softirqCpuUsage; idleCpuTimeTemp = idleCpuTime1; userCpuTimeTemp = userCpuTime1; systemCpuTimeTemp = systemCpuTime1; softirqCpuTimeTemp = softirqCpuTime1; totalCpuTimeTemp = totalCpuTime1; } catch (IOException e) { log.error("CpuUsage发生Exception. " + e.getMessage()); } return result; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 采集内存 */ public class MemUsage { private static Logger log = LoggerFactory.getLogger(MemUsage.class); private static MemUsage INSTANCE = new MemUsage(); private MemUsage(){ } public static MemUsage getInstance(){ return INSTANCE; } /** * Purpose:采集内存使用率 * @param args * @return float,内存使用率,小于1 */ public float get() { // log.info("开始收集memory使用率"); float memUsage = 0.0f; Process pro = null; Runtime r = Runtime.getRuntime(); try { String command = "cat /proc/meminfo"; pro = r.exec(command); BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream())); String line = null; int count = 0; long totalMem = 0, freeMem = 0; while((line=in.readLine()) != null){ log.info(line); String[] memInfo = line.split("\s+"); if(memInfo[0].startsWith("MemTotal")){ totalMem = Long.parseLong(memInfo[1]); } if(memInfo[0].startsWith("MemFree")){ freeMem = Long.parseLong(memInfo[1]); } memUsage = 1- (float)freeMem/(float)totalMem; log.info("本节点内存使用率为: " + memUsage); if(++count == 2){ break; } } in.close(); pro.destroy(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("MemUsage发生InstantiationException. " + e.getMessage()); log.error(sw.toString()); } return memUsage; } /** * Purpose:采集总内存 * @param args * @return floatKB */ public float getMenTotal() { // log.info("开始收集MenTotal"); float totalMem = 0; Process pro = null; Runtime r = Runtime.getRuntime(); try { String command = "cat /proc/meminfo"; pro = r.exec(command); BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream())); String line = null; int count = 0; while((line=in.readLine()) != null){ // log.info(line); String[] memInfo = line.split("\s+"); if(memInfo[0].startsWith("MemTotal")){ totalMem = Long.parseLong(memInfo[1]); } // log.info("本节点MenTotal为: " + totalMem); if(++count == 2){ break; } } in.close(); pro.destroy(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("MemUsage发生InstantiationException. " + e.getMessage()); log.error(sw.toString()); } return totalMem; } /** * Purpose:采集内存MemFree * @param args * @return float KB */ public float getMemFree() { // log.info("开始收集MemFree"); float freeMem = 0; String fileName = "/proc/meminfo"; File file = new File(fileName ); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = null; while((line=reader.readLine()) != null){ // log.info(line); String[] memInfo = line.split("\s+"); if(memInfo[0].startsWith("MemFree")){ freeMem = Long.parseLong(memInfo[1]); break; } } reader.close(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("MemUsage发生InstantiationException. " + e.getMessage()); log.error(sw.toString()); } return freeMem; } /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { while(true){ System.out.println(MemUsage.getInstance().get()); Thread.sleep(5000); } } }
/proc/diskstats文件比/sys/block/sda/stat文件多3个域,从左至右分别对应主设备号,次设备号和设备名称。后续的11个域在这两个文件里是相同的,它们的函义将在下面解释。除了第9个域,所有的域都是从启动时的累积值。
第1个域:读完成次数 ----- 读磁盘的次数,成功完成读的总次数。
(number of issued reads. This is the total number of reads completed successfully.)
第2个域:合并读完成次数, 第6个域:合并写完成次数。为了效率可能会合并相邻的读和写。从而两次4K的读在它最终被处理到磁盘上之前可能会变成一次8K的读,才被计数(和排队),因此只有一次I/O操作。这个域使你知道这样的操作有多频繁。
(number of reads merged)
第3个域:读扇区的次数,成功读过的扇区总次数。
(number of sectors read. This is the total number of sectors read successfully.)
第4个域:读花费的毫秒数,这是所有读操作所花费的毫秒数(用__make_request()到end_that_request_last()测量)。
(number of milliseconds spent reading. This is the total number of milliseconds spent by all reads (as measured from __make_request() to end_that_request_last()).)
第5个域:写完成次数 ----写完成的次数,成功写完成的总次数。
(number of writes completed. This is the total number of writes completed successfully.)
第6个域:合并写完成次数 -----合并写次数。
(number of writes merged Reads and writes which are adjacent to each other may be merged for efficiency. Thus two 4K reads may become one 8K read before it is ultimately handed to the disk, and so it will be counted (and queued) as only one I/O. This field lets you know how often this was done.)
第7个域:写扇区次数 ---- 写扇区的次数,成功写扇区总次数。
(number of sectors written. This is the total number of sectors written successfully.)
第8个域:写操作花费的毫秒数 --- 写花费的毫秒数,这是所有写操作所花费的毫秒数(用__make_request()到end_that_request_last()测量)。
(number of milliseconds spent writing This is the total number of milliseconds spent by all writes (as measured from __make_request() to end_that_request_last()).)
第9个域:正在处理的输入/输出请求数 -- -I/O的当前进度,只有这个域应该是0。当请求被交给适当的request_queue_t时增加和请求完成时减小。
(number of I/Os currently in progress. The only field that should go to zero. Incremented as requests are given to appropriate request_queue_t and decremented as they finish.)
第10个域:输入/输出操作花费的毫秒数 ----花在I/O操作上的毫秒数,这个域会增长只要field 9不为0。
(number of milliseconds spent doing I/Os. This field is increased so long as field 9 is nonzero.)
第11个域:输入/输出操作花费的加权毫秒数 ----- 加权, 花在I/O操作上的毫秒数,在每次I/O开始,I/O结束,I/O合并时这个域都会增加。这可以给I/O完成时间和存储那些可以累积的提供一个便利的测量标准。
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IoUsage { private static Logger log = LoggerFactory.getLogger(IoUsage.class); private static IoUsage INSTANCE = new IoUsage(); private static long ioReadTemp = 0; private static long ioWriteTemp = 0; private IoUsage(){ } public static IoUsage getInstance(){ return INSTANCE; } public long[] getData() { // log.info("开始收集磁盘IO read"); long ioRead = 0; long ioWrite = 0; long result[] = new long[2]; String fileName = "/proc/diskstats"; File file = new File(fileName ); BufferedReader reader = null; try { //System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String line = null; int count = 0; // 一次读入一行,直到读入null为文件结束 while ((line = reader.readLine()) != null) { // 显示行号 if(++count == 26){ // log.info(line); String[] temp = line.split("\s+"); if(temp.length > 10){ long ioReadData = (long)(Float.parseFloat(temp[6])/2+0.5); long ioWriteData = (long)(Float.parseFloat(temp[10])/2+0.5); if(ioReadTemp!=0) { ioRead=ioReadData-ioReadTemp; ioWrite=ioWriteData-ioWriteTemp; } ioReadTemp=ioReadData; ioWriteTemp=ioWriteData; } break; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } result[0]=ioRead; result[1]=ioWrite; // result[2]=ioReadTemp; // result[3]=ioWriteTemp; return result; } /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { while(true){ System.out.println(IoUsage.getInstance().get()); Thread.sleep(5000); } } }
网络IO
/proc/net/dev
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NetUsage { private static Logger log = LoggerFactory.getLogger(NetUsage.class); private static NetUsage INSTANCE = new NetUsage(); private final static float TotalBandwidth = 1000; //网口带宽,Mbps private static long inSizeTemp=0; private static long outSizeTemp=0; private NetUsage(){ } public static NetUsage getInstance(){ return INSTANCE; } /** * @Purpose:采集网络带宽使用率 * @param args * @return float,网络带宽使用率,小于1 */ public long[] getData() { // log.info("开始收集网络带宽使用率"); float netUsage = 0.0f; long inSize1 = 0; long outSize1 = 0; long result[] = new long[2]; String fileName = "/proc/net/dev"; File file = new File(fileName ); BufferedReader reader = null; try { //System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String line = null; int count = 0; while((line=reader.readLine()) != null){ line = line.trim(); if(line.startsWith("eth")){ // log.info("line:"+line); String[] temp = line.split("\s+"); long inKbyte; long outKbyte; // for(int i=0;i<temp.length;i++) // { // log.info("["+i+"]"+temp[i]); // } if(temp.length==16) { inKbyte = Long.parseLong(temp[0].substring(5))/1024; //Receive bytes,单位为Byte,转化为KB outKbyte = Long.parseLong(temp[8])/1024; //Transmit bytes,单位为Byte ,转化为KB } else { inKbyte = Long.parseLong(temp[1])/1024; //Receive bytes,单位为Byte,转化为KB outKbyte = Long.parseLong(temp[9])/1024; //Transmit bytes,单位为Byte ,转化为KB } if (inSizeTemp!=0) { inSize1= inKbyte-inSizeTemp; outSize1= outKbyte-outSizeTemp; } inSizeTemp=inKbyte; outSizeTemp=outKbyte; break; } } reader.close(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("NetUsage发生InstantiationException. " + e.getMessage()); log.error(sw.toString()); } result[0]=inSize1; result[1]=outSize1; // result[2]=inSizeTemp; // result[3]=outSizeTemp; return result; } /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { while(true){ System.out.println(NetUsage.getInstance().get()); Thread.sleep(5000); } } }
获取数据采用两种方式作对比,举网络的例子
方式一:通过cat /proc/net/dev来取数据,代码如下:
public long[] getData1() { // log.info("开始收集网络带宽使用率"); float netUsage = 0.0f; long inSize1 = 0; long outSize1 = 0; long result[] = new long[4]; Process pro1; Runtime r = Runtime.getRuntime(); try { String command = "cat /proc/net/dev"; //第一次采集流量数据 long startTime = System.currentTimeMillis(); pro1 = r.exec(command); BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream())); String line = null; while((line=in1.readLine()) != null){ line = line.trim(); if(line.startsWith("eth")){ String[] temp = line.split("\s+"); long inKbyte = Long.parseLong(temp[0].substring(5))/1024; //Receive bytes,单位为Byte,转化为KB long outKbyte = Long.parseLong(temp[8])/1024; //Transmit bytes,单位为Byte ,转化为KB if (inSizeTemp!=0) { inSize1= inKbyte-inSizeTemp; outSize1= outKbyte-outSizeTemp; } inSizeTemp=inKbyte; outSizeTemp=outKbyte; break; } } in1.close(); pro1.destroy(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("NetUsage发生InstantiationException. " + e.getMessage()); log.error(sw.toString()); } result[0]=inSize1; result[1]=outSize1; result[2]=inSizeTemp; result[3]=outSizeTemp; return result; }
方式二:采用文件读,代码如下:
/** * @Purpose:采集网络带宽使用率 * @param args * @return float,网络带宽使用率,小于1 */ public long[] getData() { // log.info("开始收集网络带宽使用率"); float netUsage = 0.0f; long inSize1 = 0; long outSize1 = 0; long result[] = new long[2]; String fileName = "/proc/net/dev"; File file = new File(fileName ); BufferedReader reader = null; try { //System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String line = null; int count = 0; while((line=reader.readLine()) != null){ line = line.trim(); if(line.startsWith("eth")){ // log.info("line:"+line); String[] temp = line.split("\s+"); long inKbyte; long outKbyte; // for(int i=0;i<temp.length;i++) // { // log.info("["+i+"]"+temp[i]); // } if(temp.length==16) { inKbyte = Long.parseLong(temp[0].substring(5))/1024; //Receive bytes,单位为Byte,转化为KB outKbyte = Long.parseLong(temp[8])/1024; //Transmit bytes,单位为Byte ,转化为KB } else { inKbyte = Long.parseLong(temp[1])/1024; //Receive bytes,单位为Byte,转化为KB outKbyte = Long.parseLong(temp[9])/1024; //Transmit bytes,单位为Byte ,转化为KB } if (inSizeTemp!=0) { inSize1= inKbyte-inSizeTemp; outSize1= outKbyte-outSizeTemp; } inSizeTemp=inKbyte; outSizeTemp=outKbyte; break; } } reader.close(); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("NetUsage发生InstantiationException. " + e.getMessage()); log.error(sw.toString()); } result[0]=inSize1; result[1]=outSize1; // result[2]=inSizeTemp; // result[3]=outSizeTemp; return result; }
压测下来,方式二性能更好,所以采用方式二实现所有指标采集。
监控服务实现
监控客户端采用Springboot+SpringMvc实现,客户端提供了启动监控服务与关闭监控服务两个接口给监控管理平台调用
启动监控服务
@RequestMapping(value = { "/StartMonitorMachine" }, method = { RequestMethod.GET }, produces = "application/json;charset=UTF-8") @ResponseBody public String StartMonitorMachine(MachineMonitorConfigPack config) { try { logger.info("请求StartMonitorMachine:configId=" + config.getConfigId() + "&itemId=" + config.getItemId() + "&startTime=" + config.getStartTime() + "&lastTime=" + config.getLastTime() + "&ReCallUrl=" + config.getReCallUrl() + "&ip=" + config.getIp()); MonitorService.setConfigId(config.getConfigId()); MonitorService.setItemId(config.getItemId()); MonitorService.setRecallUrl(config.getReCallUrl()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startDate=new Date(); // Date startDate = sdf.parse(config.getStartTime()); Date deadDate = new Date(startDate.getTime() + config.getLastTime() * 60 * 1000); MonitorService.setStartTime(startDate); MonitorService.setDeadTime(deadDate); MonitorService.setIp(config.getIp()); MonitorService.getInstance().StartMonitor(); logger.info("请求启动监控信息成功"); ret.put("StateCode", "0"); ret.put("Message", "成功"); ret.put("Data", "0"); } catch (Exception e) { // TODO Auto-generated catch block logger.info("请求StartMonitorMachine Exception:"+e); ret.put("StateCode", "1"); ret.put("Message", e.toString()); ret.put("date", "1"); } return config.getJsoncallback()+"("+ret.toString()+")"; }
请求model
public class MachineMonitorConfigPack { private String jsoncallback; private int configId; private int itemId; private String startTime; private int lastTime; private String ReCallUrl; private String ip; public String getJsoncallback() { return jsoncallback; } public void setJsoncallback(String jsoncallback) { this.jsoncallback = jsoncallback; } public int getConfigId() { return configId; } public void setConfigId(int configId) { this.configId = configId; } public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public int getLastTime() { return lastTime; } public void setLastTime(int lastTime) { this.lastTime = lastTime; } public String getReCallUrl() { return ReCallUrl; } public void setReCallUrl(String reCallUrl) { ReCallUrl = reCallUrl; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
关闭监控服务
@RequestMapping(value = { "/StopMonitorMachine" }, method = { RequestMethod.GET }, produces = "application/json;charset=UTF-8") @ResponseBody public String StopMonitorMachine(String jsoncallback) { APIResponse<String> rsp; try { logger.info("请求StopMonitorMachine"); MonitorService.getInstance().StopMonitor(); ret.put("StateCode", "0"); ret.put("Message", "成功"); ret.put("Data", "0"); logger.info("请求StopMonitorMachine成功"); } catch (Exception e) { // TODO Auto-generated catch block logger.info("请求StopMonitorMachine Exception:"+e.toString()); ret.put("StateCode", "1"); ret.put("Message", e.toString()); ret.put("Data", "1"); } return jsoncallback+"("+ret.toString()+")"; }
jsoncallback是用来实现跨域访问
监控服务
启动监控接口会调用监控服务,监控服务会启动监控线程,为了保证只有一个监控进程活着,监控服务采用单例实现(其实这边可以采用@Component 托管给Spring,默认就是单例)
import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; public class MonitorService { private static Boolean _isRunning = false; private static Date deadTime; private static Date startTime; private static String recallUrl; private static int configId; private static int itemId; //private static int machineId; private static String ip; private static final Logger logger = LoggerFactory.getLogger(MonitorService.class); private MonitorService(){} private static final MonitorService monitorService=new MonitorService(); private static MonitorThread monitorThread = new MonitorThread(); private static Thread thread; // 将myRunnable作为Thread target创建新的线程 public static MonitorService getInstance(){ return monitorService; } public static void StartMonitor() { try { if (_isRunning) { logger.info("监控已启动"); monitorThread.setDeadTime(deadTime); monitorThread.setConfigId(configId); monitorThread.setItemId(itemId); monitorThread.setRecallUrl(recallUrl); logger.info("DeadTime:"+monitorThread.getDeadTime()); logger.info("configId:"+monitorThread.getConfigId()); logger.info("itemId:"+monitorThread.getItemId()); return; } Date time = new Date(); // if(time.before(deadTime) && time.after(startTime)) if(time.before(deadTime)) { // monitorThread.setIp(ip); // monitorThread.setUserName("root"); // monitorThread.setPassword("ymt@123"); monitorThread.setDeadTime(deadTime); monitorThread.setConfigId(configId); monitorThread.setItemId(itemId); monitorThread.setRecallUrl(recallUrl); logger.info("当前时间在监控时间内,启动监控进程"); thread = new Thread(monitorThread); thread.start(); logger.info("监控进程start"); _isRunning=true; } else { logger.info("当前时间不在监控时间内,未启动监控进程"); } } catch (Exception e) { logger.info("StartMonitor() Exception:"+e); } } @SuppressWarnings("deprecation") public static void StopMonitor() { thread.stop(); _isRunning=false; logger.info("关闭监控进程"); } public static void setRunning(boolean flag){ _isRunning=flag; } public static synchronized boolean getRunning(){ return _isRunning; } public static Date getDeadTime() { return deadTime; } public static void setDeadTime(Date deadTime) { MonitorService.deadTime = deadTime; } public static Date getStartTime() { return startTime; } public static void setStartTime(Date startTime) { MonitorService.startTime = startTime; } public static String getRecallUrl() { return recallUrl; } public static void setRecallUrl(String recallUrl) { MonitorService.recallUrl = recallUrl; } public static int getConfigId() { return configId; } public static void setConfigId(int configId) { MonitorService.configId = configId; } public static int getItemId() { return itemId; } public static void setItemId(int itemId) { MonitorService.itemId = itemId; } public static MonitorService getMonitorservice() { return monitorService; } public static String getIp() { return ip; } public static void setIp(String ip) { MonitorService.ip = ip; } }
监控线程
import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ymt.envagency.util.HttpRequest; import com.ymt.envagency.util.monitor.CpuUsage; import com.ymt.envagency.util.monitor.IoUsage; import com.ymt.envagency.util.monitor.MemUsage; import com.ymt.envagency.util.monitor.NetUsage; public class MonitorThread implements Runnable { private String ip; private String userName; private String password; private Date deadTime; private int configId; private int itemId; private String recallUrl; private static final Logger logger = LoggerFactory.getLogger(MonitorThread.class); public synchronized String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public synchronized String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public synchronized Date getDeadTime() { return deadTime; } public void setDeadTime(Date deadTime) { this.deadTime = deadTime; } public synchronized int getConfigId() { return configId; } public void setConfigId(int configId) { this.configId = configId; } public synchronized int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public synchronized String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public synchronized String getRecallUrl() { return recallUrl; } public void setRecallUrl(String recallUrl) { this.recallUrl = recallUrl; } public void run() { logger.info("进入run()"); try { float Memtotal = MemUsage.getInstance().getMenTotal()/1024; Date nowDate = new Date(); //这边获取是为了抛弃第一的无意义的取值 CpuUsage.getInstance().get(); IoUsage.getInstance().getData(); NetUsage.getInstance().getData(); logger.info("当前时间:"+nowDate); while (nowDate.before(getDeadTime())) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, 1); String addInfoTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(calendar.getTime()); int cpus[]=CpuUsage.getInstance().get(); long ios[]=IoUsage.getInstance().getData(); long nets[]=NetUsage.getInstance().getData(); // logger.info("cpuData:" + (int)cpus[3]+","+(int)cpus[0]+","+(int)cpus[1]+","+(int)cpus[2]); // logger.info("cpuData:" + (int)cpus[3]+","+(int)cpus[0]+","+(int)cpus[1]+","+(int)cpus[2]); // logger.info("cpuData:" + (int)cpus[3]+","+(int)cpus[0]+","+(int)cpus[1]+","+(int)cpus[2]); String url = recallUrl+"/createStressMonitorInfo.action"; String param = "configId=" + configId + "&itemId=" + itemId + "&cpuData=" + (int)cpus[0]+ "&cpu1Data=" + (int)cpus[1] + "&cpu2Data=" + (int)cpus[2] + "&cpu3Data=" + (int)cpus[3] + "&coreNumber=" + 8 + "&memoryData=" + (int)(MemUsage.getInstance().getMemFree()/1024)+ "&memoryTotalData=" + (int)Memtotal + "&diskReadData=" + (int)(ios[0]) + "&diskWriteData=" + (int)(ios[1]) + "&networkReceiveData=" + (int)(nets[0]) + "&networkSendData=" + (int)(nets[1]) + "&addInfoTime=" + URLEncoder.encode(addInfoTime); // logger.info("url:" + url); // logger.info("param:" + param); String s = HttpRequest.sendGet(url, param); logger.info("发送:"+url+"?"+param+" 返回:"+s); Thread.sleep(1000); nowDate = new Date(); } MonitorService.setRunning(false); logger.info("监控时间到,监控停止。"); } catch (Exception e) { logger.info("MonitorThread中run异常"+e.toString()); } } }
Windows段监控客户端
启动接口
public string StartMonitorMachine(MachineMonitorConfigPack info) { var resp = new APIResponse<string>() { StateCode = StateCode.Success, Message = "启动监控成功" }; try { // String name = ConfigurationManager.AppSettings["name"]; // String pwd = ConfigurationManager.AppSettings["password"]; // String domain = "."; //Logger.Info("domain:" + domain + "name:" + name + ",password:" + pwd); ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); //DateTime startTime = DateTime.Parse(info.startTime); DateTime startTime = DateTime.Now; DateTime endTime = startTime.AddMinutes(info.lastTime); MachineMonitor.SetStartTime(startTime); MachineMonitor.SetDeadTime(endTime); MachineMonitor.SetRecalUrl(info.ReCallUrl); MachineMonitor.SetConfigId(info.configId); MachineMonitor.SetItemId(info.itemId); MachineMonitor.StartMonitor(); Logger.Info("Post Start Monitor Machine success."); Logger.Info("startTime:"+ startTime); Logger.Info("endTime:"+ endTime); Logger.Info("RecalUrl:"+ info.ReCallUrl); Logger.Info("ConfigId:"+ info.configId); Logger.Info("ItemId:" + info.itemId); resp.Data = "0"; } catch (Exception ex) { resp.StateCode = StateCode.Fail; resp.Message += ex.ToString(); resp.Data = "1"; Logger.Info("Start Monitor Machine Exception:" + ex); } Logger.Info("请求StateCode:"+resp.StateCode+ ",Message:"+resp.Message); String result = info.jsoncallback + "(" + new JavaScriptSerializer().Serialize(resp) + ")"; return result; }
请求model
using Core.Bases; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Models { public class MachineMonitorConfigPack : PostPackBase { public string jsoncallback { get; set; } public int configId { get; set; } public int itemId { get; set; } public string startTime { get; set; } public int lastTime { get; set; } public string ReCallUrl { set; get; } } public class AppPoolMonitorConfigPack : PostPackBase { public int appPoolInfoId { get; set; } public string poolName { get; set; } public DateTime startTime { get; set; } public int lastTime { get; set; } } }
停止接口
public string StopMonitorMachine(string jsoncallback) { var resp = new APIResponse<string>() { StateCode = StateCode.Success, Message = "停止监控成功" }; try { MachineMonitor.SetDeadTime(DateTime.Now); MachineMonitor.StopMonitor(); Logger.Info("Start Monitor Machine."); resp.Data = "0"; } catch (Exception ex) { resp.StateCode = StateCode.Fail; resp.Message += ex.ToString(); resp.Data = "1"; Logger.Info("Stop Monitor Machine Exception:" + ex); } return jsoncallback + "(" + new JavaScriptSerializer().Serialize(resp) + ")"; }
监控服务
using Core.Monitor; using Core.MonitorUtils; using Core.ServerUtils; using Core.Text; using NLog; using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Web; namespace EnvAgency.Services { public class MachineMonitor { private static bool _isRunning = false; private static DateTime deadTime; private static DateTime startTime; private static String recallUrl; private static int configId; private static int itemId; //private static int machineId; private static Thread thread; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private MachineMonitor() { startTime = DateTime.Now.ToLocalTime(); deadTime = DateTime.Now.ToLocalTime(); } public static void SetStartTime(DateTime t) { startTime = t; } public static void SetDeadTime(DateTime t) { deadTime = t; } public static void SetRecalUrl(string t) { recallUrl = t; } public static void SetConfigId(int t) { configId = t; } public static void SetItemId(int t) { itemId = t; } public static void StartMonitor() { if (_isRunning) { Logger.Info("监控已启动"); return; } DateTime time = DateTime.Now.ToLocalTime(); string ip = ServerInfo.GetLocalIP(); //MachineInfo machineInfo = db.MachineInfo.Where(o => o.IP == ip).First(); //if (time < deadTime && time > startTime) Logger.Info("time:" + time); if(time < deadTime) { thread = new Thread(GetInfo); thread.Start(); Logger.Info("监控开启"); _isRunning = true; } else { Logger.Info("监控未开始或者已经结束"); } } public static void StopMonitor() { thread.Abort(); _isRunning = false; Logger.Info("监控关闭"); } public static void GetInfo() { Logger.Info("Start GetInfo Process"); DateTime dt = DateTime.Now; //int totalMemory = (int)((MemoryMonitor.getMemoryInfo().totalPhys / (1024 * 1024))); //int coreNum = ProcessorCountMonitor.getValue(); MachineMonitorInfo info; Logger.Info("Now:" + dt); while (dt<deadTime) { info = MonitorUtil.GetMachineMonitorInfo(); var client = new RestClient(recallUrl); string param = @"/createStressMonitorInfo.action?" + "configId=" + configId + "&itemId=" + itemId + "&cpuData=" + info.cpuData + "&coreNumber=" + info.coreNumber + "&memoryData=" + info.memoryData + "&memoryTotalData=" + info.memoryTotalData + "&diskReadData=" + info.diskReadData + "&diskWriteData=" + info.diskWriteData + "&networkReceiveData=" + info.networkReceiveData + "&networkSendData=" + info.networkSendData + "&addInfoTime=" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); Logger.Info("recallUrl : " + recallUrl); Logger.Info("request : " + param); var request = new RestRequest(param, Method.GET); var response = client.Execute(request); Logger.Info("response :" + response.StatusCode); System.Threading.Thread.Sleep(1000); dt = DateTime.Now; Logger.Info("Now:" + dt); } _isRunning = false; } } }
工具类
using Core.Monitor; using Core.Security; using EnvAgency.Extensions; using NLog; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Core.MonitorUtils { public class MonitorUtil { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); // 获取CPU,内存占用率,c盘,d盘使用情况 public static MachineMonitorInfoExt GetMachineMonitorInfoExt() { MachineMonitorInfoExt info = new MachineMonitorInfoExt(); ArrayList listThread = new ArrayList(); // 获取C盘可用空间 Thread thread5 = new Thread(delegate () { GetCAvaliable(ref info); }); thread5.Start(); listThread.Add(thread5); // 获取C盘总空间 Thread thread6 = new Thread(delegate () { GetCTotal(ref info); }); thread6.Start(); listThread.Add(thread6); // 获取D盘可用空间 Thread thread7 = new Thread(delegate () { GetDAvaliable(ref info); }); thread7.Start(); listThread.Add(thread7); // 获取D盘总空间 Thread thread8 = new Thread(delegate () { GetDTotal(ref info); }); thread8.Start(); listThread.Add(thread8); foreach (Thread thread in listThread) { thread.Join(); } return info; } // 获取cpu,内存,Disk(I/O),Network(I/O) public static MachineMonitorInfo GetMachineMonitorInfo() { MachineMonitorInfo info = new MachineMonitorInfo(); // info.CpuUsage = CPUMonitor.getValue(); /*由于采用新建线程存在内存一直上升的情况,所以换成线程池来才解决这个问题*/ ArrayList listThread = new ArrayList(); // 获取CPU占用比 Thread thread1 = new Thread(delegate () { GetCpu(ref info); }); thread1.Start(); listThread.Add(thread1); // 获取CPU核数 Thread thread2 = new Thread(delegate () { GetCpuCount(ref info); }); thread2.Start(); listThread.Add(thread2); // 获取可用内存 Thread thread3 = new Thread(delegate () { GetMenoryAvaliable(ref info); }); thread3.Start(); listThread.Add(thread3); // 获取总内存 Thread thread4 = new Thread(delegate () { GetMenoryTotal(ref info); }); thread4.Start(); listThread.Add(thread4); // 获取Disk Read Thread thread5 = new Thread(delegate () { GetDiskRead(ref info); }); thread5.Start(); listThread.Add(thread5); // 获取Disk Write Thread thread6 = new Thread(delegate () { GetDiskWrite(ref info); }); thread6.Start(); listThread.Add(thread6); // 获取Network Receive Thread thread7 = new Thread(delegate () { GetNetworkReceive(ref info); }); thread7.Start(); listThread.Add(thread7); // 获取Network Send Thread thread8 = new Thread(delegate () { GetNetworkSend(ref info); }); thread8.Start(); listThread.Add(thread8); foreach (Thread thread in listThread) { thread.Join(); } foreach (Thread thread in listThread) { thread.Abort(); } return info; } public static void GetCpu(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.cpuData = (int)(CPUMonitor.getValue()); } } public static void GetCpuCount(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.coreNumber = ProcessorCountMonitor.getValue(); } } public static void GetMenoryAvaliable(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.memoryData = (int)((MemoryMonitor.getMemoryInfo().availPhys / (1024 * 1024))); } } public static void GetMenoryTotal(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.memoryTotalData = (int)((MemoryMonitor.getMemoryInfo().totalPhys / (1024 * 1024))); } } public static void GetCAvaliable(ref MachineMonitorInfoExt info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.CHardDiskFreeSpace = (MemoryMonitor.GetHardDiskFreeSpace("C") / (1024 * 1024)); } } public static void GetCTotal(ref MachineMonitorInfoExt info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.CHardDiskSpace = (MemoryMonitor.GetHardDiskSpace("C") / (1024 * 1024)); } } public static void GetDAvaliable(ref MachineMonitorInfoExt info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.DHardDiskFreeSpace = (MemoryMonitor.GetHardDiskFreeSpace("D") / (1024 * 1024)); } } public static void GetDTotal(ref MachineMonitorInfoExt info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.DHardDiskSpace = (MemoryMonitor.GetHardDiskSpace("D") / (1024 * 1024)); } } // 单kb public static void GetDiskRead(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.diskReadData = (int)((DiskReadMonitor.getValue()) / 1024); } } // 单位Kb public static void GetDiskWrite(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.diskWriteData = (int)((DiskWriteMonitor.getValue()) / 1024); } } // 单位Kb public static void GetNetworkReceive(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.networkReceiveData = (int)((NetworkReceiveMonitor.getValue()) / 1024); } } // 单位Kb public static void GetNetworkSend(ref MachineMonitorInfo info) { ImpersonateUser user = new ImpersonateUser(); ImpersonateUserExt.ImpersonateAdminUser(user); lock (info) { info.networkSendData = (int)((NetworkSendMonitor.getValue()) / 1024); } } } [Serializable] public class MachineMonitorInfo { public int configId { get; set; } public int itemId { get; set; } public int cpuData { get; set; } public int coreNumber { get; set; } public int memoryData { get; set; } public int memoryTotalData { get; set; } public int diskReadData { get; set; } public int diskWriteData { get; set; } public int networkReceiveData { get; set; } public int networkSendData { get; set; } } [Serializable] public class MachineMonitorInfoExt : MachineMonitorInfo { public float CHardDiskFreeSpace { get; set; } public float DHardDiskFreeSpace { get; set; } public float CHardDiskSpace { get; set; } public float DHardDiskSpace { get; set; } } }
CPU
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { public sealed class CPUMonitor { private static readonly CPUMonitor instance = new CPUMonitor(); private PerformanceCounter pcCpuLoad; private CPUMonitor() { //初始化CPU计数器 pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total"); pcCpuLoad.MachineName = "."; pcCpuLoad.NextValue(); System.Threading.Thread.Sleep(1000); } public static CPUMonitor getMonitor() { return instance; } public static float getValue() { return instance.pcCpuLoad.NextValue(); } } }
CPU核数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { public sealed class ProcessorCountMonitor { public static readonly ProcessorCountMonitor instance = new ProcessorCountMonitor(); private int m_ProcessorCount = 0; //CPU个数 private ProcessorCountMonitor() { //CPU个数 m_ProcessorCount = Environment.ProcessorCount; } public static ProcessorCountMonitor getMonitor() { return instance; } public static int getValue() { return getMonitor().m_ProcessorCount; } } }
内存信息
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { [StructLayout(LayoutKind.Sequential)] public struct MEMORY_INFO { public uint dwLength; public uint dwMemoryLoad;//内存占用比 public UInt64 dwTotalPhys; //总的物理内存大小 public UInt64 dwAvailPhys; //可用的物理内存大小 public UInt64 dwTotalPageFile; public UInt64 dwAvailPageFile; //可用的页面文件大小 public UInt64 dwTotalVirtual; //返回调用进程的用户模式部分的全部可用虚拟地址空间 public UInt64 dwAvailVirtual; // 返回调用进程的用户模式部分的实际自由可用的虚拟地址空间 } [StructLayout(LayoutKind.Sequential)] public struct MEMORYSTATUSEX { public uint dwLength; public uint dwMemoryLoad; public ulong ullTotalPhys; public ulong ullAvailPhys; public ulong ullTotalPageFile; public ulong ullAvailPageFile; public ulong ullTotalVirtual; public ulong ullAvailVirtual; public ulong ullAvailExtendedVirtual; } /// <summary> /// 存放内存信息 /// </summary> public class MemoryInfo { public uint memoryLoad { get; set; }//返回00形式 public ulong totalPhys { get; set; } //以Bite为单位 public ulong availPhys { get; set; }//以Bite为单位 } public class MemoryMonitor { /// <summary> /// 获取内存信息 /// </summary> /// <param name="meminfo"></param> [DllImport("kernel32")] public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo); [DllImport("kernel32")] public static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX stat); /// <summary> /// 获取内存信息 /// </summary> /// <returns></returns> public static MemoryInfo getMemoryInfo() { MEMORYSTATUSEX memEx = new MEMORYSTATUSEX(); memEx.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX)); GlobalMemoryStatusEx(ref memEx); MemoryInfo memoryInfo = new MemoryInfo(); memoryInfo.memoryLoad = memEx.dwMemoryLoad; memoryInfo.availPhys = memEx.ullAvailPhys; memoryInfo.totalPhys = memEx.ullTotalPhys; return memoryInfo; } /// <summary> /// 获取指定驱动器的空间总大小(单位为B) /// </summary> /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 (大写)</param> /// <returns> </returns> public static long GetHardDiskSpace(string str_HardDiskName) { long totalSize = new long(); str_HardDiskName = str_HardDiskName + ":\"; System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); foreach (System.IO.DriveInfo drive in drives) { if (drive.Name == str_HardDiskName) { totalSize = drive.TotalSize; } } return totalSize; } /// <summary> /// 获取指定驱动器的剩余空间总大小(单位为B) /// </summary> /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param> /// <returns> </returns> public static long GetHardDiskFreeSpace(string str_HardDiskName) { long freeSpace = new long(); str_HardDiskName = str_HardDiskName + ":\"; System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives(); foreach (System.IO.DriveInfo drive in drives) { if (drive.Name == str_HardDiskName) { freeSpace = drive.TotalFreeSpace; } } return freeSpace; } } }
磁盘读
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { public sealed class DiskReadMonitor { private static readonly DiskReadMonitor instance = new DiskReadMonitor(); private PerformanceCounter counter; private DiskReadMonitor() { counter = new PerformanceCounter("PhysicalDisk", "Disk Read Bytes/sec", "_Total"); counter.NextValue(); System.Threading.Thread.Sleep(1000); } public static DiskReadMonitor getMonitor() { return instance; } public static float getValue() { return instance.counter.NextValue(); } } }
磁盘写
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { public sealed class DiskWriteMonitor { private static readonly DiskWriteMonitor instance = new DiskWriteMonitor(); private PerformanceCounter counter; private DiskWriteMonitor() { counter = new PerformanceCounter("PhysicalDisk", "Disk Write Bytes/sec", "_Total"); counter.NextValue(); System.Threading.Thread.Sleep(1000); } public static DiskWriteMonitor getMonitor() { return instance; } public static float getValue() { return instance.counter.NextValue(); } } }
网络收
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { public sealed class NetworkReceiveMonitor { private static readonly NetworkReceiveMonitor instance = new NetworkReceiveMonitor(); private List<PerformanceCounter> counters = new List<PerformanceCounter>(); private NetworkReceiveMonitor() { //初始化CPU计数器 //counter = new PerformanceCounter("Network Interface", "Bytes Received/sec", "*"); PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string[] instances = performanceCounterCategory.GetInstanceNames(); // 多网卡的要确定当前用的是哪个 //发送 foreach (string instance in instances) { PerformanceCounter counter = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); counters.Add(counter); counter.NextValue(); } System.Threading.Thread.Sleep(1000); } public static NetworkReceiveMonitor getMonitor() { return instance; } public static float getValue() { float value = 0; //return instance.counter.NextValue(); foreach (PerformanceCounter counter in instance.counters) { value += counter.NextValue(); } return value; } } }
网络发
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Monitor { public sealed class NetworkSendMonitor { private static readonly NetworkSendMonitor instance = new NetworkSendMonitor(); private List<PerformanceCounter> counters = new List<PerformanceCounter>(); private NetworkSendMonitor() { //初始化CPU计数器 //counter = new PerformanceCounter("Network Interface", "Bytes Received/sec", "*"); PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string[] instances = performanceCounterCategory.GetInstanceNames(); // 多网卡的要确定当前用的是哪个 //发送 foreach (string instance in instances) { PerformanceCounter counter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance); counters.Add(counter); counter.NextValue(); } System.Threading.Thread.Sleep(1000); } public static NetworkSendMonitor getMonitor() { return instance; } public static float getValue() { float value = 0; //return instance.counter.NextValue(); foreach (PerformanceCounter counter in instance.counters) { value += counter.NextValue(); } return value; } } }
用户登录
using Core.Security; using Core.Text; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using NLog; namespace EnvAgency.Extensions { public static class ImpersonateUserExt { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public static bool ImpersonateAdminUser(this ImpersonateUser user) { String name = ConfigurationManager.AppSettings["name"]; String pwd = ConfigurationManager.AppSettings["password"]; String domain = "."; Logger.Info("name:" + name + ",password:" + pwd); return user.ImpersonateValidUser(name, domain, pwd); } public static bool ImpersonateIISResetUser(this ImpersonateUser user) { string name, pwd, domain; name = "test"; pwd = "ymtcs2015"; domain = "."; return user.ImpersonateValidUser(name, domain, pwd); } } }
由于新建的线程都需要认证,所以新的采样线程都必须以管理员身份登录下
ImpersonateUser user = new ImpersonateUser();
ImpersonateUserExt.ImpersonateAdminUser(user);