码迷,mamicode.com
首页 > Windows程序 > 详细

C#监控-机器资源监控:CPU、内存、C盘、D盘资源监控及邮件预警

时间:2015-10-10 14:07:46      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:c#监控-机器资源监控:cpu、内存、c盘、d盘资源监控及邮件预警

针对CPU、内存、C盘、D盘资源监控及邮件预警,要实现在页面上配置资源监控选项,并且页面上能看到资源使用情况,超出阈值,邮件预警,效果图如下:


  1. 配置监控列表页

技术分享


2. 配置监控详情页

技术分享


3. 实时监控信息展示页技术分享


4. 监控信息图标展示

技术分享


5. 超出阈值发送预警邮件

技术分享


实现详情:

处于性能上的优化,每个监控都写成了个单例,并且通过多线程来取得各个监控数据


  1. CPU监控

    通过PerformanceCounter("Processor", "% Processor Time", "_Total")的NextValue()来获取获取cpu占用率,注意该Counter的第一个值是无效的0,要等一个时间片后方能取得有效值




CPUMonitor.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace XXX.XXX.QA.Platform.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();
        }
    }
}


2. 核数

由于有些指标要除以核数,所以这边也把核数读下


ProcessorCountMonitor.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace xxx.xxx.QA.Platform.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;
        }
    }
}


3.  内存、C、D盘监控监控

MemoryInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace xxx.xxx.QA.Platform.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()
        {
            MEMORY_INFO memInfo = new MEMORY_INFO();
            MEMORYSTATUSEX memEx = new MEMORYSTATUSEX();
            memEx.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
            GlobalMemoryStatusEx(ref memEx);
            GlobalMemoryStatus(ref memInfo);
            MemoryInfo memoryInfo = new MemoryInfo();
            memoryInfo.memoryLoad = memInfo.dwMemoryLoad;
            memoryInfo.availPhys = memInfo.dwAvailPhys;
            memoryInfo.totalPhys = memInfo.dwTotalPhys;
            return memoryInfo;
        }
        /// <summary>
        /// 获取内存占用率
        /// </summary>
        /// <returns></returns>
        public static uint GetMenoryLoad()
        {
            MEMORY_INFO memInfo = new MEMORY_INFO();
            MEMORYSTATUSEX memEx = new MEMORYSTATUSEX();
            memEx.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
            GlobalMemoryStatusEx(ref memEx);
            GlobalMemoryStatus(ref memInfo);
            return memInfo.dwMemoryLoad;
        }
        ///  <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;
        }
    }
}


4. 把所有这些监控指标放入一个Util中

MonitorUtil.cs

using NLog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace xxx.xxx.QA.Platform.Core.Monitor
{ 
    public class MonitorUtil
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        public static MachineMonitorInfo GetMachineMonitorInfo()
        {            
            MachineMonitorInfo info = new MachineMonitorInfo();
            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);
            // 获取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;
        }
        public static void GetCpu(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.CpuUsage = CPUMonitor.getValue();
            }
        }
        public static void GetCpuCount(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.CoreNumber = ProcessorCountMonitor.getValue();
            }
        }
        public static void GetMenoryAvaliable(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.MemoryAvailable = (MemoryMonitor.getMemoryInfo().availPhys/(1024*1024));
            }
        }
        public static void GetMenoryTotal(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.PhysicalMemory = (MemoryMonitor.getMemoryInfo().totalPhys / (1024 * 1024));
            }
        }
        public static void GetCAvaliable(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.CHardDiskFreeSpace = (MemoryMonitor.GetHardDiskFreeSpace("C") / (1024 * 1024));
            }
        }
        public static void GetCTotal(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.CHardDiskSpace = (MemoryMonitor.GetHardDiskSpace("C") / (1024 * 1024));
            }
        }
        public static void GetDAvaliable(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.DHardDiskFreeSpace = (MemoryMonitor.GetHardDiskFreeSpace("D") / (1024 * 1024));
            }
        }
        public static void GetDTotal(ref MachineMonitorInfo info)
        {
            lock (info)
            {
                info.DHardDiskSpace = (MemoryMonitor.GetHardDiskSpace("D") / (1024 * 1024));
            }
        }
    }
    [Serializable]
    public class MachineMonitorInfo
    {
        public float CpuUsage { get; set; }
        public int CoreNumber { get; set; }
        public float MemoryAvailable { get; set; }
        public float PhysicalMemory { get; set; }
        public float CHardDiskFreeSpace { get; set; }
        public float DHardDiskFreeSpace { get; set; }
        public float CHardDiskSpace { get; set; }
        public float DHardDiskSpace { get; set; }
    }
}



