懒得勤快 3 tahun lalu
induk
melakukan
d0740e76fd

+ 8 - 2
src/Masuit.MyBlogs.Core/Common/PerfCounter.cs

@@ -1,5 +1,7 @@
-using System.ComponentModel.DataAnnotations.Schema;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
 using System.Diagnostics;
+using System.Net.Sockets;
 using Masuit.MyBlogs.Core.Infrastructure;
 using Masuit.Tools;
 using Masuit.Tools.DateTimeExt;
@@ -62,7 +64,8 @@ public interface IPerfCounter
             DiskRead = read,
             DiskWrite = write,
             Download = down,
-            Upload = up
+            Upload = up,
+            ServerIP = SystemInfo.GetLocalUsedIP(AddressFamily.InterNetwork).ToString()
         };
     }
 
@@ -171,6 +174,9 @@ public static class PerfCounterServiceExtension
 [Table(nameof(PerformanceCounter))]
 public class PerformanceCounter
 {
+    [StringLength(128)]
+    public string ServerIP { get; set; }
+
     /// <summary>
     /// 当前时间戳
     /// </summary>

+ 1 - 1
src/Masuit.MyBlogs.Core/Controllers/AdvertisementController.cs

@@ -71,7 +71,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 where = where.And(p => p.Title.Contains(kw) || p.Description.Contains(kw) || p.Url.Contains(kw));
             }
 
-            var list = AdsService.GetQuery(where).OrderByDescending(p => p.Status == Status.Available).ThenByDescending(a => a.Price).ProjectTo<AdvertisementViewModel>(MapperConfig).NotCacheable().ToPagedList(page, size);
+            var list = AdsService.GetQuery(where).OrderByDescending(p => p.Status == Status.Available).ThenByDescending(a => a.Price).ThenByDescending(a => a.Id).ProjectTo<AdvertisementViewModel>(MapperConfig).NotCacheable().ToPagedList(page, size);
             return Ok(list);
         }
 

+ 14 - 4
src/Masuit.MyBlogs.Core/Controllers/SystemController.cs

@@ -16,7 +16,9 @@ using Newtonsoft.Json.Linq;
 using System.ComponentModel.DataAnnotations;
 using System.Diagnostics;
 using System.Net;
+using System.Net.Sockets;
 using System.Text;
+using Masuit.Tools.Hardware;
 using PerformanceCounter = Masuit.MyBlogs.Core.Common.PerformanceCounter;
 
 namespace Masuit.MyBlogs.Core.Controllers
@@ -33,13 +35,20 @@ namespace Masuit.MyBlogs.Core.Controllers
 
         public IPerfCounter PerfCounter { get; set; }
 
+        public ActionResult GetServers()
+        {
+            var servers = PerfCounter.CreateDataSource().Select(c => c.ServerIP).Distinct().ToArray();
+            return Ok(servers);
+        }
+
         /// <summary>
         /// 获取历史性能计数器
         /// </summary>
         /// <returns></returns>
