中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警

發布時間:2020-04-02 23:54:07 來源:網絡 閱讀:14229 作者:sudachenjiazhu 欄目:web開發

針對CPU、內存、C盤、D盤資源監控及郵件預警,要實現在頁面上配置資源監控選項,并且頁面上能看到資源使用情況,超出閾值,郵件預警,效果圖如下:


  1. 配置監控列表頁

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


2. 配置監控詳情頁

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


3. 實時監控信息展示頁C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


4. 監控信息圖標展示

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


5. 超出閾值發送預警郵件

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


實現詳情:

處于性能上的優化,每個監控都寫成了個單例,并且通過多線程來取得各個監控數據


  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/><h4>時間</h4>" + time;
                            // CPU占用率過高報警:郵件告知
                            if (monitorConfig.Cpu != null && cpu > monitorConfig.Cpu || cpu > 95)
                            {
                                body += "<h4>CPU占用率超標</h4>CPU占用率: " + cpu + "(閾值:" + monitorConfig.Cpu + ")<br/><br/>";
                                flag = true;
                            }
                            // 內存占用率過高報警:郵件告知
                            if (memory > monitorConfig.Memery || memory > 95)
                            {
                                body += "<h4>內存占用率超標</h4>內存占用率:" + memory + "(閾值:" + monitorConfig.Memery + ")<br/><br/>";
                                flag = true;
                            }
                            // C盤占用率過高報警:郵件告知
                            if (c > monitorConfig.C || c > 95)
                            {
                                body += "<h4>C盤占用率超標</h4>C盤占用率:" + c + "(閾值:" + monitorConfig.C + ")<br/><br/>";
                                flag = true;
                            }
                            // D盤占用率過高報警:郵件告知
                            if (d > monitorConfig.D || d > 95)
                            {
                                body += "<h4>D盤占用率超標</h4>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();
        }
    }


存數據基本完成了,所用表如下:

配置表:

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


監控數據表:

C#監控-機器資源監控:CPU、內存、C盤、D盤資源監控及郵件預警


前端展示:

用的引用有:

    @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"  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" ></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" ></div></div></div></td><td>' + results.Data.CoreNumber + '核</td><td></td><td><button class="warning" id="IISRestBtn"  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" ></div></div></div>  </td><td>' + results.Data.PhysicalMemory + 'MB</td><td>' + results.Data.MemoryAvailable + 'MB</td><td><!--<button class="warning" id="enlargeMenory" >申請擴充內存</button>--></td></tr>';
                    bodyContent += '<tr><td>C盤</td><td><div class="progressbar_3"><div class="text">' + cvalue + '%</div><div class="bar" ></div></div></div> </td><td>' + results.Data.CHardDiskSpace + 'MB</td><td>' + results.Data.CHardDiskFreeSpace + 'MB</td><td><!--<button class="warning" id="enlargeMenory" >申請擴充C盤</button>--></td></tr>';
                    bodyContent += '<tr><td>D盤</td><td><div class="progressbar_3"><div class="text">' + dvalue + '%</div><div class="bar" ></div></div></div></td><td>' + results.Data.DHardDiskSpace + 'MB</td><td>' + results.Data.DHardDiskFreeSpace + 'MB</td><td><!--<button class="warning" id="enlargeMenory" >申請擴充D盤</button>--></td></tr>';
                    
                    container1.html('<table class="table bordered striped hovered dataTable" cellspacing="0" id="machineMonitortable" ><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 ><button class="link invokebtn"><i class="icon-play"></i></button></td><td>' + item.MachineName + '</td><td >' + item.IPAddress + '</td><td >' + item.DomainName + '</td><td ><div class="progressbar_3"><div class="text">' + item.Cpu + '%</div><div class="bar" ></div></div></div></td><td ><div class="progressbar_3"><div class="text">' + item.Memory + '%</div><div class="bar" ></div></div></div></td><td  ><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 ><button class="refreshbtn success"  ><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"  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" ><i class="icon-checkmark fg-green" ></i></button>');
                    $('.invokesuccessbtn').click(function () {
                        monitorconfigpage.startInvoke($(this));
                    });
                } else {
                    $.note('Error', '喚醒' + ip + '失敗!', 'error');
                    parentObj.append('<button class="link invokefailbtn" ><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" ><i class="icon-cancel-2 fg-red"></i></button>');
                $('.invokefailbtn').click(function () {
                    monitorconfigpage.startInvoke($(this));
                });
            }
        });
    }
}




向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

屯门区| 灵璧县| 夏河县| 惠州市| 扶风县| 竹北市| 红桥区| 甘德县| 利川市| 额济纳旗| 嘉荫县| 庄河市| 资讯| 松江区| 雷州市| 南溪县| 城步| 罗平县| 禄劝| 大安市| 吴川市| 大城县| 长宁区| 孝感市| 麟游县| 曲靖市| 阳山县| 比如县| 甘肃省| 伽师县| 扶风县| 吉首市| 崇义县| 洪泽县| 连山| 绥宁县| 濉溪县| 张家口市| 吉木乃县| 六安市| 比如县|