MonitorServicesBus.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. using Azure.Cosmos;
  7. using Azure.Messaging.ServiceBus;
  8. using Microsoft.Azure.WebJobs;
  9. using Microsoft.Azure.WebJobs.Host;
  10. using Microsoft.Extensions.Logging;
  11. using StackExchange.Redis;
  12. using TEAMModelOS.SDK.DI;
  13. using TEAMModelOS.SDK.Extension;
  14. using TEAMModelOS.SDK;
  15. using TEAMModelOS.SDK.Models;
  16. using TEAMModelOS.SDK.Models.Cosmos;
  17. using TEAMModelOS.SDK.Models.Cosmos.Common;
  18. namespace TEAMModelFunction
  19. {
  20. public class MonitorServicesBus
  21. {
  22. private readonly AzureCosmosFactory _azureCosmos;
  23. private readonly DingDing _dingDing;
  24. private readonly AzureStorageFactory _azureStorage;
  25. private readonly AzureRedisFactory _azureRedis;
  26. private readonly AzureServiceBusFactory _serviceBus;
  27. public MonitorServicesBus(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage , AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus)
  28. {
  29. _azureCosmos = azureCosmos;
  30. _dingDing = dingDing;
  31. _azureStorage = azureStorage;
  32. _azureRedis = azureRedis;
  33. _serviceBus = serviceBus;
  34. }
  35. [FunctionName("Exam")]
  36. public async Task Exam([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  37. {
  38. try
  39. {
  40. var json = JsonDocument.Parse(msg);
  41. json.RootElement.TryGetProperty("id", out JsonElement id);
  42. json.RootElement.TryGetProperty("progress", out JsonElement progress);
  43. json.RootElement.TryGetProperty("code", out JsonElement code);
  44. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  45. var client = _azureCosmos.GetCosmosClient();
  46. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{code}"));
  47. exam.progress = progress.ToString();
  48. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"{code}"));
  49. }
  50. catch (Exception ex)
  51. {
  52. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  53. }
  54. }
  55. [FunctionName("Vote")]
  56. public async Task Vote([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  57. {
  58. try
  59. {
  60. var jsonMsg = JsonDocument.Parse(msg);
  61. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  62. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  63. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  64. var client = _azureCosmos.GetCosmosClient();
  65. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  66. vote.progress = progress.ToString();
  67. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  68. }
  69. catch (Exception ex)
  70. {
  71. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  72. }
  73. }
  74. [FunctionName("Correct")]
  75. public async Task Correct([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  76. {
  77. try
  78. {
  79. var jsonMsg = JsonDocument.Parse(msg);
  80. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  81. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  82. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  83. var client = _azureCosmos.GetCosmosClient();
  84. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  85. correct.progress = progress.ToString();
  86. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  87. }
  88. catch (Exception ex)
  89. {
  90. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  91. }
  92. }
  93. [FunctionName("Survey")]
  94. public async Task Survey([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  95. {
  96. try
  97. {
  98. var jsonMsg = JsonDocument.Parse(msg);
  99. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  100. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  101. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  102. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  103. var client = _azureCosmos.GetCosmosClient();
  104. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  105. survey.progress = progress.ToString();
  106. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  107. }
  108. catch (Exception ex)
  109. {
  110. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  111. }
  112. }
  113. [FunctionName("Blob")]
  114. public async Task Blob([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blob", Connection = "Azure:ServiceBus:ConnectionString")] string msg) {
  115. try
  116. {
  117. // await _dingDing.SendBotMsg($"ServiceBus,Blob(){msg}", GroupNames.醍摩豆服務運維群組);
  118. var jsonMsg = JsonDocument.Parse(msg);
  119. if(jsonMsg.RootElement.TryGetProperty("name", out JsonElement name)&& name.ValueKind==JsonValueKind.String)
  120. {
  121. var client = _azureStorage.GetBlobContainerClient($"{name}");
  122. var size = await client.GetBlobsCatalogSize();
  123. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{long.Parse($"{size.Item1}")}"));
  124. foreach (var key in size.Item2.Keys)
  125. {
  126. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  127. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  128. }
  129. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{size.Item1},文件分类:{size.Item2.ToJsonString()}",
  130. GroupNames.成都开发測試群組);
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  136. }
  137. }
  138. /// <summary>
  139. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  140. /// </summary>
  141. /// <param name="msg"></param>
  142. /// <returns></returns>
  143. [FunctionName("BlobRoot")]
  144. public async Task BlobRoot([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  145. {
  146. try
  147. {
  148. var jsonMsg = JsonDocument.Parse(msg);
  149. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  150. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  151. {
  152. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:触发变更,{jsonMsg.ToJsonString()}",
  153. GroupNames.成都开发測試群組);
  154. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  155. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  156. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  157. string name = $"{_name}";
  158. string lockKey = $"Blob:Lock:{name}:{u}";
  159. bool exist= await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  160. if (!exist)
  161. { ///key不存在则正常进行计算
  162. bool condition = false;
  163. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  164. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  165. //准备处理Blob刷新时间
  166. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  167. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  168. await RefreshBlob(name, u);
  169. //将action 与Redis最新的时间进行比较,如果
  170. var rds = await CheckLockKey(lockKey, action);
  171. condition = rds.condition;
  172. exist = rds.exist;
  173. if (condition || !exist) {
  174. await RefreshBlob(name, u);
  175. }
  176. //使用 CancellationToken
  177. //while (condition || !exist)
  178. //{
  179. //}
  180. }
  181. else {
  182. ///key存在则,则刷新key对应的值
  183. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  184. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  185. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  186. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  187. }
  188. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
  189. GroupNames.成都开发測試群組);
  190. }
  191. }
  192. catch (Exception ex)
  193. {
  194. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  195. }
  196. }
  197. private async Task<(bool condition,bool exist)> CheckLockKey(string lockKey,long nowTime) {
  198. //Redis的最新时间
  199. long newestTime = 0;
  200. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  201. if (value != default && !value.IsNullOrEmpty)
  202. {
  203. JsonElement record = value.ToString().ToObject<JsonElement>();
  204. if (record.TryGetInt64(out newestTime))
  205. {
  206. }
  207. }
  208. //说明key已经不存在
  209. if (newestTime == 0)
  210. {
  211. return (false, true);
  212. }
  213. //说明key存在
  214. else {
  215. //说明Redis记录了最新的时间戳
  216. if (nowTime != newestTime)
  217. {
  218. return (true, false);
  219. }
  220. //时间相同,没有被再次记录最新的时间戳
  221. else
  222. {
  223. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  224. return (false, true);
  225. }
  226. }
  227. }
  228. private async Task RefreshBlob(string name ,string u) {
  229. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  230. var client = _azureStorage.GetBlobContainerClient(name);
  231. var size = await client.GetBlobsSize(u);
  232. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  233. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  234. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  235. double blobsize = 0;
  236. if (scores != default && scores != null)
  237. {
  238. foreach (var score in scores)
  239. {
  240. blobsize = blobsize + score.Score;
  241. }
  242. }
  243. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  244. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  245. long dis = (end - statr)/1000;
  246. long timeout = 10;
  247. if (dis> timeout) {
  248. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  249. }
  250. }
  251. /// <summary>
  252. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  253. /// </summary>
  254. /// <data msg>
  255. /// CourseChange
  256. ///// </data>
  257. /// <param name="msg"></param>
  258. /// <returns></returns>
  259. [FunctionName("StuList")]
  260. public async Task StuList([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "stulist", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  261. {
  262. var client = _azureCosmos.GetCosmosClient();
  263. try
  264. {
  265. var jsonMsg = JsonDocument.Parse(msg);
  266. StuListChange stuListChange = msg.ToObject<StuListChange>();
  267. //名单变动修改学生课程关联信息
  268. //await StuListService.FixStuCourse(client, stuListChange);
  269. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  270. //名单变动修改学生问卷关联信息
  271. await StuListService.FixActivity(client, _dingDing, stuListChange, "Survey");
  272. //名单变动修改学生投票关联信息
  273. await StuListService.FixActivity(client, _dingDing, stuListChange, "Vote");
  274. //名单变动修改学生评测关联信息
  275. await StuListService.FixActivity(client, _dingDing, stuListChange, "Exam");
  276. //TODO学习活动
  277. //await FixActivity(client, stuListChange, "Learn");
  278. //TODO作业活动
  279. // await FixActivity(client, stuListChange, "Homework");
  280. //TODO课程名单变动修改学生课程关联信息
  281. await StuListService.FixStuCourse(client, _dingDing, stuListChange);
  282. }
  283. catch (Exception ex)
  284. {
  285. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListServiceBus-StuList\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  286. }
  287. }
  288. }
  289. }