2024-08-04 18:44:33 -05:00
|
|
|
using LANCommander.Server.Data;
|
|
|
|
|
using LANCommander.Server.Hubs;
|
|
|
|
|
using LANCommander.Server.Services;
|
2023-01-02 15:44:04 -06:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2023-04-19 18:09:34 -05:00
|
|
|
using Hangfire;
|
2023-11-17 12:32:09 -06:00
|
|
|
using Microsoft.Data.Sqlite;
|
2024-05-01 21:32:21 -05:00
|
|
|
using Microsoft.AspNetCore.Http.Features;
|
2024-08-12 00:15:16 -05:00
|
|
|
using LANCommander.SDK.Enums;
|
2024-08-28 20:33:59 -05:00
|
|
|
using Serilog;
|
2025-01-02 11:40:15 +11:00
|
|
|
using LANCommander.Server;
|
2025-02-08 14:07:29 -06:00
|
|
|
using LANCommander.Server.Models;
|
|
|
|
|
|
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
|
|
|
|
|
|
builder.AddLogger();
|
|
|
|
|
|
|
|
|
|
// Add services to the container.
|
|
|
|
|
Log.Debug("Loading settings");
|
|
|
|
|
LANCommanderSettings settings = SettingService.GetSettings(true);
|
|
|
|
|
builder.Services.AddSingleton(settings);
|
|
|
|
|
Log.Debug("Validating settings");
|
|
|
|
|
if (settings.Authentication.TokenSecret.Length < 16)
|
2023-02-12 17:32:59 -06:00
|
|
|
{
|
2025-02-08 14:07:29 -06:00
|
|
|
Log.Debug("JWT token secret is too short. Regenerating...");
|
|
|
|
|
settings.Authentication.TokenSecret = Guid.NewGuid().ToString();
|
|
|
|
|
SettingService.SaveSettings(settings);
|
|
|
|
|
}
|
|
|
|
|
Log.Debug("Done validating settings");
|
|
|
|
|
|
|
|
|
|
builder.AddRazor();
|
|
|
|
|
builder.AddSignalR();
|
|
|
|
|
builder.AddCors();
|
|
|
|
|
builder.AddControllers();
|
|
|
|
|
|
|
|
|
|
builder.Services.AddAutoMapper(typeof(LANCommanderMappingProfile));
|
|
|
|
|
|
|
|
|
|
builder.WebHost.ConfigureKestrel((ctx, options) =>
|
|
|
|
|
{
|
|
|
|
|
var settings = options.ApplicationServices.GetRequiredService<LANCommanderSettings>();
|
|
|
|
|
var logger = options.ApplicationServices.GetRequiredService<ILogger<Program>>();
|
|
|
|
|
logger.LogDebug("Starting web server on port {Port}", settings.Port);
|
|
|
|
|
// Configure as HTTP only
|
|
|
|
|
options.ListenAnyIP(settings.Port);
|
|
|
|
|
|
|
|
|
|
options.Limits.MaxRequestBodySize = long.MaxValue;
|
|
|
|
|
options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(5);
|
|
|
|
|
}).UseKestrel();
|
|
|
|
|
|
|
|
|
|
builder.AddIdentity(settings);
|
|
|
|
|
|
|
|
|
|
builder.AddHangfire();
|
|
|
|
|
|
|
|
|
|
builder.Services.AddFusionCache();
|
|
|
|
|
|
|
|
|
|
Log.Debug("Registering Swashbuckle");
|
|
|
|
|
builder.Services.AddEndpointsApiExplorer();
|
|
|
|
|
builder.Services.AddSwaggerGen();
|
|
|
|
|
|
|
|
|
|
Log.Debug("Registering AntDesign Blazor");
|
|
|
|
|
builder.Services.AddAntDesign();
|
|
|
|
|
|
|
|
|
|
builder.Services.AddHttpClient();
|
|
|
|
|
|
|
|
|
|
builder.WebHost.UseStaticWebAssets();
|
|
|
|
|
|
|
|
|
|
builder.AddLANCommanderServices(settings);
|
|
|
|
|
builder.AddDatabase();
|
|
|
|
|
|
|
|
|
|
builder.Services.Configure<FormOptions>(options =>
|
|
|
|
|
{
|
|
|
|
|
options.MultipartBodyLengthLimit = long.MaxValue;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
Log.Debug("Building Application");
|
|
|
|
|
var app = builder.Build();
|
|
|
|
|
|
|
|
|
|
app.UseCors("CorsPolicy");
|
|
|
|
|
|
|
|
|
|
app.MapHub<GameServerHub>("/hubs/gameserver");
|
|
|
|
|
|
|
|
|
|
app.UseRobots();
|
|
|
|
|
app.UseApiVersioning();
|
|
|
|
|
|
|
|
|
|
// Configure the HTTP request pipeline.
|
|
|
|
|
if (app.Environment.IsDevelopment())
|
|
|
|
|
{
|
|
|
|
|
Log.Debug("App has been run in a development environment");
|
|
|
|
|
app.UseMigrationsEndPoint();
|
|
|
|
|
app.UseSwagger();
|
|
|
|
|
app.UseSwaggerUI();
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
app.UseExceptionHandler("/Home/Error");
|
|
|
|
|
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
|
|
|
|
app.UseHsts();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
app.UseHangfireDashboard();
|
|
|
|
|
|
|
|
|
|
// app.UseHttpsRedirection();
|
|
|
|
|
app.UseStaticFiles();
|
|
|
|
|
|
|
|
|
|
app.UseRouting();
|
|
|
|
|
|
|
|
|
|
app.UseAuthentication();
|
|
|
|
|
app.UseAuthorization();
|
|
|
|
|
|
|
|
|
|
app.UseMvcWithDefaultRoute();
|
|
|
|
|
|
|
|
|
|
Log.Debug("Registering Endpoints");
|
|
|
|
|
|
|
|
|
|
app.MapHub<LoggingHub>("/logging");
|
|
|
|
|
|
|
|
|
|
app.UseEndpoints(endpoints =>
|
|
|
|
|
{
|
|
|
|
|
endpoints.MapBlazorHub();
|
|
|
|
|
endpoints.MapFallbackToPage("/_Host");
|
|
|
|
|
endpoints.MapControllers();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
PrepareDirectories(app);
|
|
|
|
|
|
|
|
|
|
await EnsureDatabase(app);
|
|
|
|
|
|
|
|
|
|
await InitializeServerProcesses(app);
|
|
|
|
|
|
2025-01-02 11:40:15 +11:00
|
|
|
app.Run();
|
2025-02-08 14:07:29 -06:00
|
|
|
|
|
|
|
|
static void PrepareDirectories(WebApplication app)
|
|
|
|
|
{
|
|
|
|
|
var settings = app.Services.GetRequiredService<LANCommanderSettings>();
|
|
|
|
|
var logger = app.Services.GetRequiredService<ILogger<Program>>();
|
|
|
|
|
logger.LogDebug("Ensuring required directories exist");
|
|
|
|
|
|
|
|
|
|
IEnumerable<string> directories = [
|
|
|
|
|
settings.Logs.StoragePath,
|
|
|
|
|
settings.Archives.StoragePath,
|
|
|
|
|
settings.UserSaves.StoragePath,
|
|
|
|
|
settings.Media.StoragePath,
|
|
|
|
|
settings.Update.StoragePath,
|
|
|
|
|
"Snippets",
|
|
|
|
|
"Backups"
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
foreach (var directory in directories)
|
2023-01-04 23:45:11 -06:00
|
|
|
{
|
2025-02-08 14:07:29 -06:00
|
|
|
logger.LogDebug("Ensuring directory {Directory} exists", directory);
|
|
|
|
|
if (!Directory.Exists(directory))
|
|
|
|
|
Directory.CreateDirectory(directory);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static async Task EnsureDatabase(WebApplication app)
|
|
|
|
|
{
|
|
|
|
|
// Migrate
|
|
|
|
|
using var scope = app.Services.CreateAsyncScope();
|
|
|
|
|
using var db = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
|
|
|
|
|
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
|
|
|
|
var settings = scope.ServiceProvider.GetRequiredService<LANCommanderSettings>();
|
|
|
|
|
logger.LogDebug("Migrating database if required");
|
|
|
|
|
|
|
|
|
|
if (!(await db.Database.GetPendingMigrationsAsync()).Any())
|
|
|
|
|
{
|
|
|
|
|
logger.LogDebug("No pending migrations are available. Skipping database migration.");
|
|
|
|
|
return;
|
|
|
|
|
}
|
WIP fix for MySQL connection concurrency issues
This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL:
- The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no.
- Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory.
- A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function.
- Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml`
- The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution.
- The application can now log to Seq when using debug build
- Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future.
- Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled.
- All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation.
- Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
|
|
|
|
2025-02-08 14:07:29 -06:00
|
|
|
var dataSource = new SqliteConnectionStringBuilder(settings.DatabaseConnectionString).DataSource;
|
2024-11-05 20:22:24 -06:00
|
|
|
|
2025-02-08 14:07:29 -06:00
|
|
|
var backupName = Path.Combine("Backups", $"LANCommander.db.{DateTime.Now:dd-MM-yyyy-HH.mm.ss.bak}");
|
2024-11-05 20:20:03 -06:00
|
|
|
|
2025-02-08 14:07:29 -06:00
|
|
|
if (File.Exists(dataSource))
|
|
|
|
|
{
|
|
|
|
|
logger.LogInformation("Migrations pending, database will be backed up to {BackupName}", backupName);
|
|
|
|
|
File.Copy(dataSource, backupName);
|
2023-08-11 15:03:30 -05:00
|
|
|
}
|
2025-02-08 14:07:29 -06:00
|
|
|
|
|
|
|
|
await db.Database.MigrateAsync();
|
2023-08-11 15:03:30 -05:00
|
|
|
}
|
|
|
|
|
|
2025-02-08 14:07:29 -06:00
|
|
|
static async Task InitializeServerProcesses(WebApplication app)
|
|
|
|
|
{
|
|
|
|
|
// Autostart any server processes
|
|
|
|
|
using var scope = app.Services.CreateScope();
|
|
|
|
|
var serverService = scope.ServiceProvider.GetRequiredService<ServerService>();
|
|
|
|
|
var serverProcessService = scope.ServiceProvider.GetRequiredService<ServerProcessService>();
|
|
|
|
|
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
|
|
|
|
logger.LogDebug("Autostarting Servers");
|
|
|
|
|
|
|
|
|
|
foreach (var server in await serverService.Get(s => s.Autostart && s.AutostartMethod == ServerAutostartMethod.OnApplicationStart).ToListAsync())
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
logger.LogDebug("Autostarting server {ServerName} with a delay of {AutostartDelay} seconds", server.Name, server.AutostartDelay);
|
|
|
|
|
|
|
|
|
|
if (server.AutostartDelay > 0)
|
|
|
|
|
await Task.Delay(server.AutostartDelay);
|
|
|
|
|
|
|
|
|
|
await serverProcessService.StartServerAsync(server.Id);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogError(ex, "An unexpected error occurred while trying to autostart the server {ServerName}", server.Name);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|