-        public IActionResult GetCounterHistory()
+        public IActionResult GetCounterHistory(string ip = null)
         {
-            var counters = PerfCounter.CreateDataSource();
+            ip = ip.IfNullOrEmpty(() => SystemInfo.GetLocalUsedIP(AddressFamily.InterNetwork).ToString());
+            var counters = PerfCounter.CreateDataSource().Where(c => c.ServerIP == ip);
             var count = counters.Count();
             var ticks = count switch
             {
@@ -51,7 +60,8 @@ namespace Masuit.MyBlogs.Core.Controllers
                 > 200000 and <= 300000 => 72,
                 _ => count
             } * 10000;
-            var list = count < 5000 ? counters.ToList() : counters.GroupBy(c => c.Time / ticks).Select(g => new PerformanceCounter
+
+            var list = count < 5000 ? counters.OrderBy(c => c.Time).ToList() : counters.GroupBy(c => c.Time / ticks).Select(g => new PerformanceCounter
             {
                 Time = g.Key * ticks,
                 CpuLoad = g.Average(c => c.CpuLoad),
@@ -60,7 +70,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 Download = g.Average(c => c.Download),
                 Upload = g.Average(c => c.Upload),
                 MemoryUsage = g.Average(c => c.MemoryUsage)
-            }).ToList();
+            }).OrderBy(c => c.Time).ToList();
             return Ok(new
             {
                 cpu = list.Select(c => new[]

+ 6 - 5
src/Masuit.MyBlogs.Core/Extensions/Firewall/IRequestLogger.cs

@@ -10,14 +10,14 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall;
 
 public interface IRequestLogger
 {
-    void Log(string ip, string url, string userAgent);
+    void Log(string ip, string url, string userAgent, string traceid);
 
     void Process();
 }
 
 public class RequestNoneLogger : IRequestLogger
 {
-    public void Log(string ip, string url, string userAgent)
+    public void Log(string ip, string url, string userAgent, string traceid)
     {
     }
 
@@ -28,7 +28,7 @@ public class RequestNoneLogger : IRequestLogger
 
 public class RequestFileLogger : IRequestLogger
 {
-    public void Log(string ip, string url, string userAgent)
+    public void Log(string ip, string url, string userAgent, string traceid)
     {
         TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog()
         {
@@ -59,14 +59,15 @@ public class RequestDatabaseLogger : IRequestLogger
         _dataContext = dataContext;
     }
 
-    public void Log(string ip, string url, string userAgent)
+    public void Log(string ip, string url, string userAgent, string traceid)
     {
         Queue.Enqueue(new RequestLogDetail
         {
             Time = DateTime.Now,
             UserAgent = userAgent,
             RequestUrl = url,
-            IP = ip
+            IP = ip,
+            TraceId = traceid
         });
     }
 

+ 2 - 1
src/Masuit.MyBlogs.Core/Extensions/Firewall/RequestInterceptMiddleware.cs

@@ -98,7 +98,8 @@ public class RequestInterceptMiddleware
                 var q = request.QueryString.Value.Trim('?');
                 requestUrl = requestUrl.Replace(q, q.Split('&').Where(s => !s.StartsWith("cid") && !s.StartsWith("uid")).Join("&"));
             }
-            _requestLogger.Log(ip, requestUrl, context.Request.Headers[HeaderNames.UserAgent]);
+
+            _requestLogger.Log(ip, requestUrl, context.Request.Headers[HeaderNames.UserAgent], context.Session.Id);
         }
 
         if (string.IsNullOrEmpty(context.Session.Get<string>(SessionKey.TimeZone)))

+ 8 - 1
src/Masuit.MyBlogs.Core/Infrastructure/LoggerDbContext.cs

@@ -3,6 +3,8 @@ using Microsoft.EntityFrameworkCore;
 using System.Reflection;
 using Masuit.MyBlogs.Core.Common;
 using Microsoft.EntityFrameworkCore.Metadata;
+using Lucene.Net.Sandbox.Queries;
+using OpenXmlPowerTools;
 
 namespace Masuit.MyBlogs.Core.Infrastructure;
 
@@ -61,7 +63,12 @@ public static class TimeScaleExtensions
                         }
                         else
                         {
-                            context.Database.ExecuteSqlRaw($"SELECT create_hypertable('\"{tableName}\"', '{columnName}', chunk_time_interval => 100000);");
+                            context.Database.ExecuteSqlRaw($"SELECT create_hypertable('\"{tableName}\"', '{columnName}', chunk_time_interval => 604800000000);");
+                            context.Database.ExecuteSqlRaw($@"CREATE FUNCTION current_microfortnight() RETURNS BIGINT
+                            LANGUAGE SQL STABLE AS $$
+                               SELECT CAST(1209600 * EXTRACT(EPOCH FROM CURRENT_TIME) / 1000000 AS BIGINT)
+                             $$;
+                            SELECT set_integer_now_func('""{columnName}""', 'current_microfortnight');");
                         }
                     }
                 }

+ 3 - 0
src/Masuit.MyBlogs.Core/Models/Entity/RequestLogDetail.cs

@@ -34,4 +34,7 @@ public class RequestLogDetail
 
     [StringLength(256)]
     public string Network { get; set; }
+
+    [StringLength(128)]
+    public string TraceId { get; set; }
 }

+ 5 - 1
src/Masuit.MyBlogs.Core/Models/ViewModel/PostDataModel.cs

@@ -84,5 +84,9 @@
         /// </summary>
         public string LimitDesc { get; set; }
 
+        /// <summary>
+        /// 提交人IP地址
+        /// </summary>
+        public string IP { get; set; }
     }