5. 新建个定时触发的task来监控


MonitorTask.cs

using FluentScheduler;
using NLog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace xxx.xxx.QA.Platform.EnvAgent.Services.Tasks
{
    public class MonitorTask : ITask
    {
        private static readonly object Locker = new object();
        private static bool _isRunning;
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        public void Execute()
        {
            if (_isRunning)
            {
                return;
            }
            ChangeState(true);
            try
            {
                Logger.Info("Monitor  start");
                EnvMachine envMachine = EnvMachineBiz.GetCurrentMachine();
                #region 机器监控
                EnvMachineMonitorConfig monitorConfig = EnvMachineMonitorConfigBiz.GetCurrentMachineMonitorConfig();
                // 判断监控开启
                if (monitorConfig != null && monitorConfig.Turnon == 1)
                {
                    //Logger.Info("监控开始时间:" + DateTime.Now.ToLocalTime());
                    // 获取机器实时监控信息
                    MachineMonitorInfo info = MonitorUtil.GetMachineMonitorInfo();                   
                    int cpu = (int)info.CpuUsage;
                    int memory = (int)((info.MemoryAvailable / info.PhysicalMemory) * 100);
                    int c = (int)(((info.CHardDiskSpace - info.CHardDiskFreeSpace) / info.CHardDiskSpace) * 100);
                    int d = (int)(((info.DHardDiskSpace - info.DHardDiskFreeSpace) / info.DHardDiskSpace) * 100);
                    DateTime time = DateTime.Now.ToLocalTime();
                    // 实时监控信息插入数据库
                    Logger.Info("Add Machine Monitor info (" + envMachine.Id + ", " + cpu + ", " + memory + ", " + time + ")");
                    EnvMachineMonitor newInfo = EnvMachineMonitorBiz.AddMachineMonitorInfo(envMachine.Id, cpu, memory, c, d, time);
                    //Logger.Info("Result: success, return EnvMachineMonitor id is " + newInfo.Id);
                    #region 机器预警
                    if (monitorConfig.Issendmail == 1)
                    {
                        DateTime dn = DateTime.Now.ToLocalTime();
                        //Logger.Info("现在时间:"+dn.ToLocalTime());
                        //Logger.Info("时间器时间:" + EmailSendTime.GetTime().ToLocalTime());
                        //Logger.Info("时间差:" + EmailSendTime.GetTimeSpanSecond(dn).ToString()+"s");
                        if (EmailSendTime.GetTimeSpanSecond(dn) > 15)
                        {
                            string reciever = monitorConfig.Recievers;
                            // 未设置情况默认为该账户
                            if (reciever == null || reciever.Equals(""))
                            {
                                reciever = "chenjz@Ctrip.com";
                            }
                            bool flag = false;
                            string body = envMachine.IP + "<br/><h3>时间</h3>" + time;
                            // CPU占用率过高报警:邮件告知
                            if (monitorConfig.Cpu != null && cpu > monitorConfig.Cpu || cpu > 95)
                            {
                                body += "<h3>CPU占用率超标</h3>CPU占用率: " + cpu + "(阈值:" + monitorConfig.Cpu + ")<br/><br/>";
                                flag = true;
                            }
                            // 内存占用率过高报警:邮件告知
                            if (memory > monitorConfig.Memery || memory > 95)
                            {
                                body += "<h3>内存占用率超标</h3>内存占用率:" + memory + "(阈值:" + monitorConfig.Memery + ")<br/><br/>";
                                flag = true;
                            }
                            // C盘占用率过高报警:邮件告知
                            if (c > monitorConfig.C || c > 95)
                            {
                                body += "<h3>C盘占用率超标</h3>C盘占用率:" + c + "(阈值:" + monitorConfig.C + ")<br/><br/>";
                                flag = true;
                            }
                            // D盘占用率过高报警:邮件告知
                            if (d > monitorConfig.D || d > 95)
                            {
                                body += "<h3>D盘占用率超标</h3>D盘占用率:" + d + "(阈值:" + monitorConfig.D + ")<br/><br/>";
                                flag = true;
                            }
                            if (flag)
                            {
                                Mail.SendMailWithHtml2(reciever, "机器预警:" + envMachine.Name, body, "xxx@Ctrip.com");
                                Logger.Info("Send 机器预警 mail:" + body);
                                EmailSendTime.SetTime(dn);
                                //Logger.Info("时间器时间设为:"+EmailSendTime.GetTime().ToLocalTime());                            
                                //Logger.Info("监控结束时间:" + DateTime.Now.ToLocalTime());
                            }
                        }
                    }
                    #endregion
                }
                #endregion
              
            }
            catch (Exception ex)
            {
                Logger.Error("MonitorTask异常信息:" + ex.ToString());
            }
            finally
            {
                ChangeState(false);
            }
        }
        private void ChangeState(bool running)
        {
            lock (Locker)
            {
                _isRunning = running;
            }
        }
   
    }
    public class AppPoolMonitorInfo
    {
        public string name {get;set;}
        public string turnOn {get;set;}
    }
}


