MonitorServicesBus.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 (CosmosException)
  51. {
  52. }
  53. catch (Exception ex)
  54. {
  55. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  56. }
  57. }
  58. [FunctionName("Vote")]
  59. public async Task Vote([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "vote", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  60. {
  61. try
  62. {
  63. var jsonMsg = JsonDocument.Parse(msg);
  64. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  65. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  66. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  67. var client = _azureCosmos.GetCosmosClient();
  68. Vote vote = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Vote>(id.ToString(), new PartitionKey($"{code}"));
  69. vote.progress = progress.ToString();
  70. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(vote, id.ToString(), new PartitionKey($"{code}"));
  71. }
  72. catch (CosmosException)
  73. {
  74. }
  75. catch (Exception ex)
  76. {
  77. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,VoteBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  78. }
  79. }
  80. [FunctionName("Correct")]
  81. public async Task Correct([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "correct", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  82. {
  83. try
  84. {
  85. var jsonMsg = JsonDocument.Parse(msg);
  86. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  87. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  88. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  89. var client = _azureCosmos.GetCosmosClient();
  90. Correct correct = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Correct>(id.ToString(), new PartitionKey($"{code}"));
  91. correct.progress = progress.ToString();
  92. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(correct, id.ToString(), new PartitionKey($"{code}"));
  93. }
  94. catch (CosmosException)
  95. {
  96. }
  97. catch (Exception ex)
  98. {
  99. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Correct()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  100. }
  101. }
  102. [FunctionName("Survey")]
  103. public async Task Survey([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "survey", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  104. {
  105. try
  106. {
  107. var jsonMsg = JsonDocument.Parse(msg);
  108. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  109. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  110. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  111. //Dictionary<string, object> keyValuePairs = mySbMsg.ToObject<Dictionary<string, object>>();
  112. var client = _azureCosmos.GetCosmosClient();
  113. Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.ToString(), new PartitionKey($"{code}"));
  114. survey.progress = progress.ToString();
  115. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, id.ToString(), new PartitionKey($"{code}"));
  116. }
  117. catch (CosmosException)
  118. {
  119. }
  120. catch (Exception ex)
  121. {
  122. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,SurveyBus()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  123. }
  124. }
  125. [FunctionName("Homework")]
  126. public async Task Homework([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "homework", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  127. {
  128. try
  129. {
  130. var jsonMsg = JsonDocument.Parse(msg);
  131. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  132. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  133. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  134. var client = _azureCosmos.GetCosmosClient();
  135. Homework homework = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Homework>(id.ToString(), new PartitionKey($"{code}"));
  136. homework.progress = progress.ToString();
  137. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(homework, id.ToString(), new PartitionKey($"{code}"));
  138. }
  139. catch (CosmosException ) {
  140. }
  141. catch (Exception ex)
  142. {
  143. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Homework()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  144. }
  145. }
  146. [FunctionName("Study")]
  147. public async Task Study([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "study", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  148. {
  149. try
  150. {
  151. var jsonMsg = JsonDocument.Parse(msg);
  152. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  153. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  154. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  155. var client = _azureCosmos.GetCosmosClient();
  156. Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.ToString(), new PartitionKey($"{code}"));
  157. study.progress = progress.ToString();
  158. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, id.ToString(), new PartitionKey($"{code}"));
  159. }
  160. catch (CosmosException)
  161. {
  162. }
  163. catch (Exception ex)
  164. {
  165. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Study()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  166. }
  167. }
  168. [FunctionName("ExamLite")]
  169. public async Task ExamLite([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "examlite", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  170. {
  171. try
  172. {
  173. var jsonMsg = JsonDocument.Parse(msg);
  174. jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
  175. jsonMsg.RootElement.TryGetProperty("progress", out JsonElement progress);
  176. jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);
  177. var client = _azureCosmos.GetCosmosClient();
  178. ExamLite lite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.ToString(), new PartitionKey($"{code}"));
  179. lite.progress = progress.ToString();
  180. await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(lite, id.ToString(), new PartitionKey($"{code}"));
  181. }
  182. catch (CosmosException)
  183. {
  184. }
  185. catch (Exception ex)
  186. {
  187. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,ExamLite()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  188. }
  189. }
  190. [FunctionName("Blob")]
  191. public async Task Blob([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blob", Connection = "Azure:ServiceBus:ConnectionString")] string msg) {
  192. try
  193. {
  194. //11 await _dingDing.SendBotMsg($"ServiceBus,Blob(){msg}", GroupNames.醍摩豆服務運維群組);
  195. var jsonMsg = JsonDocument.Parse(msg);
  196. if(jsonMsg.RootElement.TryGetProperty("name", out JsonElement name)&& name.ValueKind==JsonValueKind.String)
  197. {
  198. var client = _azureStorage.GetBlobContainerClient($"{name}");
  199. var size = await client.GetBlobsCatalogSize();
  200. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{long.Parse($"{size.Item1}")}"));
  201. foreach (var key in size.Item2.Keys)
  202. {
  203. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  204. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  205. }
  206. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{size.Item1},文件分类:{size.Item2.ToJsonString()}",
  207. // GroupNames.成都开发測試群組);
  208. }
  209. }
  210. catch (Exception ex)
  211. {
  212. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  213. }
  214. }
  215. /// <summary>
  216. /// 根据容器的根目录刷新redis并获取redis的最新使用情况
  217. /// </summary>
  218. /// <param name="msg"></param>
  219. /// <returns></returns>
  220. [FunctionName("BlobRoot")]
  221. public async Task BlobRoot([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "blobroot", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  222. {
  223. try
  224. {
  225. var jsonMsg = JsonDocument.Parse(msg);
  226. if (jsonMsg.RootElement.TryGetProperty("name", out JsonElement _name) && _name.ValueKind == JsonValueKind.String
  227. && jsonMsg.RootElement.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
  228. {
  229. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:触发变更,{jsonMsg.ToJsonString()}",
  230. // GroupNames.成都开发測試群組);
  231. List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
  232. string[] uls = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/");
  233. string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
  234. string name = $"{_name}";
  235. string lockKey = $"Blob:Lock:{name}:{u}";
  236. bool exist= await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  237. if (!exist)
  238. { ///key不存在则正常进行计算
  239. bool condition = false;
  240. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  241. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  242. //准备处理Blob刷新时间
  243. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  244. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  245. await RefreshBlob(name, u);
  246. //将action 与Redis最新的时间进行比较,如果
  247. var rds = await CheckLockKey(lockKey, action);
  248. condition = rds.condition;
  249. exist = rds.exist;
  250. if (condition || !exist) {
  251. await RefreshBlob(name, u);
  252. }
  253. //使用 CancellationToken
  254. //while (condition || !exist)
  255. //{
  256. //}
  257. }
  258. else {
  259. ///key存在则,则刷新key对应的值
  260. TimeSpan timeSpan = new TimeSpan(DateTimeOffset.UtcNow.AddMinutes(5).Ticks);
  261. timeSpan = timeSpan - new TimeSpan(DateTimeOffset.UtcNow.Ticks);
  262. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  263. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, now, expiry: timeSpan);
  264. }
  265. //await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{u},文件分类:{list.ToJsonString()}",
  266. // GroupNames.成都开发測試群組);
  267. }
  268. }
  269. catch (Exception ex)
  270. {
  271. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob()\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.醍摩豆服務運維群組);
  272. }
  273. }
  274. private async Task<(bool condition,bool exist)> CheckLockKey(string lockKey,long nowTime) {
  275. //Redis的最新时间
  276. long newestTime = 0;
  277. RedisValue value = await _azureRedis.GetRedisClient(8).StringGetAsync(lockKey);
  278. if (value != default && !value.IsNullOrEmpty)
  279. {
  280. JsonElement record = value.ToString().ToObject<JsonElement>();
  281. if (record.TryGetInt64(out newestTime))
  282. {
  283. }
  284. }
  285. //说明key已经不存在
  286. if (newestTime == 0)
  287. {
  288. return (false, true);
  289. }
  290. //说明key存在
  291. else {
  292. //说明Redis记录了最新的时间戳
  293. if (nowTime != newestTime)
  294. {
  295. return (true, false);
  296. }
  297. //时间相同,没有被再次记录最新的时间戳
  298. else
  299. {
  300. await _azureRedis.GetRedisClient(8).KeyDeleteAsync(lockKey);
  301. return (false, true);
  302. }
  303. }
  304. }
  305. private async Task RefreshBlob(string name ,string u) {
  306. long statr = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  307. var client = _azureStorage.GetBlobContainerClient(name);
  308. var size = await client.GetBlobsSize(u);
  309. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
  310. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
  311. var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
  312. double blobsize = 0;
  313. if (scores != default && scores != null)
  314. {
  315. foreach (var score in scores)
  316. {
  317. blobsize = blobsize + score.Score;
  318. }
  319. }
  320. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue(name), new RedisValue($"{blobsize}"));
  321. long end = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  322. long dis = (end - statr)/1000;
  323. long timeout = 10;
  324. if (dis> timeout) {
  325. await _dingDing.SendBotMsg($"ServiceBus,RefreshBlob:空间计算已经超过{timeout}秒\n容器名:{name}\n文件夹:{u}\n计算时长:{dis}", GroupNames.醍摩豆服務運維群組);
  326. }
  327. }
  328. /// <summary>
  329. /// 完善课程变更,StuListChange, originCode是学校编码 则表示名单是学校自定义名单,如果是tmdid则表示醍摩豆的私有名单,scope=school,private。
  330. /// </summary>
  331. /// <data msg>
  332. /// CourseChange
  333. ///// </data>
  334. /// <param name="msg"></param>
  335. /// <returns></returns>
  336. [FunctionName("StuList")]
  337. public async Task StuList([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "stulist", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
  338. {
  339. var client = _azureCosmos.GetCosmosClient();
  340. try
  341. {
  342. var jsonMsg = JsonDocument.Parse(msg);
  343. ListChange stuListChange = msg.ToObject<ListChange>();
  344. //名单变动修改学生课程关联信息
  345. //await StuListService.FixStuCourse(client, stuListChange);
  346. //Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
  347. //名单变动修改学生问卷关联信息
  348. await StuListService.FixActivity(client, _dingDing, stuListChange, "Survey");
  349. //名单变动修改学生投票关联信息
  350. await StuListService.FixActivity(client, _dingDing, stuListChange, "Vote");
  351. //名单变动修改学生评测关联信息
  352. await StuListService.FixActivity(client, _dingDing, stuListChange, "Exam");
  353. //TODO学习活动
  354. //await FixActivity(client, stuListChange, "Learn");
  355. //TODO作业活动
  356. // await FixActivity(client, stuListChange, "Homework");
  357. if (stuListChange.type==null||!stuListChange.type.Equals("research")) {
  358. //课程名单变动修改学生课程关联信息
  359. await StuListService.FixStuCourse(client, _dingDing, stuListChange);
  360. }
  361. }
  362. catch (Exception ex)
  363. {
  364. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListServiceBus-StuList\n{ex.Message}\n{ex.StackTrace}\n{msg}", GroupNames.成都开发測試群組);
  365. }
  366. }
  367. }
  368. }