-}
+}

+ 5 - 2
src/Masuit.MyBlogs.Core/Views/Dashboard/Counter.cshtml

@@ -8,8 +8,9 @@
 <html>
 <head>
     <title>服务器性能监控</title>
-    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
-    <link href="https://cdn.staticfile.org/limonte-sweetalert2/6.6.9/sweetalert2.min.css" rel="stylesheet">
+    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" async defer>
+    <link href="https://cdn.staticfile.org/limonte-sweetalert2/6.6.9/sweetalert2.min.css" rel="stylesheet" async defer>
+    <link href="~/Assets/layui/css/layui.min.css" rel="stylesheet" async defer>
 </head>
 <body>
     <div class="container-fluid">
@@ -18,6 +19,8 @@
     <script src="/_framework/blazor.server.js"></script>
     <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
     <script src="https://cdn.staticfile.org/limonte-sweetalert2/6.6.10/sweetalert2.min.js"></script>
+    <script src="~/Assets/layui/layui.js"></script>
+    <script src="https://maplemei.gitee.io/xm-select/xm-select.js"></script>
     <script src="~/Scripts/global/counter.js"></script>
 </body>
 </html>

+ 9 - 6
src/Masuit.MyBlogs.Core/Views/Dashboard/Counter.razor

@@ -5,9 +5,7 @@
 @using Masuit.Tools
 @using System.IO
 @using Collections.Pooled
-@using Masuit.MyBlogs.Core.Infrastructure
 @using Masuit.Tools.Logging
-@using Microsoft.EntityFrameworkCore
 @using PerformanceCounter = Masuit.MyBlogs.Core.Common.PerformanceCounter
 @inject IPerfCounter PerfCounter;
 @inject IJSRuntime JS;
@@ -114,6 +112,9 @@
     <div class="page-header">
         <h3 class="text-center">性能实时监控</h3>
     </div>
+    <div class="row">
+        <div id="servers" style="width: 200px"></div>
+    </div>
     <div class="row">
         <div id="container" class="col-md-3" style="height: 400px;"></div>
         <div id="container-cpu" class="col-md-5" style="height: 400px;"></div>
@@ -123,11 +124,12 @@
 
 @code {
     private string bootTime;
+    private string ip=SystemInfo.GetLocalUsedIP(AddressFamily.InterNetwork).ToString();
     private string runningTime;
     private readonly CpuInfo cpu = SystemInfo.GetCpuInfo()[0];
     private readonly RamInfo memory = SystemInfo.GetRamInfo();
     private readonly IList<string> macs = SystemInfo.GetMacAddress();
-    private readonly IList<string> ips = SystemInfo.GetLocalIPs().OrderBy(u => u.Address.AddressFamily != AddressFamily.InterNetwork).Select(a => a.Address.ToString()).ToPooledList();
+    private readonly IList<string> ips = SystemInfo.GetLocalIPs().OrderBy(u => u.Address.AddressFamily != AddressFamily.InterNetwork).Select(a => a.Address.ToString()).ToList();
     private readonly DriveInfo[] _driveInfos = DriveInfo.GetDrives().Where(d => d.IsReady).ToArray();
 
     protected override void OnInitialized()
@@ -140,7 +142,8 @@
 
     protected override async Task OnAfterRenderAsync(bool firstRender)
     {
-        await JS.InvokeVoidAsync("showLine");
+        await JS.InvokeVoidAsync("getServers");
+        await JS.InvokeVoidAsync("showLine",ip);
     }
 
     [JSInvokable]
@@ -160,10 +163,10 @@
         Windows.ClearMemorySilent();
         JS.InvokeVoidAsync("showSuccess");
     }