6. 注册下task

public class TaskRegistry : Registry
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        public TaskRegistry()
        {
            Logger.Info("每1分钟执行下机器监控");
            Schedule<MonitorTask>().ToRunNow().AndEvery(1).Minutes();
        }
    }


存数据基本完成了,所用表如下:

配置表:

技术分享


监控数据表:

技术分享


前端展示:

用的引用有:

    @Styles.Render("~/Content/themes/metro/css")

    @Styles.Render("~/Content/themes/custom/chcore.css")

    @Styles.Render("~/Content/themes/fakeloader/fakeloader.css")


    @Scripts.Render("~/bundles/jquery")

    @Scripts.Render("~/Scripts/jquery.mousewheel.js")

    @Scripts.Render("~/Scripts/jquery.widget.min.1.9.1.js")

    @Scripts.Render("~/Scripts/highcharts4.1.8/highcharts.js")

    @Scripts.Render("~/Scripts/highcharts4.1.8/exporting.js")

    @Scripts.Render("~/Scripts/jquery.datatables.js")

    @Scripts.Render("~/Scripts/custom/chcoreui.js")

    @Scripts.Render("~/Scripts/custom/Chart.js")

    @Scripts.Render("~/Scripts/pages/envhomepage.js")

    @Scripts.Render("~/Scripts/control/fakeloader/fakeloader.min.js")


    @*@Scripts.Render("~/Scripts/combined/envhome.min.js")*@

    @Scripts.Render("~/Scripts/metro.min.js")


  1. 显示页面js

    图标用highcharts4.1.8实现

