BILogAnalyseService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using Azure.Storage.Blobs;
  2. using Azure.Storage.Blobs.Models;
  3. using Azure.Storage.Blobs.Specialized;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.SDK.Context.BI;
  12. using TEAMModelOS.SDK.DI;
  13. using TEAMModelOS.SDK.Extension;
  14. using TEAMModelOS.SDK.Models.Cosmos.BI;
  15. namespace TEAMModelOS.SDK.Models.Service.BI
  16. {
  17. public static class BILogAnalyseService
  18. {
  19. /// <summary>
  20. /// 读取全部的防火墙日志文件并分析保存至
  21. /// </summary>
  22. /// <param name="_azureStorage"></param>
  23. /// <param name="site"></param>
  24. /// <returns></returns>
  25. public static async Task<(List<RecCnt> recCnts ,List<string> saveUrls)> GetAllLogAnalyse(AzureStorageFactory _azureStorage,string site = null)
  26. {
  27. var blobClient = _azureStorage.GetBlobContainerClient($"insights-logs-applicationgatewayfirewalllog", name: BIConst.LogChina);
  28. if ($"{site}".Equals(BIConst.Global))
  29. {
  30. blobClient = _azureStorage.GetBlobContainerClient($"insights-logs-applicationgatewayfirewalllog", name: BIConst.Global);
  31. }
  32. List<RecCnt> recCnts = new();
  33. List<string> urls = new();
  34. //地址: y={year}/m={month}/d={day}/h={hour}/m=00/PT1H.json
  35. string logName = "resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/OSFIREWARE";
  36. await foreach (BlobItem blobItem in blobClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, logName))
  37. {
  38. StringBuilder visits = new("[");
  39. BlobClient tempBlobClient = blobClient.GetBlobClient(blobItem.Name);
  40. BlobDownloadInfo download = tempBlobClient.Download();
  41. var content = download.Content;
  42. string text;
  43. using (var streamReader = new StreamReader(content))
  44. {
  45. while ((text = streamReader.ReadLine()) != null)
  46. {
  47. if (streamReader.EndOfStream)
  48. visits.Append($"{text.ToString()}");
  49. else
  50. visits.Append($"{text.ToString()},");
  51. }
  52. visits.Append("]");
  53. streamReader.Close();
  54. }
  55. string input = visits.ToString();
  56. List<AGInfo> aGInfos = input.ToObject<List<AGInfo>>();
  57. DateTimeOffset dtime = DateTimeOffset.UtcNow;
  58. string cHour = dtime.ToString("yyyyMMddHH");
  59. string cDay = dtime.ToString("yyyyMMdd");
  60. if (aGInfos.Count > 0)
  61. {
  62. cHour = aGInfos.Select(s => DateTimeOffset.Parse(s.time).ToString("yyyyMMddHH")).First();
  63. cDay = aGInfos.Select(s => DateTimeOffset.Parse(s.time).ToString("yyyyMMdd")).First();
  64. }
  65. RecCnt saveCnts = new();
  66. List<RecAppGWInfo> recInfo = aGInfos.Select(s => new RecAppGWInfo { hour = cHour, ip = s.properties.clientIp, api = s.properties.requestUri.Split("?").ToList().Count() > 1 ? s.properties.requestUri.Split("?").ToList()[0] : s.properties.requestUri, hostName = s.properties.hostname }).ToList();
  67. List<RecApiCnt> apiCnt = recInfo.GroupBy(a => a.api).Select(g => new RecApiCnt { api = g.Key, count = g.Count(), hour = cHour, hostName = g.Select(h => h.hostName).Distinct().ToList(), ip = g.Select(i => i.ip).Distinct().ToList() }).ToList();
  68. saveCnts.apiCnt = apiCnt;
  69. List<RecIpCnt> ipCnt = recInfo.GroupBy(a => a.ip).Select(g => new RecIpCnt { ip = g.Key, count = g.Count(), hour = cHour, hostName = g.Select(h => h.hostName).Distinct().ToList(), api = g.Select(i => i.api).Distinct().ToList() }).ToList();
  70. saveCnts.ipCnt = ipCnt;
  71. recCnts.Add(saveCnts);
  72. ////保存存至Blob文件
  73. var url = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(saveCnts.ToJsonString(), $"visitCnt/{cDay}", $"{cHour}.json");
  74. urls.Add(url);
  75. }
  76. return (recCnts, urls);
  77. }
  78. /// <summary>
  79. /// 通过路径获取日志文件并分析结果
  80. /// </summary>
  81. /// <param name="_azureStorage"></param>
  82. /// <param name="path">防火墙路径</param>
  83. /// <param name="connectStr">连接字串</param>
  84. /// <returns></returns>
  85. public static async Task<(List<RecCnt> recCnts, List<string> saveUrls)> GetPathAnalyse(AzureStorageFactory _azureStorage,IPSearcher _ipSearcher,DingDing _dingDing, string path, string connectName)
  86. {
  87. List<RecCnt> recCnts = new();
  88. List<string> urls = new();
  89. DateTimeOffset dtime = DateTimeOffset.UtcNow;
  90. string cDay = dtime.ToString("yyyyMMdd");
  91. try {
  92. var blobClient = _azureStorage.GetBlobContainerClient($"insights-logs-applicationgatewayfirewalllog", name: connectName);
  93. await foreach (BlobItem blobItem in blobClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, path))
  94. {
  95. StringBuilder visits = new("[");
  96. //BlobClient tempBlobClient = blobClient.GetBlobClient(blobItem.Name);
  97. //BlobDownloadInfo download = tempBlobClient.Download();
  98. BlobDownloadInfo download = blobClient.GetBlobClient(blobItem.Name).Download();
  99. var content = download.Content;
  100. string text;
  101. using (var streamReader = new StreamReader(content))
  102. {
  103. while ((text = streamReader.ReadLine()) != null)
  104. {
  105. if (streamReader.EndOfStream)
  106. visits.Append($"{text.ToString()}");
  107. else
  108. visits.Append($"{text.ToString()},");
  109. }
  110. visits.Append("]");
  111. streamReader.Close();
  112. }
  113. string input = visits.ToString();
  114. List<AGInfo> tempAinfos = input.ToObject<List<AGInfo>>();
  115. List<AGInfo> tempsert = new List<AGInfo>();
  116. List<AGInfo> aGInfos = new List<AGInfo>();
  117. tempAinfos.ForEach(item =>
  118. {
  119. string requestUri = item.properties.requestUri;
  120. var isType = StaticValue.suffixName.Where(k => requestUri.Contains(k)).ToList();
  121. if (isType.Count == 0)
  122. aGInfos.Add(item);
  123. });
  124. //foreach (var item in tempAinfos)
  125. //{
  126. // string requestUri = item.properties.requestUri;
  127. // var isType = type.Where(k => requestUri.Contains(k)).ToList();
  128. // if (isType.Count == 0)
  129. // aGInfos.Add(item);
  130. //}
  131. string cHour = dtime.ToString("yyyyMMddHH");
  132. string cHH = dtime.ToString("HH");
  133. if (aGInfos.Count > 0)
  134. {
  135. cHour = aGInfos.Select(s => DateTimeOffset.Parse(s.time).ToString("yyyyMMddHH")).First();
  136. cDay = aGInfos.Select(s => DateTimeOffset.Parse(s.time).ToString("yyyyMMdd")).First();
  137. cHH = aGInfos.Select(s => DateTimeOffset.Parse(s.time).ToString("HH")).First();
  138. }
  139. RecCnt saveCnts = new();
  140. List<RecAppGWInfo> recInfo = aGInfos.Select(s => new RecAppGWInfo { hour = cHour, ip = s.properties.clientIp, api = s.properties.requestUri.Split("?").ToList().Count() > 1 ? s.properties.requestUri.Split("?").ToList()[0] : s.properties.requestUri, hostName = s.properties.hostname,minute = DateTimeOffset.Parse(s.time).ToString("mm") }).ToList();
  141. List<RecApiCnt> apiCnt = recInfo.GroupBy(a => a.api).Select(g => new RecApiCnt { api = g.Key, count = g.Count(), hour = cHour, hostName = g.Select(h => h.hostName).Distinct().ToList(), ip = g.Select(i => i.ip).Distinct().ToList() }).ToList();
  142. saveCnts.apiCnt = apiCnt;
  143. List<RecIpCnt> ipCnt = recInfo.GroupBy(a => a.ip).Select(g => new RecIpCnt { ip = g.Key, count = g.Count(), hour = cHour, hostName = g.Select(h => h.hostName).Distinct().ToList(), api = g.Select(i => i.api).Distinct().ToList() }).ToList();
  144. saveCnts.ipCnt = ipCnt;
  145. List<MinuteCnt> minCnts = recInfo.GroupBy(a => a.minute).Select(s => new MinuteCnt { minute = s.Key, cnt = s.Count() }).ToList();
  146. saveCnts.minCnts = minCnts;
  147. var ipcounts = saveCnts.ipCnt.Select(z => new IdCodeCount { id = z.ip, count = z.count }).ToList();
  148. ipcounts.ForEach(async x => {
  149. string region =await _ipSearcher.SearchIpAsync(x.id);
  150. if (!string.IsNullOrWhiteSpace(region))
  151. {
  152. string[] dis = region.Split("·");
  153. if (dis.Length >= 2)
  154. {
  155. x.code = dis[dis.Length - 1];
  156. x.name = dis[dis.Length - 2]; // 不保留省份
  157. //x.name = region.Substring(0, region.LastIndexOf("·")); //保留省份
  158. }
  159. else {
  160. var disrs = Regex.Split(region.TrimStart().TrimEnd(), @"\s+");
  161. if (disrs.Length >= 2)
  162. {
  163. x.code = disrs[disrs.Length - 1];
  164. x.name = disrs[disrs.Length - 2]; //不保留省份
  165. //x.name = region.Substring(0, region.LastIndexOf("·")); //保留省份
  166. }
  167. else {
  168. x.code = region;
  169. x.name = region;
  170. }
  171. }
  172. }
  173. else {
  174. x.name = x.id;
  175. x.code = x.id;
  176. }
  177. });
  178. List<RecRegionCnt> regionCnts = new List<RecRegionCnt>();
  179. ipcounts.GroupBy(x => x.name).ToList().ForEach(z => {
  180. regionCnts.Add(new RecRegionCnt { region = z.Key, count = z.ToList().Sum(y => y.count), hour = cHour });
  181. });
  182. saveCnts.regionCnts = regionCnts;
  183. recCnts.Add(saveCnts);
  184. //保存存至Blob文件
  185. var url = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(saveCnts.ToJsonString(), $"visitCnt/{cDay}", $"{cHH}.json");
  186. urls.Add(url);
  187. }
  188. if (recCnts.Count > 1)
  189. {
  190. //保存一天的数据至Blob文件
  191. var daysUrl = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(recCnts.ToJsonString(), $"visitCnt/{cDay}", $"days.json");
  192. }
  193. var azureClient = _azureStorage.GetBlobContainerClient("0-public");//获取容器连接地址
  194. int expireTime = int.Parse(DateTimeOffset.UtcNow.AddDays(-180).ToString("yyyyMMdd"));
  195. await foreach (var blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix: "visitCnt"))
  196. {
  197. string[] sub_name = blobItem.Name.Split('/');
  198. if (sub_name.Length > 2)
  199. {
  200. if (int.Parse(sub_name[1]) <= expireTime)
  201. {
  202. await azureClient.GetBlobBaseClient(blobItem.Name).DeleteIfExistsAsync();
  203. }
  204. }
  205. }
  206. } catch (Exception ex) {
  207. await _dingDing.SendBotMsg($"防火墙日志统计异常:{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  208. }
  209. return (recCnts, urls);
  210. }
  211. }
  212. }