BlobService.cs 13 KB

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