/// Machine-Infomation ///
var informationpage = {
    render: function () {
        var mainContainer = $(pageid.mainContent);
        mainContainer.empty();
        // toolbar
        mainContainer.append(‘<div id="iistoolbarsub" class=" margin20 no-margin-top"><button class="info" style="width:280px;" id="btnloadMachineMonitorInfo">载 入机器监控信息</button><div id="iiscontent"><div id="machinemonitor"></div></div></div>‘);
        // #region 注册载 入机器监控信息按钮事件
        $(‘#btnloadMachineMonitorInfo‘).click(function () {
            informationpage.getMachineMonitorInfo();
        });
      
    },
    IISReset: function (id) {
        var machine = pagefind.currentMachine();
        var sender = $("#" + id);
        var ip = machine.IP;
        
        iisresetpage.postReset(ip, sender);
    },
    
    getMachineMonitorInfo: function () {
        var container = $("#machinemonitor");
        var machine = pagefind.currentMachine();
        container.empty();
        if (machine == null) {
            $.note(null, ‘请先选择环境&机器‘, ‘error‘);
            return;
        }
        container.append(‘<div id="container1"></div><div id="container2" style="min-width: 310px; height: 400px; margin: 0 auto"></div>‘);
        var container1 = $("#container1");
        var container2 = $("#container2");
        chcoreui.attachLoader(container1, pageid.loader, 410, 100);
        var url = ‘http://‘ + machine.IP + ‘:8167/MachineMonitor/GetMachineMonitorInfo‘;
        var pack = new Object();
        pack.Token = $.readCookie(‘accessToken‘);
        var submitData = JSON.stringify(pack);
        $.ajax({
            type: "POST",
            url: url,
            data: submitData,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            success: function (results) {
                if (results.StateCode == 0) {
                    var bodyContent = ‘‘;
                    var memoryvalue = ((results.Data.PhysicalMemory - results.Data.MemoryAvailable) / results.Data.PhysicalMemory).toFixed(4) * 100;
                    var cvalue = (1 - results.Data.CHardDiskFreeSpace / results.Data.CHardDiskSpace).toFixed(4) * 100;
                    var dvalue =  (1-results.Data.DHardDiskFreeSpace / results.Data.DHardDiskSpace).toFixed(4) * 100 ;
                    bodyContent += ‘<tr><td >CPU</td><td><div class="progressbar_3"><div class="text">‘ + results.Data.CpuUsage + ‘%</div><div class="bar" style="width: ‘ + results.Data.CpuUsage + ‘%;"></div></div></div></td><td>‘ + results.Data.CoreNumber + ‘核</td><td></td><td><button class="warning" id="IISRestBtn" style="width:160px" onclick="informationpage.IISReset(id)">IISReset</button></td></tr>‘;
                    bodyContent += ‘<tr><td>内存</td><td><div class="progressbar_3"><div class="text">‘ + memoryvalue + ‘%</div><div class="bar" style="width: ‘ + memoryvalue + ‘%;"></div></div></div>  </td><td>‘ + results.Data.PhysicalMemory + ‘MB</td><td>‘ + results.Data.MemoryAvailable + ‘MB</td><td><!--<button class="warning" id="enlargeMenory" style="width:160px">申请扩充内存</button>--></td></tr>‘;
                    bodyContent += ‘<tr><td>C盘</td><td><div class="progressbar_3"><div class="text">‘ + cvalue + ‘%</div><div class="bar" style="width: ‘ + cvalue + ‘%;"></div></div></div> </td><td>‘ + results.Data.CHardDiskSpace + ‘MB</td><td>‘ + results.Data.CHardDiskFreeSpace + ‘MB</td><td><!--<button class="warning" id="enlargeMenory" style="width:160px">申请扩充C盘</button>--></td></tr>‘;
                    bodyContent += ‘<tr><td>D盘</td><td><div class="progressbar_3"><div class="text">‘ + dvalue + ‘%</div><div class="bar" style="width: ‘ + dvalue + ‘%;"></div></div></div></td><td>‘ + results.Data.DHardDiskSpace + ‘MB</td><td>‘ + results.Data.DHardDiskFreeSpace + ‘MB</td><td><!--<button class="warning" id="enlargeMenory" style="width:160px">申请扩充D盘</button>--></td></tr>‘;
                    
                    container1.html(‘<table class="table bordered striped hovered dataTable" cellspacing="0" id="machineMonitortable" style="text-align:center"><thead><tr><th>Name</th><th>占用百分比</th><th>总数</th><th>可用</th><th>Action</th></tr></thead><tbody>‘ + bodyContent + ‘</tbody></table>‘);
                    $(‘#machineMonitortable‘).dataTable({
                        "paging": false,
                        "searching": true,
                        "ordering": false,
                        "info": false,
                        "striped":false,
                        //"scrollY": "450px",
                        "scrollCollapse": true
                    });
                    $(‘#machineMonitortable‘).removeClass("striped");
                    //$(".progress-bar").onShow();
                }
            },
            error: function (xhr, status, error) {
                $.note(‘Error‘, ‘获取机器监控信息失败,请联系管理员(qyli).‘, ‘error‘);
            }
        });
    
        chcoreui.attachLoader(container2, pageid.loader, 410, 100);
        var url2 = ‘/MachineMonitor/GetMonitorInfos?ip=‘ + machine.IP;
        var pack = new Object();
        pack.Token = $.readCookie(‘accessToken‘);
        var submitData = JSON.stringify(pack);
        $.ajax({
            type: "POST",
            url: url2,
            data: submitData,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            success: function (results) {
                if (results.StateCode == 0) {
                   
                    $.cpuandmemorychart(container2, results.Data);
                }
                else {
                    $.note( ‘获取数据库中机器监控信息失败.‘+results.Message, ‘error‘);
                }
            },
            error: function (xhr, status, error) {
                $.note(‘Error‘, ‘获取数据库中机器监控信息失败‘, ‘error‘);
            }
        });
    },
    
};


