BlobService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. if (!string.IsNullOrWhiteSpace(key))
  144. {
  145. catalog[key] = val;
  146. }
  147. }
  148. usedSize = blobsize;
  149. //1024 * 1024 * 1024=1073741824 =1G
  150. surplus = (total - teach) * 1073741824 - usedSize;
  151. //return (usedSize, teach, total, surplus, catalog);
  152. }
  153. else
  154. {
  155. await _dingDing.SendBotMsg($"{location}Blob空间计算没有缓存{name}", GroupNames.成都开发測試群組);
  156. //没有缓存
  157. var client = _azureStorage.GetBlobContainerClient(name);
  158. var size = await client.GetBlobsCatalogSize();
  159. if (size.Item1 > 0)
  160. {
  161. await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
  162. }
  163. foreach (var key in size.Item2.Keys)
  164. {
  165. await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
  166. await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
  167. }
  168. usedSize = size.Item1.Value;
  169. //1024 * 1024 * 1024=1073741824 =1G
  170. //surplus 可能为负数
  171. surplus = (total - teach) * 1073741824 - usedSize;
  172. catalog = size.Item2;
  173. //return (usedSize, teach, total, surplus, catalog = size.Item2);
  174. }
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. await _dingDing.SendBotMsg($"IES5,{location},GetSurplusSpace \n{ex.Message}\n{ex.StackTrace}\n{name},\n{scope}", GroupNames.醍摩豆服務運維群組);
  180. return (usedSize, teach, total, surplus, catalog);
  181. }
  182. if (usedSize > 0 && total > 0) {
  183. double percent = (surplus * 1.0 * 100 / 1073741824 / total );
  184. if (percent < 10) {
  185. _ = _httpTrigger.RequestHttpTrigger(new { name, scope, percent }, location, "surplus-space-notify");
  186. }
  187. }
  188. return (usedSize, teach, total, surplus, catalog);
  189. }
  190. /// <summary>
  191. /// 记录在redis,使用ttl 进行过期管理
  192. /// </summary>
  193. public class BlobSpaceNotify
  194. {
  195. /// <summary>
  196. /// id=$"{tmdid}-{tag}"
  197. /// </summary>
  198. public string? id { get; set; }
  199. public int tag { get; set; }
  200. public string? containerName { get; set; }
  201. public string? scope { get; set; }
  202. public string? notifyIndex { get; set; }
  203. }
  204. /// <param name="scope">school or private</param>
  205. /// <param name="containerName">school code or tmid</param>
  206. /// <param name="type">doc, res, item... Empty if no need.</param>
  207. /// <param name="periodId">Only for school</param>
  208. public static async Task<List<BlobCount>> BloblogCount(CosmosClient clientc, string scope, string containerName, string type, string periodId)
  209. {
  210. List<BlobCount> bloblogcnt = new List<BlobCount>();
  211. try
  212. {
  213. //必須項檢查
  214. if(scope.Equals("school") && string.IsNullOrWhiteSpace(periodId))
  215. {
  216. return bloblogcnt;
  217. }
  218. //資料取得
  219. var queryslt = new StringBuilder();
  220. queryslt.Append($"SELECT COUNT(1) AS count, c.type FROM c ");
  221. if (scope.Equals("school"))
  222. {
  223. queryslt.Append($"JOIN A1 IN c.periodId WHERE A1 IN ('{periodId}') ");
  224. if(!string.IsNullOrWhiteSpace(type)) queryslt.Append($"AND c.type='{type}'");
  225. queryslt.Append("GROUP BY c.type");
  226. await foreach (var item in clientc.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<BlobCount>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{containerName}") }))
  227. {
  228. bloblogcnt.Add(item);
  229. }
  230. }
  231. else if (scope.Equals("private"))
  232. {
  233. if (!string.IsNullOrWhiteSpace(type)) queryslt.Append($"AND c.type='{type}'");
  234. queryslt.Append("GROUP BY c.type");
  235. await foreach (var item in clientc.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<BlobCount>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{containerName}") }))
  236. {
  237. bloblogcnt.Add(item);
  238. }
  239. }
  240. return bloblogcnt;
  241. }
  242. catch (Exception ex)
  243. {
  244. return bloblogcnt;
  245. }
  246. }
  247. public class UsedBlob
  248. {
  249. public long teach { get; set; }
  250. public long? size { get; set; }
  251. public Dictionary<string, double?> catalog { get; set; }
  252. }
  253. public class BlobCount
  254. {
  255. public string type { get; set; }
  256. public int count { get; set; }
  257. }
  258. }
  259. public class BlobRefreshMessage{
  260. public string id { get; set; }= Guid.NewGuid().ToString();
  261. public string name { get; set; }
  262. public string progress { get; set; }
  263. public string root { get; set; }
  264. }
  265. }