123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- using AipGateway.AIP.Service.Services;
- using Microsoft.OpenApi.Models;
- using Microsoft.AspNetCore.HttpOverrides;
- using System.Net;
- using AutoMapper;
- using AipGateway.AIP;
- using AipGateway.AIP.Service;
- using Serilog;
- using AipGateway.API.Application;
- using AipGateway.API.Application.Interfaces.Services;
- using AipGateway.API.Application.Mappings;
- using AipGateway.AIP.Service.Services.Interfaces;
- using AipDatabase.AIP.Service.Infrastructures;
- using AipGateway.API.Application.Configurations;
- using Serilog.Extensions.Logging;
- using AipGateway.AIP.Service.Repositories;
- using System.Diagnostics;
- using AipGateway.AIP.Service.WindowsService;
- internal class Program
- {
- private static List<Process> SubProcessList = new List<Process>();
- private static void StartSubProcess(int port)
- {
- var currentProcessPath = Process.GetCurrentProcess().MainModule!.FileName;
- var startInfo = new ProcessStartInfo
- {
- FileName = currentProcessPath,
- Arguments = $"{port}",
- CreateNoWindow = true,
- UseShellExecute = false
- };
- Process prcs = Process.Start(startInfo)!;
- Log.Information("Worker Thread Start {0} ==> Port: {1}, PID: {2}.", currentProcessPath, port, prcs.Id);
- SubProcessList.Add(prcs);
- }
- private static async Task Main(string[] args)
- {
- var configuration = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile(
- path: "appsettings.json",
- optional: false,
- reloadOnChange: true)
- .AddJsonFile(
- path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
- optional: true,
- reloadOnChange: true)
- .Build();
- var serillogLogger = new Serilog.LoggerConfiguration()
- .ReadFrom.Configuration(configuration)
- .MinimumLevel.Information()
- .Enrich.FromLogContext()
- //.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
- .CreateLogger();
- Log.Logger = serillogLogger.ForContext<Program>();
- int licenseAccounts = LicenseManager.LocalValidateLicense();
- if (licenseAccounts <= 0)
- {
- if (licenseAccounts == 0)
- {
- Log.Fatal("프로그램 라이센스에 허가된 계정 정보가 없습니다..");
- }
- else
- {
- Log.Fatal("프로그램 라이센스 정보를 확인하지 못했습니다.");
- }
- return;
- }
- Startup.SetSystemConfig();
- try
- {
- var builder = WebApplication.CreateBuilder(args);
- builder.Logging.ClearProviders();
- //builder.Logging.AddLog4Net();
- builder.Host.UseSerilog((context, services, configuration) => configuration
- .ReadFrom.Configuration(context.Configuration)
- .ReadFrom.Services(services)
- .Enrich.FromLogContext(), true);
- if (args.Length == 0)
- {
- builder.Services.AddWindowsService();
- builder.Services.AddHostedService<AipServiceMain>();
- }
- else
- {
- builder.Services.AddHostedService<AipServiceSub>();
- }
- ConfigureSettings(builder.Host, builder.Environment); // 환경설정 파일 설정
- if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != null)
- {
- Log.Information("Start Azure Information RESTFull API Service... License Accounts: {0} EA. [{1}]",
- licenseAccounts, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
- }
- else
- {
- Log.Information("Start Azure Information RESTFull API Service...License Accounts: {0} EA.", licenseAccounts);
- }
- ILogger<AipDbRepository> aipDbRepositoryLogger = new SerilogLoggerFactory(serillogLogger).CreateLogger<AipDbRepository>();
- ILogger<AipFileService> aipFileServiceLogger = new SerilogLoggerFactory(serillogLogger).CreateLogger<AipFileService>();
- ILogger<AipFileManager> aipFileManagerLogger = new SerilogLoggerFactory(serillogLogger).CreateLogger<AipFileManager>();
- DatabaseFactory databaseFactory = new DatabaseFactory(builder.Configuration);
- AipDbRepository aipDbRepository = new AipDbRepository(aipDbRepositoryLogger, builder.Configuration, databaseFactory);
- AipSettings aipSettings = await aipDbRepository.LoadAipConfig();
- int defPort = aipSettings.Port;
- int Port = defPort;
- if (args.Length == 0)
- {
- //for (int ii = 0; ii < aipSettings.Bindings; ii++)
- //{
- // Port = defPort + (ii + 1);
- // StartSubProcess(Port);
- //}
- aipSettings.Port = defPort;
- aipSettings.ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
- }
- else
- {
- if (args.Length != 2)
- {
- return;
- }
-
- int.TryParse(args[0], out Port);
- int.TryParse(args[1], out int processId);
- aipSettings.Port = Port;
- aipSettings.ProcessId = processId;
- aipSettings.MipData = aipSettings.MipData + (Port - defPort).ToString();
- }
- AipFileManager aipFileManager = new AipFileManager(serillogLogger, aipSettings.GetConfig());
- if (!Startup.AipFileInitialize(aipFileManager))
- {
- Log.Error("AipFileInitialize: Failed. {0}, {1}", aipFileManager.LastErrNo, aipFileManager.LastErrMsg);
- return;
- }
- AipFileService aipFileService = new AipFileService(aipFileServiceLogger, aipDbRepository, aipFileManager, aipSettings);
- aipFileService.DownloadAipFileInformations();
- builder.Services.AddControllers();
- //FastEndpoints
- //builder.Services.AddFastEndpoints();
- builder.Services.AddSwaggerGen(c => {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "Azure Information Protection RESTFull API Service Gateway", Version = "v1" });
- //c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
- });
- builder.Services.Configure<ForwardedHeadersOptions>(options =>
- {
- options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
- options.KnownNetworks.Clear();
- options.KnownProxies.Clear();
- });
- //https://learn.microsoft.com/ko-kr/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-8.0
- //builder.WebHost.ConfigureKestrel((context, serverOptions) =>
- //{
- // serverOptions.ListenAnyIP(Port);
- //});
- Log.Information("Start AIP RESTFull Service...Binding Port: {0}.", aipSettings.Port);
- builder.WebHost.ConfigureKestrel((context, serverOptions) =>
- {
- serverOptions.Limits.MaxRequestBodySize = 100_000_000; // [RequestSizeLimit(100_000_000)] --> Controller 위에 선언, IHttpMaxRequestBodySizeFeature
- serverOptions.Limits.MaxConcurrentConnections = 200;
- serverOptions.Limits.MaxConcurrentUpgradedConnections = 200;
- serverOptions.Listen(IPAddress.Any, aipSettings.Port, listenOptions =>
- {
- //listenOptions.UseHttps("testCert.pfx", "testPassword");
- //listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
- });
- });
- builder.Services.InjectDependencies(builder.Configuration);
- builder.Services.AddSingleton<AipSettings>(aipSettings);
- builder.Services.AddSingleton<IDatabaseFactory>(databaseFactory);
- builder.Services.AddSingleton<IAipDbRepository>(aipDbRepository);
- builder.Services.AddSingleton<IAipFileService>(aipFileService);
- builder.Services.AddSingleton<IDatabaseFactory>(databaseFactory);
- builder.Services.AddSingleton<IAipFileService>(aipFileService);
- builder.Services.AddScoped<IApiAipService, ApiAipService>();
- builder.Services.AddScoped<IApiFileService, ApiFileService>();
- builder.Services.AddScoped<IApiStreamService, ApiStreamService>();
- // Scheduler Job
- var mappingConfig = new MapperConfiguration(mc =>
- {
- mc.AddProfile(new MappingProfile());
- });
- IMapper mapper = mappingConfig.CreateMapper();
- builder.Services.AddSingleton(mapper);
- builder.Services.AddHealthChecks();
- builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
- {
- //builder.WithOrigins("*", "http://localhost:3011", "https://localhost:3011", "https://localhost:7261").AllowAnyMethod().AllowAnyHeader();
- }));
-
- var app = builder.Build();
- //HTTP Strict Transport Security : Method used by server to declare that they should only be accessed using HTTPS (secure connection) only
- app.UseHsts();
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseCors(builder => builder
- .AllowAnyOrigin()
- .AllowAnyMethod()
- .AllowAnyHeader());
- app.UseCors("corsapp");
- app.UseAuthentication();
- app.UseAuthorization();
- //if (app.Environment.IsDevelopment())
- {
- app.UseSwagger();
- app.UseSwaggerUI(options =>
- {
- options.SwaggerEndpoint("/swagger/v1/swagger.json", "AIP Gateway API v1");
- options.RoutePrefix = "swagger-ui";
- });
- }
- app.MapControllers();
- app.Run();
- Log.Information("Azure Information RESTFull API Service...Stopped cleanly.");
- }
- catch (Exception ex)
- {
- Log.Fatal(ex, "Azure Information RESTFull API Service...An unhandled exception occurred during bootstrapping.");
- }
- finally
- {
- #if false
- foreach(Process prcs in SubProcessList) {
- var process = Process.GetProcessById(prcs.Id);
- if (process != null)
- {
- Log.Information("SubProcess Kill: {0}", prcs.Id);
- process.Kill();
- }
- else
- {
- Log.Error("SubProcess Not Found: {0}", prcs.Id);
- }
- }
- #endif
- Log.CloseAndFlush();
- }
- }
- private static void ConfigureSettings(IHostBuilder hostBuilder, IHostEnvironment environment)
- {
- #if false
- IConfigurationBuilder configuration = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile(
- path: "appsettings.json",
- optional: false,
- reloadOnChange: true)
- .AddJsonFile(
- path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
- optional: true,
- reloadOnChange: true)
- .AddEnvironmentVariables();
- #endif
- hostBuilder.ConfigureAppConfiguration(config =>
- {
- config
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile(
- path: "appsettings.json",
- optional: false,
- reloadOnChange: true)
- .AddJsonFile(
- path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
- optional: true,
- reloadOnChange: true)
- .AddEnvironmentVariables();
- });
- }
- }
|