Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using AipGateway.AIP.Service.Services;
  2. using Microsoft.OpenApi.Models;
  3. using Microsoft.AspNetCore.HttpOverrides;
  4. using System.Net;
  5. using AutoMapper;
  6. using AipGateway.AIP;
  7. using AipGateway.AIP.Service;
  8. using Serilog;
  9. using AipGateway.API.Application;
  10. using AipGateway.API.Application.Interfaces.Services;
  11. using AipGateway.API.Application.Mappings;
  12. using AipGateway.AIP.Service.Services.Interfaces;
  13. using AipDatabase.AIP.Service.Infrastructures;
  14. using AipGateway.API.Application.Configurations;
  15. using Serilog.Extensions.Logging;
  16. using AipGateway.AIP.Service.Repositories;
  17. using System.Diagnostics;
  18. using AipGateway.AIP.Service.WindowsService;
  19. internal class Program
  20. {
  21. private static List<Process> SubProcessList = new List<Process>();
  22. private static void StartSubProcess(int port)
  23. {
  24. var currentProcessPath = Process.GetCurrentProcess().MainModule!.FileName;
  25. var startInfo = new ProcessStartInfo
  26. {
  27. FileName = currentProcessPath,
  28. Arguments = $"{port}",
  29. CreateNoWindow = true,
  30. UseShellExecute = false
  31. };
  32. Process prcs = Process.Start(startInfo)!;
  33. Log.Information("Worker Thread Start {0} ==> Port: {1}, PID: {2}.", currentProcessPath, port, prcs.Id);
  34. SubProcessList.Add(prcs);
  35. }
  36. private static async Task Main(string[] args)
  37. {
  38. var configuration = new ConfigurationBuilder()
  39. .SetBasePath(Directory.GetCurrentDirectory())
  40. .AddJsonFile(
  41. path: "appsettings.json",
  42. optional: false,
  43. reloadOnChange: true)
  44. .AddJsonFile(
  45. path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
  46. optional: true,
  47. reloadOnChange: true)
  48. .Build();
  49. var serillogLogger = new Serilog.LoggerConfiguration()
  50. .ReadFrom.Configuration(configuration)
  51. .MinimumLevel.Information()
  52. .Enrich.FromLogContext()
  53. //.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
  54. .CreateLogger();
  55. Log.Logger = serillogLogger.ForContext<Program>();
  56. int licenseAccounts = LicenseManager.LocalValidateLicense();
  57. if (licenseAccounts <= 0)
  58. {
  59. if (licenseAccounts == 0)
  60. {
  61. Log.Fatal("프로그램 라이센스에 허가된 계정 정보가 없습니다..");
  62. }
  63. else
  64. {
  65. Log.Fatal("프로그램 라이센스 정보를 확인하지 못했습니다.");
  66. }
  67. return;
  68. }
  69. Startup.SetSystemConfig();
  70. try
  71. {
  72. var builder = WebApplication.CreateBuilder(args);
  73. builder.Logging.ClearProviders();
  74. //builder.Logging.AddLog4Net();
  75. builder.Host.UseSerilog((context, services, configuration) => configuration
  76. .ReadFrom.Configuration(context.Configuration)
  77. .ReadFrom.Services(services)
  78. .Enrich.FromLogContext(), true);
  79. if (args.Length == 0)
  80. {
  81. builder.Services.AddWindowsService();
  82. builder.Services.AddHostedService<AipServiceMain>();
  83. }
  84. else
  85. {
  86. builder.Services.AddHostedService<AipServiceSub>();
  87. }
  88. ConfigureSettings(builder.Host, builder.Environment); // 환경설정 파일 설정
  89. if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != null)
  90. {
  91. Log.Information("Start Azure Information RESTFull API Service... License Accounts: {0} EA. [{1}]",
  92. licenseAccounts, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
  93. }
  94. else
  95. {
  96. Log.Information("Start Azure Information RESTFull API Service...License Accounts: {0} EA.", licenseAccounts);
  97. }
  98. ILogger<AipDbRepository> aipDbRepositoryLogger = new SerilogLoggerFactory(serillogLogger).CreateLogger<AipDbRepository>();
  99. ILogger<AipFileService> aipFileServiceLogger = new SerilogLoggerFactory(serillogLogger).CreateLogger<AipFileService>();
  100. ILogger<AipFileManager> aipFileManagerLogger = new SerilogLoggerFactory(serillogLogger).CreateLogger<AipFileManager>();
  101. DatabaseFactory databaseFactory = new DatabaseFactory(builder.Configuration);
  102. AipDbRepository aipDbRepository = new AipDbRepository(aipDbRepositoryLogger, builder.Configuration, databaseFactory);
  103. AipSettings aipSettings = await aipDbRepository.LoadAipConfig();
  104. int defPort = aipSettings.Port;
  105. int Port = defPort;
  106. if (args.Length == 0)
  107. {
  108. //for (int ii = 0; ii < aipSettings.Bindings; ii++)
  109. //{
  110. // Port = defPort + (ii + 1);
  111. // StartSubProcess(Port);
  112. //}
  113. aipSettings.Port = defPort;
  114. aipSettings.ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
  115. }
  116. else
  117. {
  118. if (args.Length != 2)
  119. {
  120. return;
  121. }
  122. int.TryParse(args[0], out Port);
  123. int.TryParse(args[1], out int processId);
  124. aipSettings.Port = Port;
  125. aipSettings.ProcessId = processId;
  126. aipSettings.MipData = aipSettings.MipData + (Port - defPort).ToString();
  127. }
  128. AipFileManager aipFileManager = new AipFileManager(serillogLogger, aipSettings.GetConfig());
  129. if (!Startup.AipFileInitialize(aipFileManager))
  130. {
  131. Log.Error("AipFileInitialize: Failed. {0}, {1}", aipFileManager.LastErrNo, aipFileManager.LastErrMsg);
  132. return;
  133. }
  134. AipFileService aipFileService = new AipFileService(aipFileServiceLogger, aipDbRepository, aipFileManager, aipSettings);
  135. aipFileService.DownloadAipFileInformations();
  136. builder.Services.AddControllers();
  137. //FastEndpoints
  138. //builder.Services.AddFastEndpoints();
  139. builder.Services.AddSwaggerGen(c => {
  140. c.SwaggerDoc("v1", new OpenApiInfo { Title = "Azure Information Protection RESTFull API Service Gateway", Version = "v1" });
  141. //c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
  142. });
  143. builder.Services.Configure<ForwardedHeadersOptions>(options =>
  144. {
  145. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  146. options.KnownNetworks.Clear();
  147. options.KnownProxies.Clear();
  148. });
  149. //https://learn.microsoft.com/ko-kr/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-8.0
  150. //builder.WebHost.ConfigureKestrel((context, serverOptions) =>
  151. //{
  152. // serverOptions.ListenAnyIP(Port);
  153. //});
  154. Log.Information("Start AIP RESTFull Service...Binding Port: {0}.", aipSettings.Port);
  155. builder.WebHost.ConfigureKestrel((context, serverOptions) =>
  156. {
  157. serverOptions.Limits.MaxRequestBodySize = 100_000_000; // [RequestSizeLimit(100_000_000)] --> Controller 위에 선언, IHttpMaxRequestBodySizeFeature
  158. serverOptions.Limits.MaxConcurrentConnections = 200;
  159. serverOptions.Limits.MaxConcurrentUpgradedConnections = 200;
  160. serverOptions.Listen(IPAddress.Any, aipSettings.Port, listenOptions =>
  161. {
  162. //listenOptions.UseHttps("testCert.pfx", "testPassword");
  163. //listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
  164. });
  165. });
  166. builder.Services.InjectDependencies(builder.Configuration);
  167. builder.Services.AddSingleton<AipSettings>(aipSettings);
  168. builder.Services.AddSingleton<IDatabaseFactory>(databaseFactory);
  169. builder.Services.AddSingleton<IAipDbRepository>(aipDbRepository);
  170. builder.Services.AddSingleton<IAipFileService>(aipFileService);
  171. builder.Services.AddSingleton<IDatabaseFactory>(databaseFactory);
  172. builder.Services.AddSingleton<IAipFileService>(aipFileService);
  173. builder.Services.AddScoped<IApiAipService, ApiAipService>();
  174. builder.Services.AddScoped<IApiFileService, ApiFileService>();
  175. builder.Services.AddScoped<IApiStreamService, ApiStreamService>();
  176. // Scheduler Job
  177. var mappingConfig = new MapperConfiguration(mc =>
  178. {
  179. mc.AddProfile(new MappingProfile());
  180. });
  181. IMapper mapper = mappingConfig.CreateMapper();
  182. builder.Services.AddSingleton(mapper);
  183. builder.Services.AddHealthChecks();
  184. builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
  185. {
  186. //builder.WithOrigins("*", "http://localhost:3011", "https://localhost:3011", "https://localhost:7261").AllowAnyMethod().AllowAnyHeader();
  187. }));
  188. var app = builder.Build();
  189. //HTTP Strict Transport Security : Method used by server to declare that they should only be accessed using HTTPS (secure connection) only
  190. app.UseHsts();
  191. app.UseHttpsRedirection();
  192. app.UseRouting();
  193. app.UseCors(builder => builder
  194. .AllowAnyOrigin()
  195. .AllowAnyMethod()
  196. .AllowAnyHeader());
  197. app.UseCors("corsapp");
  198. app.UseAuthentication();
  199. app.UseAuthorization();
  200. //if (app.Environment.IsDevelopment())
  201. {
  202. app.UseSwagger();
  203. app.UseSwaggerUI(options =>
  204. {
  205. options.SwaggerEndpoint("/swagger/v1/swagger.json", "AIP Gateway API v1");
  206. options.RoutePrefix = "swagger-ui";
  207. });
  208. }
  209. app.MapControllers();
  210. app.Run();
  211. Log.Information("Azure Information RESTFull API Service...Stopped cleanly.");
  212. }
  213. catch (Exception ex)
  214. {
  215. Log.Fatal(ex, "Azure Information RESTFull API Service...An unhandled exception occurred during bootstrapping.");
  216. }
  217. finally
  218. {
  219. #if false
  220. foreach(Process prcs in SubProcessList) {
  221. var process = Process.GetProcessById(prcs.Id);
  222. if (process != null)
  223. {
  224. Log.Information("SubProcess Kill: {0}", prcs.Id);
  225. process.Kill();
  226. }
  227. else
  228. {
  229. Log.Error("SubProcess Not Found: {0}", prcs.Id);
  230. }
  231. }
  232. #endif
  233. Log.CloseAndFlush();
  234. }
  235. }
  236. private static void ConfigureSettings(IHostBuilder hostBuilder, IHostEnvironment environment)
  237. {
  238. #if false
  239. IConfigurationBuilder configuration = new ConfigurationBuilder()
  240. .SetBasePath(Directory.GetCurrentDirectory())
  241. .AddJsonFile(
  242. path: "appsettings.json",
  243. optional: false,
  244. reloadOnChange: true)
  245. .AddJsonFile(
  246. path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
  247. optional: true,
  248. reloadOnChange: true)
  249. .AddEnvironmentVariables();
  250. #endif
  251. hostBuilder.ConfigureAppConfiguration(config =>
  252. {
  253. config
  254. .SetBasePath(Directory.GetCurrentDirectory())
  255. .AddJsonFile(
  256. path: "appsettings.json",
  257. optional: false,
  258. reloadOnChange: true)
  259. .AddJsonFile(
  260. path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
  261. optional: true,
  262. reloadOnChange: true)
  263. .AddEnvironmentVariables();
  264. });
  265. }
  266. }