Program.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Management;
  5. using System.Net.Http;
  6. using System.Text.Json.Serialization;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using AipGateway.AIP;
  11. using Serilog;
  12. using Newtonsoft.Json;
  13. using System.IO;
  14. namespace AipGateway.Test
  15. {
  16. class Program
  17. {
  18. private static string _email = "seungho@ms365.hanteinfo.com";
  19. private static string _apiKey = "24826125-188B-4875-A841-F9146DD267F0";
  20. private static string _aipGuid = "1098bdb0-f2bc-43d3-b9c7-e610431fc1a4";
  21. private static AipFileManager _aipFileManager;
  22. private static string[] dispFileNames = {
  23. "sample.pptx",
  24. "sample-1.pptx", "sample-2.pptx", "sample-3.pptx", "sample-4.pptx", "sample-5.pptx",
  25. "sample-6.pptx", "sample-7.pptx", "sample-8.pptx", "sample-9.pptx", "sample-10.pptx",
  26. "sample-11.pptx", "sample-12.pptx", "sample-13.pptx", "sample-14.pptx", "sample-15.pptx",
  27. "sample-16.pptx", "sample-17.pptx", "sample-18.pptx", "sample-19.pptx", "sample-20.pptx",
  28. "sample-21.pptx", "sample-22.pptx", "sample-23.pptx", "sample-24.pptx", "sample-25.pptx",
  29. "sample-26.pptx", "sample-27.pptx", "sample-28.pptx", "sample-29.pptx", "sample-30.pptx",
  30. };
  31. private static string[] realFileNames = dispFileNames;
  32. public static long GetElapsedMilliseconds(long start)
  33. {
  34. return (long)((Stopwatch.GetTimestamp() - start) * 1000 / (double)Stopwatch.Frequency);
  35. }
  36. public static void SetSystemConfig()
  37. {
  38. ThreadPool.GetAvailableThreads(out int workerThreads1, out int completionPortThreads1);
  39. ThreadPool.GetMaxThreads(out int workerThreads2, out int completionPortThreads2);
  40. ThreadPool.GetMinThreads(out int workerThreads3, out int completionPortThreads3);
  41. Log.Information(" AvailableThreads: worker({0}), port({1})", workerThreads1, completionPortThreads1);
  42. Log.Information(" MaxThreads: worker({0}), port({1})", workerThreads2, completionPortThreads2);
  43. Log.Information(" MinThreads: worker({0}), port({1})", workerThreads3, completionPortThreads3);
  44. Log.Information(" UseNagleAlgorithm: {0}", System.Net.ServicePointManager.UseNagleAlgorithm);
  45. System.Net.ServicePointManager.UseNagleAlgorithm = false;
  46. Log.Information(" UseNagleAlgorithm: {0}, Application Set.", System.Net.ServicePointManager.UseNagleAlgorithm);
  47. Log.Information(" Expect100Continue: {0}", System.Net.ServicePointManager.Expect100Continue);
  48. System.Net.ServicePointManager.Expect100Continue = false;
  49. Log.Information(" Expect100Continue: {0}, Application Set.", System.Net.ServicePointManager.Expect100Continue);
  50. Log.Information(" CheckCertificateRevocationList: {0}", System.Net.ServicePointManager.CheckCertificateRevocationList);
  51. System.Net.ServicePointManager.CheckCertificateRevocationList = true;
  52. Log.Information(" CheckCertificateRevocationList: {0}, Application Set.", System.Net.ServicePointManager.CheckCertificateRevocationList);
  53. Log.Information("DefaultPersistentConnectionLimit: {0}", System.Net.ServicePointManager.DefaultPersistentConnectionLimit);
  54. Log.Information(" DefaultConnectionLimit: {0}", System.Net.ServicePointManager.DefaultConnectionLimit);
  55. System.Net.ServicePointManager.DefaultConnectionLimit = 2048;
  56. Log.Information(" DefaultConnectionLimit: {0}, Application Set.", System.Net.ServicePointManager.DefaultConnectionLimit);
  57. // Bump up the min threads reserved for this app to ramp connections faster - minWorkerThreads defaults to 4, minIOCP defaults to 4
  58. ThreadPool.SetMinThreads(100, 100);
  59. // Change max connections from .NET to a remote service default: 2
  60. //System.Net.ServicePointManager.DefaultConnectionLimit = 65000;
  61. // Turn off the Expect 100 to continue message - 'true' will cause the caller to wait until it round-trip confirms a connection to the server
  62. //System.Net.ServicePointManager.Expect100Continue = false;
  63. // Can decrease overall transmission overhead but can cause delay in data packet arrival
  64. //System.Net.ServicePointManager.UseNagleAlgorithm = false;
  65. }
  66. static void Main(string[] args)
  67. {
  68. AipConfig aipConfig = new AipConfig
  69. {
  70. AppName = "AIP.Gateway", // 어플리케이션 이름
  71. AppVersion = "1.0.0", // 어플리케이션 버전
  72. ClientId = "0e225915-3be3-419c-aa04-284d7de5e16b", // 어플리케이션 ID(클라이언트 ID)
  73. TenantId = "2e58414a-c6ae-43ff-aaf5-45ab8b78a404", // 디렉토리(테넌트) ID
  74. MipData = "c:\\temp\\app_data\\mip_data", // Mip Data Path
  75. Domain = "AIP.Gateway", // Domain
  76. EMail = "seungho@ms365.hanteinfo.com", // User E-Mail
  77. SecretValue = "CvW8Q~0iANtLN1Y2EXR_nVyYb_tQTDwjW-Z7Ndg3", // 인증 비밀번호
  78. CertThumbPrint = "C:\\Data\\SSL\\mip\\mip_gateway.pfx" // 인증서 지문
  79. };
  80. string tempLoginType = "authLoginCert";
  81. AipAuthLoginType loginType = (AipAuthLoginType)Enum.Parse(typeof(AipAuthLoginType), tempLoginType, true);
  82. aipConfig.LoginType = loginType;
  83. var serillogLogger = new LoggerConfiguration()
  84. .ReadFrom.AppSettings(filePath: AppDomain.CurrentDomain.BaseDirectory + @"App.config")
  85. .WriteTo.Logger(cfg =>
  86. cfg.ReadFrom.AppSettings(filePath: AppDomain.CurrentDomain.BaseDirectory + @"serilog.config"))
  87. .MinimumLevel.Information()
  88. .Enrich.FromLogContext()
  89. //.WriteTo.Console()
  90. .CreateLogger();
  91. Log.Logger = serillogLogger.ForContext<Program>();
  92. SetSystemConfig();
  93. //Log.Error("{0}", args);
  94. if (args.Length > 0)
  95. {
  96. int.TryParse(args[0], out int idx);
  97. if (idx < 0 || idx > dispFileNames.Length)
  98. {
  99. Log.Error("Argument index error: {0}", idx);
  100. return;
  101. }
  102. string dispFileName = "c:\\data\\source\\" + dispFileNames[idx];
  103. string realFileName = "c:\\data\\source\\" + dispFileNames[idx];
  104. string actualFileName = "c:\\data\\target\\" + dispFileNames[idx];
  105. string fmtIdx = $"mip_data_{idx}";
  106. AipConfig aipConfigChild = new AipConfig
  107. {
  108. AppName = "AIP.Gateway", // 어플리케이션 이름
  109. AppVersion = "1.0.0", // 어플리케이션 버전
  110. ClientId = "0e225915-3be3-419c-aa04-284d7de5e16b", // 어플리케이션 ID(클라이언트 ID)
  111. TenantId = "2e58414a-c6ae-43ff-aaf5-45ab8b78a404", // 디렉토리(테넌트) ID
  112. MipData = "c:\\temp\\app_data\\" + fmtIdx, // Mip Data Path
  113. Domain = "AIP.Gateway", // Domain
  114. EMail = "seungho@ms365.hanteinfo.com", // User E-Mail
  115. SecretValue = "CvW8Q~0iANtLN1Y2EXR_nVyYb_tQTDwjW-Z7Ndg3", // 인증 비밀번호
  116. CertThumbPrint = "C:\\Data\\SSL\\mip\\mip_gateway.pfx" // 인증서 지문
  117. };
  118. _aipFileManager = new AipFileManager(serillogLogger, aipConfigChild);
  119. _aipFileManager.Initialize();
  120. _aipFileManager.CreateProfile();
  121. _aipFileManager.CreateEngine();
  122. SetLabel(dispFileName, realFileName, actualFileName);
  123. Thread.Sleep(30000);
  124. return;
  125. }
  126. Log.Information("Worker Thread Total {0} EA.", dispFileNames.Length);
  127. for (int ii = 0; ii < dispFileNames.Length; ii++)
  128. {
  129. //StartChildProcess(ii);
  130. }
  131. _aipFileManager = new AipFileManager(serillogLogger, aipConfig);
  132. _aipFileManager.Initialize();
  133. _aipFileManager.CreateProfile();
  134. _aipFileManager.CreateEngine();
  135. Log.Information("SensitivityLabels=======================================================================");
  136. List<AipLabel> aipLabels = _aipFileManager.SensitivityLabels();
  137. foreach (var label in aipLabels)
  138. {
  139. Log.Information("ID: {0}, NAME: {1}", label.Id, label.Name);
  140. if (label.Children.Count > 0)
  141. {
  142. foreach (AipLabel child in label.Children)
  143. {
  144. Log.Information("\tID: {0}, NAME: {1}", child.Id, child.Name);
  145. }
  146. }
  147. }
  148. Log.Information("ListSensitivityLabels=======================================================================");
  149. List<AipLabel> labels2 = _aipFileManager.ListSensitivityLabels();
  150. foreach (var v in labels2)
  151. {
  152. Log.Information("Label List: {0}, {1}, {2}", v.Id, v.Name, v.IsActive);
  153. if (v.Children.Count > 0)
  154. {
  155. foreach (AipLabel child in v.Children)
  156. {
  157. Log.Information("\tID: {0}, NAME: {1}", child.Id, child.Name);
  158. }
  159. }
  160. }
  161. Log.Information("GetTemplates=======================================================================");
  162. List<AipTemplate> templates = _aipFileManager.GetTemplates();
  163. foreach (var v in templates)
  164. {
  165. Log.Information("Template: {0}, {1}, {2}", v.Id, v.Name, v.Description);
  166. }
  167. Log.Information("=======================================================================");
  168. ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystemProduct");
  169. foreach (ManagementObject obj in searcher.Get())
  170. {
  171. string uniqueId = obj["UUID"].ToString();
  172. Log.Information("유일한 식별자 (UUID): {0}", uniqueId);
  173. }
  174. Log.Information("=======================================================================");
  175. Log.Information("=======================================================================\r\n\r\n");
  176. int qryMode = 2;
  177. if (args.Length > 0)
  178. {
  179. int.TryParse(args[0], out qryMode);
  180. }
  181. if (qryMode == 0)
  182. {
  183. SetLabelsAll();
  184. }
  185. else if (qryMode == 1)
  186. {
  187. Test1();
  188. //SetLabelsAllAsync(99);
  189. }
  190. else if (qryMode == 2)
  191. {
  192. SetLabelsApiCallAllAsync();
  193. }
  194. #if false
  195. Log.Information("Waiting Child Process =======================================================================");
  196. var currentProcessPath = Process.GetCurrentProcess().MainModule.FileName;
  197. Process[] precesses = Process.GetProcessesByName(currentProcessPath);
  198. while (precesses != null && precesses.Length != 0 && precesses.Length != 1)
  199. {
  200. foreach (var process in precesses)
  201. {
  202. process.EnableRaisingEvents = true;
  203. process.Exited += (sender, eventArgs) =>
  204. {
  205. Log.Information("Child process {0} has exited.", process.Id);
  206. };
  207. }
  208. precesses = Process.GetProcessesByName(currentProcessPath);
  209. }
  210. #endif
  211. Log.Information("Press a key to continue...");
  212. Console.ReadKey();
  213. Log.CloseAndFlush();
  214. }
  215. public static void SetLabelsAll()
  216. {
  217. var startTotal = Stopwatch.GetTimestamp();
  218. Log.Information("SetLabel Tatal {0} EA. Start.", dispFileNames.Length);
  219. for (int ii = 0; ii < dispFileNames.Length; ii++)
  220. {
  221. string dispFileName = "c:\\data\\source\\" + dispFileNames[ii];
  222. string realFileName = "c:\\data\\source\\" + dispFileNames[ii];
  223. string actualFileName = "c:\\data\\target\\" + dispFileNames[ii];
  224. var start = Stopwatch.GetTimestamp();
  225. //Log.Information("SetLabel Start: {0}", dispFileName);
  226. _aipFileManager.SetLabel(realFileName, actualFileName, _email, _aipGuid, "", "string");
  227. Log.Information("SetLabel ..End: {0} ms. {1}", GetElapsedMilliseconds(start), dispFileName);
  228. }
  229. Log.Information("SetLabel Tatal {0} EA. ..Stop. {1} ms.", dispFileNames.Length, GetElapsedMilliseconds(startTotal));
  230. }
  231. public static void SetLabel(string dispFileName, string realFileName, string actualFileName)
  232. {
  233. var start = Stopwatch.GetTimestamp();
  234. Log.Information("SetLabel Start: {0}", dispFileName);
  235. _aipFileManager.SetLabel(realFileName, actualFileName, _email, _aipGuid, "", "string");
  236. Log.Information("SetLabel ..End: {0} ms. {1}", GetElapsedMilliseconds(start), dispFileName);
  237. }
  238. public static async void Test1()
  239. {
  240. var startTotal = Stopwatch.GetTimestamp();
  241. int reqIdx = 0;
  242. await SetLabelsAllAsync(reqIdx++);
  243. await SetLabelsAllAsync(reqIdx++);
  244. await SetLabelsAllAsync(reqIdx++);
  245. await SetLabelsAllAsync(reqIdx++);
  246. await SetLabelsAllAsync(reqIdx++);
  247. Log.Error("&&&&&&&&&&&&&&&&&&&&&&&&&&&&& SetLabel Tatal {0} EA. ..Stop. {1} ms.", dispFileNames.Length, GetElapsedMilliseconds(startTotal));
  248. }
  249. public static async Task<bool> SetLabelsAllAsync(int reqIdx)
  250. {
  251. var startTotal = Stopwatch.GetTimestamp();
  252. Log.Error("SetLabelsAllAsync Tatal {0} EA. Start.{1}.", dispFileNames.Length, reqIdx);
  253. List<SetFileInfo> result = new List<SetFileInfo>();
  254. var tasks = new List<Task<SetFileInfo>>();
  255. for (int ii = 0; ii < dispFileNames.Length; ii++)
  256. {
  257. string dispFileName = "c:\\data\\source\\" + dispFileNames[ii];
  258. string realFileName = "c:\\data\\source\\" + dispFileNames[ii];
  259. string actualFileName = "c:\\data\\target\\" + dispFileNames[ii];
  260. //SetFileInfo result = _aipFileManager.SetLabel(realFileName, actualFileName, aipConfig.EMail, _aipGuid, "", "string");
  261. tasks.Add( Task.Run(() =>
  262. {
  263. //var start = Stopwatch.GetTimestamp();
  264. //Log.Information("SetLabel Start: {0}", dispFileName);
  265. Thread.Sleep(100);
  266. SetFileInfo fileInfo = _aipFileManager.SetLabel(realFileName, actualFileName, _email, _aipGuid, "", "string");
  267. //Log.Information("SetLabel ..End: {0} ms. {1}", GetElapsedMilliseconds(start), dispFileName);
  268. return fileInfo;
  269. }));
  270. }
  271. await Task.WhenAll(tasks);
  272. Log.Error("====================== SetLabelsAllAsync Tatal {0} EA. ..Stop. {1}, {2} ms.", dispFileNames.Length, reqIdx, GetElapsedMilliseconds(startTotal));
  273. return true;
  274. }
  275. static async void SetLabelsApiCallAllAsync()
  276. {
  277. var startTotal = Stopwatch.GetTimestamp();
  278. //Log.Information("SetLabel Tatal {0} EA. Start.", dispFileNames.Length);
  279. int reqIdx = 0;
  280. await SetLabelsApiCallAsync(reqIdx++);
  281. await SetLabelsApiCallAsync(reqIdx++);
  282. await SetLabelsApiCallAsync(reqIdx++);
  283. await SetLabelsApiCallAsync(reqIdx++);
  284. await SetLabelsApiCallAsync(reqIdx++);
  285. await SetLabelsApiCallAsync(reqIdx++);
  286. await SetLabelsApiCallAsync(reqIdx++);
  287. await SetLabelsApiCallAsync(reqIdx++);
  288. await SetLabelsApiCallAsync(reqIdx++);
  289. await SetLabelsApiCallAsync(reqIdx++);
  290. await SetLabelsApiCallAsync(reqIdx++);
  291. await SetLabelsApiCallAsync(reqIdx++);
  292. await SetLabelsApiCallAsync(reqIdx++);
  293. await SetLabelsApiCallAsync(reqIdx++);
  294. await SetLabelsApiCallAsync(reqIdx++);
  295. await SetLabelsApiCallAsync(reqIdx++);
  296. await SetLabelsApiCallAsync(reqIdx++);
  297. await SetLabelsApiCallAsync(reqIdx++);
  298. await SetLabelsApiCallAsync(reqIdx++);
  299. await SetLabelsApiCallAsync(reqIdx++);
  300. await SetLabelsApiCallAsync(reqIdx++);
  301. await SetLabelsApiCallAsync(reqIdx++);
  302. await SetLabelsApiCallAsync(reqIdx++);
  303. await SetLabelsApiCallAsync(reqIdx++);
  304. await SetLabelsApiCallAsync(reqIdx++);
  305. await SetLabelsApiCallAsync(reqIdx++);
  306. await SetLabelsApiCallAsync(reqIdx++);
  307. await SetLabelsApiCallAsync(reqIdx++);
  308. await SetLabelsApiCallAsync(reqIdx++);
  309. await SetLabelsApiCallAsync(reqIdx++);
  310. Log.Error("&&&&&&&&&&&&&&&&&&&&&&&&&&&&& SetLabel Tatal {0} EA. ..Stop. {1} ms.", dispFileNames.Length, GetElapsedMilliseconds(startTotal));
  311. }
  312. static async Task<bool> SetLabelsApiCallAsync(int reqIdx)
  313. {
  314. var startTotal = Stopwatch.GetTimestamp();
  315. Log.Error("SetLabelsApiCallAsync Tatal {0} EA. Start. {1}.", dispFileNames.Length, reqIdx);
  316. HttpClient _httpClient = new HttpClient(new HttpClientHandler
  317. {
  318. MaxConnectionsPerServer = int.MaxValue
  319. });
  320. _httpClient.DefaultRequestHeaders.ConnectionClose = false;
  321. _httpClient.Timeout = TimeSpan.FromSeconds(20);
  322. int Port = 7000;
  323. int seq = 0;
  324. List<SetFileInfo> result = new List<SetFileInfo>();
  325. var tasks = new List<Task<ApiResponseModel<ResponseFile>>>();
  326. for (int ii = 0; ii < dispFileNames.Length; ii++)
  327. {
  328. string dispFileName = dispFileNames[ii];
  329. string realFileName = dispFileNames[ii];
  330. string actualFileName = dispFileNames[ii];
  331. RequestFileSet reqFileSet = new RequestFileSet
  332. {
  333. apiKey = _apiKey,
  334. email = _email,
  335. aipGuid = _aipGuid,
  336. comment = "comment",
  337. file = new RequestFile
  338. {
  339. dispFileName = dispFileName,
  340. realFileName = realFileName,
  341. }
  342. };
  343. var json = JsonConvert.SerializeObject(reqFileSet);
  344. var content = new StringContent(json, Encoding.UTF8, "application/json");
  345. string reqUri = $"http://localhost:{Port+ seq++}/api/v1/file/set-label";
  346. if (seq >= 31) seq = 0;
  347. //Log.Information($"{reqUri}");
  348. //var start0 = Stopwatch.GetTimestamp();
  349. //SetFileInfo tempInfo = SendRequestsAsync(_httpClient, reqUri, reqFileSet).Result;
  350. //Log.Information("SetLabel Start: {0}", DateTime.Now);
  351. //var response = await _httpClient.PostAsync(reqUri, content);//.ConfigureAwait(false);
  352. //Log.Information("SetLabel ..End: {0} ms. {1}", GetElapsedMilliseconds(start0), reqUri);
  353. tasks.Add(Task.Run(() =>
  354. {
  355. var start = Stopwatch.GetTimestamp();
  356. ApiResponseModel<ResponseFile> fileInfo = SendRequestsAsync(_httpClient, reqUri, reqFileSet).Result;
  357. //Log.Information("SetLabel ..End: {0} ms. {1}", GetElapsedMilliseconds(start), JsonConvert.SerializeObject(fileInfo));
  358. return fileInfo;
  359. }));
  360. }
  361. await Task.WhenAll(tasks);
  362. Log.Error("**************** SetLabelsApiCallAsync Tatal {0} EA. ..Stop. {1}, {2} ms.", dispFileNames.Length, reqIdx, GetElapsedMilliseconds(startTotal));
  363. return true;
  364. }
  365. private static async Task<ApiResponseModel<ResponseFile>> SendRequestsAsync(HttpClient httpClient, string reqUri, RequestFileSet reqFileSet)
  366. {
  367. var content = new StringContent(JsonConvert.SerializeObject(reqFileSet), Encoding.UTF8, "application/json");
  368. var response = await httpClient.PostAsync(reqUri, content);//.ConfigureAwait(false);
  369. if (response.IsSuccessStatusCode)
  370. {
  371. Log.Information($"Request successful for: {reqFileSet.file.dispFileName}");
  372. }
  373. else
  374. {
  375. Log.Error($"Request failed for: {reqFileSet.file.dispFileName}. Status code: {response.StatusCode}");
  376. }
  377. //Log.Error("{0}", JsonConvert.SerializeObject(response.Content.ToString()));
  378. //string stringContents = await response.Content.ReadAsStringAsync();
  379. //Log.Error($"Contents: {stringContents}");
  380. //return JsonConvert.DeserializeObject<ApiResponseModel<ResponseFile>>(stringContents);
  381. return JsonConvert.DeserializeObject<ApiResponseModel<ResponseFile>>(await response.Content.ReadAsStringAsync());
  382. }
  383. static void StartChildProcess(int idx)
  384. {
  385. var currentProcessPath = Process.GetCurrentProcess().MainModule.FileName;
  386. var startInfo = new ProcessStartInfo
  387. {
  388. FileName = currentProcessPath,
  389. Arguments = $"{idx}",
  390. CreateNoWindow = true,
  391. UseShellExecute = false
  392. };
  393. Process prcs = Process.Start(startInfo);
  394. Log.Information("Worker Thread Start {0} ==> {1}, {2}, {3}.", idx, prcs.Id, prcs.SessionId, prcs.ProcessName);
  395. }
  396. }
  397. }