IESTimerTrigger.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. using Azure.Cosmos;
  2. using Azure.Storage.Blobs.Models;
  3. using Azure.Storage.Blobs.Specialized;
  4. using DinkToPdf;
  5. using DinkToPdf.Contracts;
  6. using HTEXLib.COMM.Helpers;
  7. using Microsoft.Azure.Cosmos.Table;
  8. using Microsoft.Azure.Functions.Worker;
  9. using Microsoft.Azure.Functions.Worker.Http;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.OData.Edm;
  12. using StackExchange.Redis;
  13. using System;
  14. using System.Collections.Concurrent;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Net;
  19. using System.Net.Http;
  20. using System.Reflection;
  21. using System.Text;
  22. using System.Text.Json;
  23. using System.Threading.Tasks;
  24. using System.Web;
  25. using TEAMModelOS.SDK;
  26. using TEAMModelOS.SDK.DI;
  27. using TEAMModelOS.SDK.Extension;
  28. using TEAMModelOS.SDK.Models;
  29. using TEAMModelOS.SDK.Models.Cosmos.Teacher;
  30. using TEAMModelOS.SDK.Models.Service;
  31. using TEAMModelOS.SDK.Models.Service.BI;
  32. using TEAMModelOS.SDK.Models.Table;
  33. using static TEAMModelOS.SDK.Models.Service.SystemService;
  34. using static TEAMModelOS.SDK.Models.Teacher;
  35. namespace TEAMModelOS.FunctionV4.TimeTrigger
  36. {
  37. public class IESTimerTrigger
  38. {
  39. /// <summary>
  40. /// 文档。https://docs.microsoft.com/zh-cn/azure/azure-functions/functions-bindings-timer?tabs=in-process&pivots=programming-language-csharp
  41. /// Timer 在线测试 https://ncrontab.swimburger.net/
  42. /// </summary>
  43. private readonly AzureCosmosFactory _azureCosmos;
  44. private readonly DingDing _dingDing;
  45. private readonly AzureStorageFactory _azureStorage;
  46. private readonly AzureRedisFactory _azureRedis;
  47. private readonly IConverter _converter;
  48. private readonly SnowflakeId _snowflakeId;
  49. private readonly IHttpClientFactory _httpClient;
  50. private IPSearcher _ipSearcher;
  51. private readonly Region2LongitudeLatitudeTranslator _longitudeLatitudeTranslator;
  52. public IESTimerTrigger(Region2LongitudeLatitudeTranslator longitudeLatitudeTranslator, IPSearcher ipSearcher, IHttpClientFactory httpClient, SnowflakeId snowflakeId, IConverter converter, AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis)
  53. {
  54. _azureCosmos = azureCosmos;
  55. _dingDing = dingDing;
  56. _azureStorage = azureStorage;
  57. _azureRedis = azureRedis;
  58. _converter = converter;
  59. _snowflakeId=snowflakeId;
  60. _httpClient = httpClient;
  61. _ipSearcher = ipSearcher;
  62. _longitudeLatitudeTranslator = longitudeLatitudeTranslator;
  63. }
  64. /// <summary>
  65. /// 防火墙日志记录文件
  66. /// </summary>
  67. /// <param name="req"></param>
  68. /// <param name="log"></param>
  69. /// <returns></returns>
  70. [Function("HttpLogCount")]
  71. //https://docs.azure.cn/zh-cn/azure-functions/functions-bindings-timer?tabs=in-process&pivots=programming-language-csharp
  72. //0 1 * * * * 一天中每小时的第 1 分钟
  73. //0 */10 * * * * 每五分钟一次
  74. public async Task HttpLogCount([TimerTrigger("0 5 * * * *")] TimerInfo myTimer, ILogger log)
  75. {
  76. try
  77. {
  78. string location = Environment.GetEnvironmentVariable("Option:Location");
  79. //获取上一个小时的数据
  80. //获取上一个小时的数据
  81. var gmt8Time = DateTimeOffset.Now.GetGMTTime(8).AddHours(-1);
  82. var appendBlob = _azureStorage.GetBlobContainerClient("0-service-log").GetAppendBlobClient($"http-log/{gmt8Time:yyyy}/{gmt8Time:MM}/{gmt8Time:dd}/{gmt8Time:HH}.log");
  83. if (await appendBlob.ExistsAsync())
  84. {
  85. BlobDownloadResult result = await appendBlob.DownloadContentAsync();
  86. var content = result.Content.ToString();
  87. content= content.Substring(0, content.Length-2);
  88. if (content.EndsWith("}"))
  89. {
  90. content=$"[{content}]";
  91. }
  92. else
  93. {
  94. content=$"[{content}}}]";
  95. }
  96. var httpLogList = content.ToObject<List<HttpLog>>();
  97. Parallel.ForEach(httpLogList, item =>
  98. {
  99. item.year = $"{gmt8Time:yyyy}";
  100. item.month = $"{gmt8Time:MM}";
  101. item.day = $"{gmt8Time:dd}";
  102. item.hour =$"{gmt8Time:HH}";
  103. });
  104. // vistsDay.FindAll(x => x.path.Contains("common/exam/upsert-record"))
  105. (ConcurrentBag<ApiVist> vists, ConcurrentBag<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo) = await SystemService.ConvertHttpLog(httpLogList, _azureRedis, _ipSearcher, _longitudeLatitudeTranslator);
  106. if (vists!=null && vists.Count>0)
  107. {
  108. var appendDayBlob = _azureStorage.GetBlobContainerClient("0-service-log").GetAppendBlobClient($"http-log/{gmt8Time:yyyy}/{gmt8Time:MM}/{gmt8Time:dd}/index.log");
  109. if (!await appendDayBlob.ExistsAsync())
  110. {
  111. await appendDayBlob.CreateAsync();
  112. }
  113. await Parallel.ForEachAsync(vists, async (item, _) =>
  114. {
  115. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes($"{item.ToJsonString()},\n")))
  116. {
  117. await appendDayBlob.AppendBlockAsync(stream);
  118. }
  119. });
  120. }
  121. }
  122. }
  123. catch (Exception ex)
  124. {
  125. await _dingDing.SendBotMsg($"{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  126. }
  127. }
  128. /// <summary>
  129. /// 防火墙日志记录文件
  130. /// </summary>
  131. /// <param name="req"></param>
  132. /// <param name="log"></param>
  133. /// <returns></returns>
  134. [Function("FireWallFileLog")]
  135. //https://docs.azure.cn/zh-cn/azure-functions/functions-bindings-timer?tabs=in-process&pivots=programming-language-csharp
  136. //0 1 * * * * 一天中每小时的第 1 分钟
  137. //0 */10 * * * * 每五分钟一次
  138. public async Task FireWallFileLog([TimerTrigger("0 1 * * * *")] TimerInfo myTimer, ILogger log)
  139. {
  140. try
  141. {
  142. string location = Environment.GetEnvironmentVariable("Option:Location");
  143. var datetime = DateTimeOffset.Now.AddHours(-1);
  144. var y = datetime.Year;
  145. var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
  146. var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
  147. var h = datetime.Hour >= 10 ? $"{datetime.Hour}" : $"0{datetime.Hour}";
  148. #if DEBUG
  149. if (location.Equals("China-Dep"))
  150. #else
  151. if (location.Equals("China"))
  152. #endif
  153. {
  154. //string path = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/OSFIREWARE/y={y}/m={m}/d={d}/h={h}/m=00/PT1H.json";
  155. string path = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.WEB/SITES/TEAMMODELOS/y={y}/m={m}/d={d}/h={h}/m=00/PT1H.json";
  156. var retn = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, path, "LogStorage");
  157. if (retn.recCnts.IsNotEmpty())
  158. {
  159. //https://teammodelos.blob.core.chinacloudapi.cn/0-public/pie-borderRadius.html
  160. string publishUrl = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={HttpUtility.UrlEncode(retn.saveUrls.First(), Encoding.UTF8)}&time={HttpUtility.UrlEncode(datetime.AddHours(8).ToString("yyyy年MM月dd日 HH时"), Encoding.UTF8)}";
  161. string ulrs = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={retn.saveUrls.First()}&time={datetime.AddHours(8).ToString("yyyy年MM月dd日 HH时")}";
  162. string ulr = $"http://cdhabook.teammodel.cn:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(ulrs, Encoding.UTF8)}&delay=5000";
  163. string image = "";
  164. try
  165. {
  166. string strs = await _httpClient.CreateClient().GetStringAsync(ulr);
  167. if (!string.IsNullOrWhiteSpace(strs))
  168. {
  169. JsonElement json = strs.ToObject<JsonElement>();
  170. json.TryGetProperty("url", out JsonElement base64);
  171. using (MemoryStream ms = new MemoryStream(Convert.FromBase64String($"{base64}")))
  172. {
  173. TimeZoneInfo localTimezone = TimeZoneInfo.Local;
  174. var Hours = localTimezone.BaseUtcOffset.Hours;
  175. var nowTime = DateTimeOffset.UtcNow;
  176. if (Hours!=0)
  177. {
  178. //有时差
  179. nowTime = DateTimeOffset.UtcNow.AddHours(8-Hours);
  180. }
  181. image = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(ms, $"visitCnt/{nowTime.ToString("yyyyMMdd")}", $"{nowTime.ToString("yyyyMMddHH")}.png", false);
  182. //image = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(ms, $"visitCnt/{y}{m}{d}", $"{y}{m}{d}{h}.png", false);
  183. }
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. }
  189. await _dingDing.SendBotMarkdown("防火墙日志记录", $"#### 防火墙日志记录(小时)\n> 记录时间:{datetime.AddHours(8).ToString("yyyy-MM-dd HH")}\n> ![screenshot]({image})\n> ###### 发布时间:{DateTime.Now.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss")}" +
  190. $" [发布地址]({publishUrl}) \n", GroupNames.醍摩豆服務運維群組);
  191. }
  192. //处理昨天的防火墙日志
  193. var yesterday = datetime.AddHours(8).Hour >= 10 ? $"{datetime.AddHours(8).Hour}" : $"0{datetime.AddHours(8).Hour}";
  194. if (yesterday.Equals("00"))
  195. {
  196. var pastTime = datetime.AddHours(-1);
  197. var ptY = pastTime.Year;
  198. var ptM = pastTime.Month >= 10 ? $"{pastTime.Month}" : $"0{pastTime.Month}";
  199. var ptD = pastTime.Day >= 10 ? $"{pastTime.Day}" : $"0{pastTime.Day}";
  200. string dayPath = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.WEB/SITES/TEAMMODELOS/y={ptY}/m={ptM}/d={ptD}";
  201. var retnDay = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, dayPath, "LogStorage", timeType: "Day");
  202. if (retn.recCnts.IsNotEmpty())
  203. {
  204. //一天的统计
  205. string dayPublishUrl = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={HttpUtility.UrlEncode(retnDay.saveUrls.First(), Encoding.UTF8)}&time={HttpUtility.UrlEncode(pastTime.ToString("yyyy年MM月dd日"), Encoding.UTF8)}";
  206. string dayUrls = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={retnDay.saveUrls.First()}&time={pastTime.ToString("yyyy年MM月dd日")}";
  207. string dayUrl = $"http://cdhabook.teammodel.cn:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(dayUrls, Encoding.UTF8)}&delay=6000";
  208. string dayImage = "";
  209. try
  210. {
  211. string dayStr = await _httpClient.CreateClient().GetStringAsync(dayUrl);
  212. if (!string.IsNullOrWhiteSpace(dayStr))
  213. {
  214. JsonElement dayJson = dayStr.ToObject<JsonElement>();
  215. dayJson.TryGetProperty("url", out JsonElement dayBase64);
  216. using (MemoryStream dayMs = new(Convert.FromBase64String($"{dayBase64}")))
  217. {
  218. TimeZoneInfo localTimezone = TimeZoneInfo.Local;
  219. var Hours = localTimezone.BaseUtcOffset.Hours;
  220. var nowTime = DateTimeOffset.UtcNow;
  221. if (Hours!=0)
  222. {
  223. //有时差
  224. nowTime = DateTimeOffset.UtcNow.AddHours(8-Hours);
  225. }
  226. dayImage = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(dayMs, $"visitCnt/{nowTime.ToString("yyyyMMdd")}", "days.png", false);
  227. }
  228. }
  229. }
  230. catch (Exception ex) { }
  231. await _dingDing.SendBotMarkdown("防火墙日志记录", $"#### 防火墙日志记录(天)\n> 记录时间:{pastTime.ToString("yyyy-MM-dd")}\n> ![screenshot]({dayImage})\n> ###### 发布时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" +
  232. $" [发布地址]({dayPublishUrl}) \n", GroupNames.醍摩豆服務運維群組);
  233. }
  234. }
  235. }
  236. else if (location.Contains("Global"))
  237. {
  238. }
  239. }
  240. catch (Exception ex)
  241. {
  242. // await _dingDing.SendBotMsg($"FireWallFileLog 防火墙日志记录: {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  243. }
  244. }
  245. /// <summary>
  246. /// 每天执行 一次清零动作
  247. /// </summary>
  248. /// <param name="myTimer"></param>
  249. /// <param name="log"></param>
  250. /// <returns></returns>
  251. [Function("BIStatsDayDefault")]
  252. //https://docs.azure.cn/zh-cn/azure-functions/functions-bindings-timer?tabs=in-process&pivots=programming-language-csharp
  253. //0 1 0 * * * 一天中00的第 1 分钟
  254. //0 1 * * * * 一天中每小时的第 1 分钟
  255. //0 */10 * * * * 每五分钟一次
  256. public async Task BIStatsDayDefault([TimerTrigger("0 1 0 * * *")] TimerInfo myTimer, ILogger log)
  257. {
  258. try
  259. {
  260. _ = BIStats.SetStatsZeroPoint(_azureCosmos, _dingDing);
  261. }
  262. catch (Exception ex)
  263. {
  264. await _dingDing.SendBotMsg($"BIStatsDayDefault 定时清理每天的数据: {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  265. }
  266. }
  267. /// <summary>
  268. /// 清理HiTeach教研类型的课例文件上传在Blob空间的文件。 0 */10 22-23 * * *
  269. /// 该代码执行之后 需要删除或者取消Timer任务。
  270. /// </summary>
  271. /// <param name="myTimer"></param>
  272. /// <param name="log"></param>
  273. /// <returns></returns>
  274. //[Function("CleanUnusedLessonRecord")]
  275. //5分钟一次
  276. public async Task CleanUnusedLessonRecord(
  277. //[TimerTrigger("0 */10 15-23 * * *")] TimerInfo myTimer, ILogger log
  278. )
  279. {
  280. string location = Environment.GetEnvironmentVariable("Option:Location");
  281. try
  282. {
  283. if (location.Equals("China") || location.Equals("Global"))
  284. {
  285. bool lockKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"LessonRecord:Unused:Lock:{location}");
  286. bool keyLock = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"LessonRecord:Unused:Lock:Lock");
  287. if (keyLock)
  288. {
  289. return;
  290. }
  291. //key不存在的时候 。
  292. if (!lockKey)
  293. {
  294. var schoolKeys = new List<IdCodeCount>();
  295. var teacherKeys = new List<IdCodeCount>();
  296. string sqlT = "select c.id,c.name, 'Teacher' as code from c where c.code='Base'";
  297. string sqlS = "select c.id,c.name, 'School' as code from c where c.code='Base'";
  298. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).
  299. GetItemQueryIterator<IdCodeCount>(queryText: sqlT, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  300. {
  301. teacherKeys.Add(item);
  302. }
  303. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
  304. GetItemQueryIterator<IdCodeCount>(queryText: sqlS, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  305. {
  306. schoolKeys.Add(item);
  307. }
  308. string sqlcount = "select value count(1) from c where c.pk='LessonRecord'";
  309. foreach (var key in schoolKeys)
  310. {
  311. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
  312. GetItemQueryIterator<int>(queryText: sqlcount, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"LessonRecord-{key.id}") }))
  313. {
  314. key.count = item;
  315. break;
  316. }
  317. }
  318. foreach (var key in teacherKeys)
  319. {
  320. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).
  321. GetItemQueryIterator<int>(queryText: $"select value count(1) from c where c.pk='LessonRecord' and c.tmdid='{key.id}'",
  322. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"LessonRecord") }))
  323. {
  324. key.count = item;
  325. break;
  326. }
  327. }
  328. schoolKeys.AddRange(teacherKeys);
  329. //以下代码作用,用于根据当前拥有的课例数判断区分学校和个人使用课例频率越多的,
  330. //并均分每次需要处理的学校和个人容器个数,避免每次处理批次花费时间相差太大。
  331. //将每个批次处理数量级控制在500-1000左右。
  332. List<IEnumerable<IdCodeCount>> counts = new List<IEnumerable<IdCodeCount>>();
  333. //501-∞
  334. var count501_ = schoolKeys.Where(x => x.count >= 501); //至少500条
  335. counts.AddRange(count501_.Page(1));//1个学校或个人
  336. //201-500
  337. var count201_500 = schoolKeys.Where(x => x.count >= 201 && x.count <= 500); //至少603条-1500条
  338. counts.AddRange(count201_500.Page(3));//2个学校或个人
  339. //100-200
  340. var count100_200 = schoolKeys.Where(x => x.count >= 100 && x.count <= 200);//至少500条-1000条
  341. counts.AddRange(count100_200.Page(10));//5个学校或个人
  342. //51-99
  343. var count51_99 = schoolKeys.Where(x => x.count >= 51 && x.count <= 99);//至少500条-990条
  344. counts.AddRange(count51_99.Page(10));//10个学校或个人
  345. //21-50
  346. var count21_50 = schoolKeys.Where(x => x.count >= 21 && x.count <= 50);//至少410条-1000条
  347. counts.AddRange(count21_50.Page(20));//20个学校或个人
  348. //10-20
  349. var count10_20 = schoolKeys.Where(x => x.count >= 10 && x.count <= 20);//至少500条-1000条
  350. counts.AddRange(count10_20.Page(50));//50个学校或个人
  351. //5-9
  352. var count0_9 = schoolKeys.Where(x => x.count >= 5 && x.count <= 9);//至少500条-900条
  353. counts.AddRange(count0_9.Page(100));//100个学校或个人
  354. //2-4
  355. var count2_4 = schoolKeys.Where(x => x.count >= 2 && x.count <= 4);//至少600条-1200条
  356. counts.AddRange(count2_4.Page(300));
  357. //0-1,已经处理过一次,不用再处理
  358. var count0_1 = schoolKeys.Where(x => x.count ==1);//至少500,就算没有课例也算一次。
  359. counts.AddRange(count0_1.Page(1000));
  360. int field = 1;
  361. foreach (var item in counts)
  362. {
  363. if (item.Any())
  364. {
  365. bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"LessonRecord:Unused:Lock:{location}", field,
  366. new UnusedLock { field = field, status = 0, item = item }.ToJsonString());
  367. field += 1;
  368. }
  369. }
  370. await _dingDing.SendBotMsg($"{location},获取到:{schoolKeys.Count} 个学校和个人的容器\n" +
  371. $"大概要处理:{schoolKeys.Sum(x => x.count) + schoolKeys.Where(x => x.count >= 0).Count()} 条数据\n" +
  372. $"将数据分为:{field - 1} 次处理,每次处理500-1000条数据。", GroupNames.醍摩豆服務運維群組);
  373. }
  374. //key存在的时候 开始进行数据处理
  375. var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"LessonRecord:Unused:Lock:{location}");
  376. List<UnusedLock> unuseds = new List<UnusedLock>();
  377. foreach (var rcd in records)
  378. {
  379. var value = rcd.Value.ToString().ToObject<UnusedLock>();
  380. unuseds.Add(value);
  381. }
  382. int max = unuseds.Max(x => x.field);
  383. int index = max + 1;
  384. var unusedLock = unuseds.Where(s => s.status == 0)?.OrderBy(x => x.field)?.First();
  385. if (unusedLock != null)
  386. {
  387. var stime = DateTimeOffset.UtcNow;
  388. long s = stime.ToUnixTimeMilliseconds();
  389. string sdata = stime.ToString("yyyy-MM-dd HH:mm:ss");
  390. await _dingDing.SendBotMsg($"{location}-开始第{unusedLock.field}轮清理冗余的课例记录文件...\n开始时间:{sdata}\n清理容器有{unusedLock.item.Select(x => $"{x.name}-{x.id}").ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  391. //将当前的标记为1锁定。
  392. bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"LessonRecord:Unused:Lock:{location}", unusedLock.field,
  393. new UnusedLock { field = unusedLock.field, status = 1, item = unusedLock.item }.ToJsonString());
  394. List<KeyValuePair<string, List<string>>> deleteUrls = new List<KeyValuePair<string, List<string>>>();
  395. foreach (IdCodeCount idCode in unusedLock.item)
  396. {
  397. try
  398. {
  399. List<string> urls = new List<string>();
  400. var ContainerClient = _azureStorage.GetBlobContainerClient(idCode.id);
  401. List<string> items = await ContainerClient.List("records");
  402. if (items.IsNotEmpty())
  403. {
  404. HashSet<string> set = new HashSet<string>();
  405. items.ForEach(z =>
  406. {
  407. var uri = z.Split("/");
  408. if (uri.Length > 1)
  409. {
  410. set.Add(uri[1]);
  411. }
  412. });
  413. if (set.Any())
  414. {
  415. string tbname = idCode.code.Equals("Teacher") ? Constant.Teacher : Constant.School;
  416. string pk = idCode.code.Equals("Teacher") ? "LessonRecord" : $"LessonRecord-{idCode.id}";
  417. string sql = $"select value c.id from c where c.pk='LessonRecord' and c.id in ({string.Join(",", set.Select(m => $"'{m}'"))})";
  418. List<string> ids = new List<string>();
  419. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
  420. .GetItemQueryIterator<string>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(pk) }))
  421. {
  422. ids.Add(item);
  423. }
  424. var notin = set.Except(ids);
  425. if (notin.Any())
  426. {
  427. foreach (var not in notin)
  428. {
  429. if (!string.IsNullOrWhiteSpace(not))
  430. {
  431. string url = $"records/{not}";
  432. long id = -1;
  433. long.TryParse(not, out id);
  434. if (id > -1)
  435. {
  436. id = _snowflakeId.ParseIdToTimeStamp(id);
  437. }
  438. if (id > -1)
  439. {
  440. //72小时之外的数据。需要被删除 72 * 60 * 60 *1000= 259200000
  441. //当前时间-课例产生的时间戳
  442. if (s - id > 259200000)
  443. {
  444. urls.Add(url);
  445. await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, idCode.id, new List<string> { url });
  446. }
  447. }
  448. }
  449. }
  450. }
  451. }
  452. }
  453. if (urls.IsNotEmpty())
  454. {
  455. deleteUrls.Add(new KeyValuePair<string, List<string>>($"{idCode.name}-{idCode.id}", urls));
  456. }
  457. }
  458. catch (Exception ex)
  459. {
  460. //异常的学校,需要将数据放回redis 重新处理。
  461. await _azureRedis.GetRedisClient(8).HashSetAsync($"LessonRecord:Unused:Lock:{location}", index,
  462. new UnusedLock { field = index, status = 0, item = new List<IdCodeCount>() { idCode } }.ToJsonString());
  463. index += 1;
  464. await _dingDing.SendBotMsg($"{location}-第{unusedLock.field}轮清理时容器:{idCode.id},类型:{idCode.code}出现异常。\n将{idCode.id}重新加入队列,队列编号:{index}\n" +
  465. $"异常信息:{ex.Message},{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  466. }
  467. }
  468. await _azureRedis.GetRedisClient(8).HashDeleteAsync($"LessonRecord:Unused:Lock:{location}", unusedLock.field);
  469. var etime = DateTimeOffset.UtcNow;
  470. long e = etime.ToUnixTimeMilliseconds();
  471. string edata = etime.ToString("yyyy-MM-dd HH:mm:ss");
  472. long d = (e - s) / 1000;
  473. string timeStr = d >= 60 ? Math.Round(d / 60.0) + "分" : d + "秒";
  474. List<string> content = new List<string>();
  475. foreach (var url in deleteUrls)
  476. {
  477. if (url.Value.IsNotEmpty())
  478. {
  479. content.Add($"{url.Key}\n {string.Join(" \t\n", url.Value)}");
  480. }
  481. }
  482. if (max == unusedLock.field)
  483. {
  484. //锁定15至少小时。
  485. await _azureRedis.GetRedisClient(8).StringSetAsync($"LessonRecord:Unused:Lock:Lock", "用于在清理完所有Blob容器后,锁定不再进行多次清理。");
  486. await _azureRedis.GetRedisClient(8).KeyExpireAsync($"LessonRecord:Unused:Lock:Lock", DateTime.UtcNow.AddHours(15));
  487. }
  488. if (content.IsNotEmpty())
  489. {
  490. string str = string.Join("\n", content);
  491. await _dingDing.SendBotMsg($"{location}-结束第{unusedLock.field}轮清理冗余的课例记录文件...\n结束时间:{edata}\n耗时:{timeStr}\n清理内容:\n{str}", GroupNames.醍摩豆服務運維群組);
  492. }
  493. else
  494. {
  495. // await _dingDing.SendBotMsg($"{location}-结束第{unusedLock.field}轮清理冗余的课例记录文件...\n结束时间:{edata}\n耗时:{timeStr}\n清理内容:暂无", GroupNames.醍摩豆服務運維群組);
  496. }
  497. }
  498. }
  499. }
  500. catch (Exception ex)
  501. {
  502. await _dingDing.SendBotMsg($"{location} 清理时容器出现异常。\n异常信息:{ex.Message},{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  503. }
  504. }
  505. /// <summary>
  506. /// 每天執行 取得IOT TeachingData 並統計昨日每校Redis資料 執行時間:每日凌晨1時1分
  507. /// </summary>
  508. [Function("BICrtDailyAnal")]
  509. //0 1 0 * * * 一天中00的第 1 分钟
  510. //0 1 * * * * 一天中每小时的第 1 分钟
  511. //0 */10 * * * * 每五分钟一次
  512. public async Task BICreatDailyAnalData([TimerTrigger("0 1 1 * * *")] TimerInfo myTimer, ILogger log)
  513. {
  514. var _azureCosmosClient = _azureCosmos.GetCosmosClient();
  515. var _azureCosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  516. var _azureCosmosClientCsv2CnRead = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  517. var datetime = DateTimeOffset.UtcNow.AddHours(-12); //統計昨天的數據
  518. var y = $"{datetime.Year}";
  519. var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
  520. var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
  521. //生成學校IOT數據
  522. await BIProdAnalysis.BICreatDailyAnalData(_azureRedis, _azureCosmosClient, _azureCosmosClientCsv2, _azureCosmosClientCsv2CnRead, _dingDing, y, m, d);
  523. //刪除三個月以前的Redis數據 [待做]
  524. }
  525. /// <summary>
  526. /// 每天執行 計算各學生各科錯題庫的數量,記入Redis 執行時間:每日2時1分
  527. /// 「新增錯題數」取得方法改由智慧錯題的時間戳記判斷,每日統計錯題數已不需要
  528. /// </summary>
  529. //[Function("CntStuErrorItems")]
  530. //public async Task CntStuErrorItems([TimerTrigger("0 1 2 * * *")] TimerInfo myTimer, ILogger log)
  531. //{
  532. // var _azureCosmosClient = _azureCosmos.GetCosmosClient();
  533. // await ErrorItemsService.cntStuErrorItemsAsync(_azureRedis, _azureCosmosClient, _dingDing);
  534. //}
  535. public class UnusedLock
  536. {
  537. public int field { get; set; }
  538. /// <summary>
  539. /// 0默认未被执行,1 正在执行中
  540. /// </summary>
  541. public int status { get; set; }
  542. public IEnumerable<IdCodeCount> item { get; set; } = new List<IdCodeCount>();
  543. }
  544. }
  545. }