-
+    
     public Dictionary<string, dynamic> GetCounterPercent()
     {
-        var counters = PerfCounter.CreateDataSource().OrderBy(c => Guid.NewGuid()).Take(5000).ToList();
+        using var counters = PerfCounter.CreateDataSource().Where(c => c.ServerIP==ip).OrderBy(c => Guid.NewGuid()).Take(5000).ToPooledList();
         var count = counters.Count();
         return new()
         {

+ 67 - 33
src/Masuit.MyBlogs.Core/wwwroot/Scripts/global/counter.js

@@ -145,8 +145,42 @@ function showIO(data) {
     return myChart;
 }
 
-function showLine() {
-    window.fetch("/system/GetCounterHistory", {
+function getServers() {
+    window.fetch("/system/GetServers", {
+        credentials: 'include',
+        method: 'GET',
+        mode: 'cors'
+    }).then(function(response) {
+        return response.json();
+    }).then(function(data) {
+        var arr=[];
+        for (var i = 0; i < data.length; i++) {
+            arr.push({name:data[i],value:data[i]});
+        }
+
+        xmSelect.render({
+            el: '#servers',
+            tips: '请选择服务器',
+            model: {
+                 icon: 'hidden',
+                 label: { type: 'text' }
+            },
+            radio: true,
+            clickClose: true,
+            autoRow: true, //选项过多,自动换行
+            data:arr,
+            on: function (data) {
+                if (data.arr.length>0) {
+                    showLine(data.arr[0].value);
+                }
+            }
+        });
+    });
+}
+
+function showLine(ip) {
+    clearInterval(window.counterInterval);
+    window.fetch("/system/GetCounterHistory?ip="+ip, {
         credentials: 'include',
         method: 'GET',
         mode: 'cors'
@@ -238,38 +272,38 @@ function showLine() {
         });
         var rateChart = showSpeed();
         var ioChart = showIO(data);
-        setInterval(function() {
-                DotNet.invokeMethodAsync('Masuit.MyBlogs.Core', 'GetCurrentPerformanceCounter').then(item => {
-                    data.cpu.push([item.time, item.cpuLoad.toFixed(2)]);
-                    data.mem.push([item.time, item.memoryUsage.toFixed(2)]);
-                    data.read.push([item.time, item.diskRead.toFixed(2)]);
-                    data.write.push([item.time, item.diskWrite.toFixed(2)]);
-                    data.up.push([item.time, item.upload.toFixed(2)]);
-                    data.down.push([item.time, item.download.toFixed(2)]);
-                    myChart.setOption({
-                        series: [{
-                                data: data.cpu
-                            }, {
-                                data: data.mem
-                            }]
-                    });
-                    ioChart.setOption({
-                        series: [{
-                                data: data.read
-                            }, {
-                                data: data.write
-                            }, {
-                                data: data.up
-                            }, {
-                                data: data.down
-                            }]
-                    });
-                    let option = rateChart.getOption();
-                    option.series[0].data[0].value = item.cpuLoad.toFixed(2);
-                    option.series[0].data[1].value = item.memoryUsage.toFixed(2);
-                    rateChart.setOption(option, true);
+        window.counterInterval = setInterval(function() {
+            DotNet.invokeMethodAsync('Masuit.MyBlogs.Core', 'GetCurrentPerformanceCounter').then(item => {
+                data.cpu.push([item.time, item.cpuLoad.toFixed(2)]);
+                data.mem.push([item.time, item.memoryUsage.toFixed(2)]);
+                data.read.push([item.time, item.diskRead.toFixed(2)]);
+                data.write.push([item.time, item.diskWrite.toFixed(2)]);
+                data.up.push([item.time, item.upload.toFixed(2)]);
+                data.down.push([item.time, item.download.toFixed(2)]);
+                myChart.setOption({
+                    series: [{
+                        data: data.cpu
+                    }, {
+                        data: data.mem
+                    }]
+                });
+                ioChart.setOption({
+                    series: [{
+                        data: data.read
+                    }, {
+                        data: data.write
+                    }, {
+                        data: data.up
+                    }, {
+                        data: data.down
+                    }]
                 });
-            }, 2000);
+                let option = rateChart.getOption();
+                option.series[0].data[0].value = item.cpuLoad.toFixed(2);
+                option.series[0].data[1].value = item.memoryUsage.toFixed(2);
+                rateChart.setOption(option, true);
+            });
+        }, 2000);
     }).catch(function(e) {
         console.error(e);
     });

+ 1 - 1
src/Masuit.MyBlogs.Core/wwwroot/ng-views/controllers/notice.js

@@ -5,7 +5,7 @@
         $scope.get("/notice/get/" + $scope.notice.Id, function (res) {
             $scope.notice = res.Data;
             if ($scope.notice.StartTime+$scope.notice.EndTime) {
-                $scope.notice.Range=new Date($scope.notice.StartTime).Format("yyyy-MM-dd")+" - "+new Date($scope.notice.EndTime).Format("yyyy-MM-dd");
+                $scope.notice.Range=new Date($scope.notice.StartTime).Format("yyyy-MM-dd hh:mm:ss")+" - "+new Date($scope.notice.EndTime).Format("yyyy-MM-dd hh:mm:ss");
             } else {
                 delete $scope.notice.StartTime;
                 delete $scope.notice.EndTime;

+ 3 - 3
src/Masuit.MyBlogs.Core/wwwroot/ng-views/controllers/partner.js

@@ -162,7 +162,7 @@
     }
     $scope.add = function() {
         $scope.partner = {
-            ExpireTime:"2049-12-31"
+            ExpireTime:"2049-12-31 23:59:59"
         };
         $scope.isAdd = true;
         $scope.allowUpload=false;
@@ -194,7 +194,7 @@
 
     $scope.edit = function (item) {
         $scope.partner = angular.copy(item);
-        $scope.partner.ExpireTime=$scope.partner.ExpireTime == null?"2049-12-31":new Date($scope.partner.ExpireTime).Format("yyyy-MM-dd hh:mm:ss");
+        $scope.partner.ExpireTime=$scope.partner.ExpireTime == null?"2049-12-31 23:59:59":new Date($scope.partner.ExpireTime).Format("yyyy-MM-dd hh:mm:ss");
         $scope.isAdd = false;
         $scope.allowUpload=false;
         layer.closeAll();
@@ -230,7 +230,7 @@
     $scope.copy = function (item) {
         $scope.partner = angular.copy(item);
         delete $scope.partner.Id;
-        $scope.partner.ExpireTime=$scope.partner.ExpireTime == null?"2049-12-31":new Date($scope.partner.ExpireTime).Format("yyyy-MM-dd hh:mm:ss");
+        $scope.partner.ExpireTime=$scope.partner.ExpireTime == null?"2049-12-31 23:59:59":new Date($scope.partner.ExpireTime).Format("yyyy-MM-dd hh:mm:ss");
         $scope.isAdd = true;
         $scope.allowUpload=false;
         layer.closeAll();

+ 3 - 2
src/Masuit.MyBlogs.Core/wwwroot/ng-views/views/post/pending.html

@@ -28,8 +28,9 @@
                 {{row.Email}}
                 <button class="badge btn btn-primary" ng-click="addToBlock(row)">标记为恶意提交</button>
             </td>
-            <td title="'标签'">
-                {{row.Label}}
+            <td title="'提交IP'">
+                {{row.IP}}
+                <button class="badge btn btn-primary pull-right" ng-click="addToBlackList(row.IP)">黑名单</button>
             </td>
             <td title="'操作'" style="width: 155px;">
                 <div class="btn-group">