图标显示js

(function ($){
    $.cpuandmemorychart = function (container, monitorinfo) {
        var time = new Array();
        var cpu = new Array();
        var memory = new Array();
        var c = new Array();
        var d = new Array();
        var i=0;
        $.each(monitorinfo, function (name, value) {
            time[i] = $.convertToDateStr(value.Time);
            cpu[i] = value.Cpu;
            memory[i] = value.Memory;
            c[i] = value.C;
            d[i] = value.D;
            i++;
        });
        container.highcharts({
            title: {
                text: ‘机器资源监控‘,
                x: -20 //center
            },
            subtitle: {
                text: ‘CPU、内存、C盘、D盘占用率‘,
                x: -20
            },
            xAxis: {
                categories: time
            },
            yAxis: {
                title: {
                    text: ‘百分比(%)‘
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: ‘#808080‘
                }]
            },
            tooltip: {
                valueSuffix: ‘%‘
            },
            legend: {
                layout: ‘vertical‘,
                align: ‘right‘,
                verticalAlign: ‘middle‘,
                borderWidth: 0
            },
            series: [{
                name: ‘CPU‘,
                data: cpu
            }, {
                name: ‘内存‘,
                data: memory
            }, {
                name: ‘C盘‘,
                data: c
            }, {
                name: ‘D盘‘,
                data: d
            }]
        });
    }
   
})(jQuery);


2. 配置页面js

