BlobService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. using Azure;
  2. using Azure.Cosmos;
  3. using Azure.Messaging.ServiceBus;
  4. using Azure.Storage.Blobs;
  5. using DocumentFormat.OpenXml.Spreadsheet;
  6. using DocumentFormat.OpenXml.Wordprocessing;
  7. using HTEXLib.COMM.Helpers;
  8. using Microsoft.Azure.Cosmos.Table;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.Hosting;
  11. using StackExchange.Redis;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Configuration;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.Json;
  18. using System.Threading.Tasks;
  19. using TEAMModelOS.Models;
  20. using TEAMModelOS.SDK.DI;
  21. using TEAMModelOS.SDK.Extension;
  22. using TEAMModelOS.SDK.Models;
  23. using TEAMModelOS.SDK.Models.Service;
  24. using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
  25. namespace TEAMModelOS.SDK.Services
  26. {
  27. public static class BlobService
  28. {
  29. public static async Task RefreshBlobRoot(BlobRefreshMessage message, AzureServiceBusFactory _serviceBus,IConfiguration _configuration,AzureRedisFactory _azureRedis) {
  30. if (!string.IsNullOrWhiteSpace(message.root) && !string.IsNullOrWhiteSpace(message.name)) {
  31. string lockKey = $"Blob:Lock:{message.name}:{message.root}";
  32. bool exist = await _azureRedis.GetRedisClient(8).KeyExistsAsync(lockKey);
  33. //不存在Blob:Lock:hbcn:video 文件夹在队列中 则加入队列
  34. if (!exist)
  35. {
  36. //保持一天的时间
  37. TimeSpan timeSpan = new TimeSpan(1,0,0);
  38. //加入队列的时间
  39. long action = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  40. await _azureRedis.GetRedisClient(8).StringSetAsync(lockKey, action, expiry: timeSpan);
  41. var messageBlob = new ServiceBusMessage(message.ToJsonString());
  42. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  43. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  44. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  45. }
  46. //如果已经存在,则忽略,不加入队列。
  47. }
  48. }
  49. /// <summary>
  50. /// 获取学校或者个人的剩余空间
  51. /// </summary>
  52. /// <param name="name">学校id 或者醍摩豆id</param>
  53. /// <param name="scope"></param>
  54. /// <param name="_azureCosmos"></param>
  55. /// <param name="_azureRedis"></param>
  56. public static async Task<(long usedSize, long teach, long total, long surplus, Dictionary<string, double?> catalog)>
  57. GetSurplusSpace(string name, string scope,string location, AzureCosmosFactory _azureCosmos, AzureRedisFactory _azureRedis, AzureStorageFactory _azureStorage,DingDing _dingDing, HttpTrigger _httpTrigger)
  58. {
  59. //已经存储的空间
  60. long usedSize = 0;
  61. //分配给教师的
  62. long teach = 0;
  63. //总空间
  64. long total = 0;
  65. // 剩余的
  66. long surplus = 0;
  67. Teacher teacher = null;
  68. Dictionary<string, double?> catalog = new Dictionary<string, double?>();
  69. try
  70. {
  71. if (!string.IsNullOrWhiteSpace(name))
  72. {
  73. if ("school".Equals(scope, StringComparison.OrdinalIgnoreCase))
  74. {
  75. School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(name, new PartitionKey("Base"));
  76. total = school.size;
  77. teach = school.tsize;
  78. //用tsize代替
  79. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ",
  80. // requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{name}") }))
  81. //{
  82. // var json = await JsonDocument.ParseAsync(item.ContentStream);
  83. // foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
  84. // {
  85. // if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
  86. // {
  87. // teach = _size.GetInt32();
  88. // break;
  89. // }
  90. // }
  91. //}
  92. }
  93. else
  94. {
  95. teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>(name, new PartitionKey("Base"));
  96. total = teacher.size;
  97. foreach (var school in teacher.schools)
  98. {
  99. try
  100. {
  101. SchoolTeacher schoolTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<SchoolTeacher>(name, new PartitionKey($"Teacher-{school.schoolId}"));
  102. total += schoolTeacher.size;
  103. }
  104. catch (Exception ex) { }
  105. }
  106. }
  107. long blobsize = 0;
  108. RedisValue value = default;
  109. value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", name);
  110. if (value != default && !value.IsNullOrEmpty)
  111. {
  112. JsonElement record = value.ToString().ToObject<JsonElement>();
  113. if (record.TryGetInt64(out blobsize))
  114. {
  115. }
  116. }
  117. else
  118. {
  119. var client = _azureStorage.GetBlobContainerClient(name);
  120. var size = await client.GetBlobsCatalogSize();
  121. if (size.Item1 > 0)
  122. {
  123. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
  124. }
  125. foreach (var key in size.Item2.Keys)
  126. {
  127. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  128. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  129. }
  130. usedSize = size.Item1.Value;
  131. //1024 * 1024 * 1024=1073741824 =1G
  132. surplus = (total - teach) * 1073741824 - usedSize;
  133. catalog=size.Item2;
  134. //return (usedSize, teach, total, surplus, catalog = size.Item2);
  135. }
  136. SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{name}");
  137. if (Scores != null)
  138. {
  139. foreach (var score in Scores)
  140. {
  141. double val = score.Score;
  142. string key = score.Element.ToString();
  143. catalog.Add(key, val);
  144. }
  145. usedSize = blobsize;
  146. //1024 * 1024 * 1024=1073741824 =1G
  147. surplus = (total - teach) * 1073741824 - usedSize;
  148. //return (usedSize, teach, total, surplus, catalog);
  149. }
  150. else
  151. {
  152. //没有缓存
  153. var client = _azureStorage.GetBlobContainerClient(name);
  154. var size = await client.GetBlobsCatalogSize();
  155. if (size.Item1 > 0)
  156. {
  157. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
  158. }
  159. foreach (var key in size.Item2.Keys)
  160. {
  161. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  162. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  163. }
  164. usedSize = size.Item1.Value;
  165. //1024 * 1024 * 1024=1073741824 =1G
  166. //surplus 可能为负数
  167. surplus = (total - teach) * 1073741824 - usedSize;
  168. catalog = size.Item2;
  169. //return (usedSize, teach, total, surplus, catalog = size.Item2);
  170. }
  171. }
  172. }
  173. catch (Exception ex)
  174. {
  175. await _dingDing.SendBotMsg($"IES5,{location},blob/used-space()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  176. return (usedSize, teach, total, surplus, catalog);
  177. }
  178. if (usedSize > 0 && total > 0) {
  179. double percent = surplus / total * 1073741824 * 100;
  180. //
  181. _ = _httpTrigger.RequestHttpTrigger(new { }, location, "surplus-space-notify");
  182. }
  183. return (usedSize, teach, total, surplus, catalog);
  184. }
  185. /// <summary>
  186. /// 记录在redis,使用ttl 进行过期管理
  187. /// </summary>
  188. public class BlobSpaceNotify
  189. {
  190. /// <summary>
  191. /// id=$"{tmdid}-{tag}"
  192. /// </summary>
  193. public string? id { get; set; }
  194. public int tag { get; set; }
  195. public string? containerName { get; set; }
  196. public string? scope { get; set; }
  197. public string? notifyIndex { get; set; }
  198. }
  199. /// <param name="scope">school or private</param>
  200. /// <param name="containerName">school code or tmid</param>
  201. /// <param name="type">doc, res, item... Empty if no need.</param>
  202. /// <param name="periodId">Only for school</param>
  203. public static async Task<List<BlobCount>> BloblogCount(CosmosClient clientc, string scope, string containerName, string type, string periodId)
  204. {
  205. List<BlobCount> bloblogcnt = new List<BlobCount>();
  206. try
  207. {
  208. //必須項檢查
  209. if(scope.Equals("school") && string.IsNullOrWhiteSpace(periodId))
  210. {
  211. return bloblogcnt;
  212. }
  213. //資料取得
  214. var queryslt = new StringBuilder();
  215. queryslt.Append($"SELECT COUNT(1) AS count, c.type FROM c ");
  216. if (scope.Equals("school"))
  217. {
  218. queryslt.Append($"JOIN A1 IN c.periodId WHERE A1 IN ('{periodId}') ");
  219. if(!string.IsNullOrWhiteSpace(type)) queryslt.Append($"AND c.type='{type}'");
  220. queryslt.Append("GROUP BY c.type");
  221. await foreach (var item in clientc.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<BlobCount>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{containerName}") }))
  222. {
  223. bloblogcnt.Add(item);
  224. }
  225. }
  226. else if (scope.Equals("private"))
  227. {
  228. if (!string.IsNullOrWhiteSpace(type)) queryslt.Append($"AND c.type='{type}'");
  229. queryslt.Append("GROUP BY c.type");
  230. await foreach (var item in clientc.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<BlobCount>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{containerName}") }))
  231. {
  232. bloblogcnt.Add(item);
  233. }
  234. }
  235. return bloblogcnt;
  236. }
  237. catch (Exception ex)
  238. {
  239. return bloblogcnt;
  240. }
  241. }
  242. public class UsedBlob
  243. {
  244. public long teach { get; set; }
  245. public long? size { get; set; }
  246. public Dictionary<string, double?> catalog { get; set; }
  247. }
  248. public class BlobCount
  249. {
  250. public string type { get; set; }
  251. public int count { get; set; }
  252. }
  253. }
  254. public class BlobRefreshMessage{
  255. public string id { get; set; }= Guid.NewGuid().ToString();
  256. public string name { get; set; }
  257. public string progress { get; set; }
  258. public string root { get; set; }
  259. }
  260. }