var monitorconfigpage = {
    render: function () {
        var container = $(pageid.mainContent);
        container.empty();
        chcoreui.attachLoader(container, pageid.loader, 410, 100);
        var url = ‘/MachineMonitor/MonitorConfig‘;
        $.getJSON(‘/MachineMonitor/MonitorConfig‘, function (results) {
            if (results.StateCode == 0) {
                // 成功
                var bodyContent = ‘‘;
                $.each(results.Data, function (idx, item) {
                    bodyContent += ‘<tr><td style="text-align:center;"><button class="link invokebtn"><i class="icon-play"></i></button></td><td>‘ + item.MachineName + ‘</td><td style="text-align:center;">‘ + item.IPAddress + ‘</td><td style="text-align:center;">‘ + item.DomainName + ‘</td><td style="text-align:center;"><div class="progressbar_3"><div class="text">‘ + item.Cpu + ‘%</div><div class="bar" style="width:‘ + item.Cpu + ‘%;"></div></div></div></td><td style="text-align:center;"><div class="progressbar_3"><div class="text">‘ + item.Memory + ‘%</div><div class="bar" style="width:‘ + item.Memory + ‘%;"></div></div></div></td><td  style="text-align:center;"><input  class="turnonckbox" id="‘ + item.MachineName + ‘" type="checkbox"‘;
                    if (item.Turnon == true)
                    {
                        bodyContent += " checked "
                    }
                    bodyContent += ‘ data-size="mini" data-on-color="success"></td><td><button class="link monitorconfigbtn" id="‘ + item.MachineName + ‘" ><span class="mif-loop2"></span>配置</button>&nbsp<button class="iisresetbtn warning"><i class="icon-play on-left"></i>IISRESET</button><!--<button class="link monitormachinedetailbtn" id="‘ + item.MachineName + ‘" ><span class="mif-loop2"></span>查看机器详情</button><button class="link monitorapppooldetailbtn" id="‘ + item.MachineName + ‘" ><span class="mif-loop2"></span>查看程序池详情</button>--></td></tr>‘;
                });
                container.empty();
                container.html(‘<div style="margin-left:30px;"><button class="refreshbtn success" style="width:100px" ><i class="icon-cycle on-left"></i>刷新</button></div><table class="table bordered striped hovered dataTable" cellspacing="0" id="apppooltable"><thead><tr><th><button class="invokeallbtn warning"><i class="icon-play on-left"></i>唤醒监控</button></th><th>机器名</th><th>IP地址</th><th>环境名称</th><th>CPU占用比</th><th>内存占用比</th><th>开启监控</th><th>Actions</th></tr></thead><tbody>‘ + bodyContent + ‘</tbody></table>‘);
                $(‘#apppooltable‘).dataTable({
                    "paging": false,
                    "searching": true,
                    "ordering": true,
                    "info": "程序池信息表",
                    // "scrollY": "450px",
                    "scrollCollapse": true,
                    "dom": ‘<"tool1bar">fr1tip‘
                });
                $(".turnonckbox").change(function () {
                    var name = this.id;
                    if ($(‘#‘ + name + ‘‘).is(‘:checked‘)) {
                        monitorconfigpage.postTurnOn(name);
                    }
                    else {
                        monitorconfigpage.postTurnOff(name);
                    }
                    
                });
                $(".refreshbtn").click(function () {
                    monitorconfigpage.render();
                });
                $(".iisresetbtn").click(function () {
                    var parentobj = $(this).parent();
                    var ip = parentobj.parent().prev().prev().prev().prev().prev().text();
                    iisresetpage.postReset(ip, $(this))
                });
                $(".invokebtn").click(function () {
                    monitorconfigpage.startInvoke($(this));
                });
                $(".invokeallbtn").click(function () {
                    if (!$(this).hasClass(‘disabled‘)) {
                        var syncbtns = $(‘.invokebtn‘);
                        $(this).addClass(‘disabled‘);
                        $.each(syncbtns, function (idx, item) {
                            item.click();
                        });
                    }
                });
                $(".monitorconfigbtn").click(function () {
                    var name = this.id;
                    monitorconfigpage.getConfigDialog(name);
                });
            }
        });
   
    },
    getConfigDialog: function (name) {
        $.setting("settingDiv", "高级配置:" + name, "900px", "400px");
        chcoreui.attachLoader($("#settingDiv"), pageid.loader, 410, 100);
        $.getJSON(‘/MachineMonitor/GetMonitorSetting?name=‘ + name, null, function (data) {
                if (data) {
                    $("#settingDiv").empty();
                    $("#MonitorSettingTemplate").tmpl(data.Data).appendTo("#settingDiv");
                    if (data.Data.Issendmail == 1) {
                        $("#issendmail").attr("checked", true);
                    }
                    else {
                        $("#issendmail").attr("checked", false);
                    }
                    if (data.Data.Isdownloadpdump == 1) {
                        $("#isdownloadpdump").attr("checked", true);
                    }
                    else {
                        $("#isdownloadpdump").attr("checked", false);
                    }
                    if (data.Data.Isdownloadadump == 1) {
                        $("#isdownloadadump").attr("checked", true);
                    }
                    else {
                        $("#isdownloadadump").attr("checked", false);
                    }
                    $("#recievers").val(data.Data.Recievers);
                }
           
                $(‘#comitSettingBtn‘).click(function () {
                    monitorconfigpage.commitMonitorConfig(name);
                    $.Dialog.close();
                });
                $(‘#cancelCommitBtn‘).click(function () {
                    monitorconfigpage.getConfigDialog(name);
                });
                $(‘#closeCommitBtn‘).click(function () {
                    $.Dialog.close();
                });
        });
    },
    commitMonitorConfig: function (name) {
        var url = ‘/MachineMonitor/CommitMonitorConfig‘;
        var pack = new Object();
        pack.Token = $.readCookie(‘accessToken‘);
        pack.machineName = name;
        var config = new Object();
        config.cpu = $("#cpu").val();
        config.memery = $("#memery").val();
        config.c = $("#c").val();
        config.d = $("#d").val();
        if ($("#issendmail").is(‘:checked‘)) {
            config.issendmail = "1";
        }
        else {
            config.issendmail = "0";
        }
        config.recievers = $("#recievers").val();
        if ($("#isdownloadpdump").is(‘:checked‘)) {
            config.isdownloadpdump = 1;
        }
        else {
            config.isdownloadpdump = 0;
        }
        config.pcpu = $("#pcpu").val();
        if ($("#isdownloadadump").is(‘:checked‘)) {
            config.isdownloadadump = 1;
        }
        else {
            config.isdownloadadump = 0;
        }
        config.acpu = $("#acpu").val();
        pack.config = config;
        var submitData = JSON.stringify(pack);
        $.ajax({
            type: "POST",
            url: url,
            data: submitData,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            success: function (results) {
                if (results.data == "0")
                {
                    $.note(null,"修改"+name+"监控配置成功!");
                }
                else
                {
                    $.note(error, "修改" + name + "监控配置失败!");
                }
            },
            error: function (xhr, status, error) {
                $.note(error, "发送修改" + name + "监控配置请求失败!");
            }
        });
    },
    postTurnOn: function (name) {
        token = $.readCookie(‘accessToken‘);
        $.post("/MachineMonitor/TurnOnMonitor", { "name": name, "alis": token }, function (data) {
            if (data.StateCode == 0) {
                $.note(null, ‘开启监控‘ + name + ‘成功.‘);
            }
            else {
                $.note(null, ‘开启监控‘ + name + ‘失败.‘);
            }
        });
     
    },
    postTurnOff: function (name) {
            token = $.readCookie(‘accessToken‘);
            $.post("/MachineMonitor/TurnOffMonitor", { "name": name, "alis": token }, function (data) {
                if (data.StateCode == 0) {
                    $.note(null, ‘关闭监控‘ + name + ‘成功.‘);
                }
                else {
                    $.note(null, ‘关闭监控‘ + name + ‘失败.‘);
                }
            });
    },
    startInvoke: function (sender) {
        var parentObj = sender.parent();
        parentObj.empty();
        parentObj.append(‘<img src="../img/loading.jpg" style="width:30px;" id="iloader" />‘);
        var ip = parentObj.next().next().text();
        var url = ‘http://‘ + ip + ‘:8167/Monitor/Ping‘;
        $.ajax({
            type: "POST",
            url: url,
            data: null,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            success: function (results) {
                parentObj.empty();
                var reg = /\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}/;
                if (reg.test(results)) {
                    $.note(null, ‘唤醒‘+ip+‘监控成功!‘);
                    parentObj.append(‘<button class="link invokesuccessbtn" style="margin-left:30px;"><i class="icon-checkmark fg-green" style="margin-left:45px;"></i></button>‘);
                    $(‘.invokesuccessbtn‘).click(function () {
                        monitorconfigpage.startInvoke($(this));
                    });
                } else {
                    $.note(‘Error‘, ‘唤醒‘ + ip + ‘失败!‘, ‘error‘);
                    parentObj.append(‘<button class="link invokefailbtn" style="margin-left:30px;"><i class="icon-cancel-2 fg-red"></i></button>‘);
                    $(‘.invokefailbtn‘).click(function () {
                        monitorconfigpage.startInvoke($(this));
                    });
                }
            },
            error: function (xhr, status, error) {
                $.note(‘Error‘, ‘唤醒‘ + ip + ‘失败!‘ + error, ‘error‘);
                parentObj.empty();
                parentObj.append(‘<button class="link invokefailbtn" style="margin-left:30px;"><i class="icon-cancel-2 fg-red"></i></button>‘);
                $(‘.invokefailbtn‘).click(function () {
                    monitorconfigpage.startInvoke($(this));
                });
            }
        });
    }
}




本文出自 “爱工作爱生活” 博客,请务必保留此出处http://4453154.blog.51cto.com/4443154/1701503

C#监控-机器资源监控:CPU、内存、C盘、D盘资源监控及邮件预警

标签:c#监控-机器资源监控:cpu、内存、c盘、d盘资源监控及邮件预警

原文地址:http://4453154.blog.51cto.com/4443154/1701503

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!