Compare commits

..

2 Commits

Author SHA1 Message Date
Tudor Stanciu 15241429fc NetworkResurrector.Agent refactoring 2023-01-29 02:45:12 +02:00
Tudor Stanciu 25f15c1de1 NetworkResurrector.Server refactoring 2023-01-29 02:34:50 +02:00
12 changed files with 177 additions and 118 deletions

View File

@ -0,0 +1,8 @@
namespace NetworkResurrector.Agent.Extensions
{
internal static class DataTypeExtensions
{
public static string Nullify(this string value)
=> string.IsNullOrWhiteSpace(value) ? null : value;
}
}

View File

@ -0,0 +1,41 @@
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Configuration;
using Serilog.Sinks.MSSqlServer;
using System;
namespace NetworkResurrector.Agent.Extensions
{
internal static class LoggingExtensions
{
internal static LoggerSinkConfiguration ConfiguredDestinations(this LoggerSinkConfiguration writeTo, IConfiguration configuration)
{
var sqlServerEnabled = configuration.GetValue<bool>("Logs:SqlServer:Enabled");
var sqlServerConnection = configuration.GetValue<string>("Logs:SqlServer:Connection");
var seqEnabled = configuration.GetValue<bool>("Logs:Seq:Enabled");
var seqUrl = configuration.GetValue<string>("Logs:Seq:Url");
var seqApiKey = configuration.GetValue<string>("Logs:Seq:ApiKey");
if (sqlServerEnabled && string.IsNullOrWhiteSpace(sqlServerConnection))
throw new Exception("If SqlServer logging is enabled, the SqlServer connection must be configured.");
if (seqEnabled && string.IsNullOrWhiteSpace(seqUrl))
throw new Exception("If Seq logging is enabled, the Seq URL must be configured.");
if (sqlServerEnabled)
{
var columnOptions = new ColumnOptions();
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.Store.Add(StandardColumn.LogEvent);
var mssqlSinkOptions = new MSSqlServerSinkOptions() { AutoCreateSqlTable = true, TableName = "__Logs_Agent" };
writeTo.MSSqlServer(sqlServerConnection, mssqlSinkOptions, columnOptions: columnOptions);
}
if (seqEnabled)
writeTo.Seq(seqUrl, apiKey: seqApiKey.Nullify());
return writeTo;
}
}
}

View File

@ -15,6 +15,7 @@
<PackageReference Include="Serilog.AspNetCore" Version="$(SerilogPackageVersion)" /> <PackageReference Include="Serilog.AspNetCore" Version="$(SerilogPackageVersion)" />
<PackageReference Include="Serilog.Extensions.Logging" Version="$(SerilogExtensionsPackageVersion)" /> <PackageReference Include="Serilog.Extensions.Logging" Version="$(SerilogExtensionsPackageVersion)" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="$(SerilogSinksMSSqlServerPackageVersion)" /> <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="$(SerilogSinksMSSqlServerPackageVersion)" />
<PackageReference Include="Serilog.Sinks.Seq" Version="$(SerilogSinksSeqPackageVersion)" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="$(AutoMapperExtensionsPackageVersion)" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="$(AutoMapperExtensionsPackageVersion)" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="$(MediatRPackageVersion)" /> <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="$(MediatRPackageVersion)" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="$(MicrosoftExtensionsHostingPackageVersion)" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="$(MicrosoftExtensionsHostingPackageVersion)" />

View File

@ -5,9 +5,6 @@ using Microsoft.Extensions.Hosting;
using NetworkResurrector.Agent.Extensions; using NetworkResurrector.Agent.Extensions;
using NetworkResurrector.Agent.Extensions.Serilog; using NetworkResurrector.Agent.Extensions.Serilog;
using Serilog; using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
using System; using System;
namespace NetworkResurrector.Agent namespace NetworkResurrector.Agent
@ -20,28 +17,12 @@ namespace NetworkResurrector.Agent
builder.Host.UseSerilog((_, lc) => builder.Host.UseSerilog((_, lc) =>
{ {
var connectionString = builder.Configuration.GetConnectionString("DatabaseConnection");
var loggingLevelParam = builder.Configuration.GetValue<string>("Logging:LogLevel:Default");
var loggingLevelOk = Enum.TryParse(loggingLevelParam, out LogEventLevel loggingLevel);
if (!loggingLevelOk)
throw new Exception($"Logging level '{loggingLevelParam}' is not valid.");
var loggingLevelSwitch = new LoggingLevelSwitch(loggingLevel);
var columnOptions = new ColumnOptions();
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.Store.Add(StandardColumn.LogEvent);
var mssqlSinkOptions = new MSSqlServerSinkOptions() { AutoCreateSqlTable = true, TableName = "__Logs_Agent" };
lc lc
.MinimumLevel.ControlledBy(loggingLevelSwitch) .ReadFrom.Configuration(builder.Configuration)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext() .Enrich.FromLogContext()
.Enrich.With(new AgentCodeEventEnricher(builder.Configuration)) .Enrich.With(new AgentCodeEventEnricher(builder.Configuration))
.WriteTo.Console() .WriteTo.Console()
.WriteTo.MSSqlServer(connectionString, mssqlSinkOptions, columnOptions: columnOptions); .WriteTo.ConfiguredDestinations(builder.Configuration);
}); });
builder.Services.ConfigureServices(builder.Configuration); builder.Services.ConfigureServices(builder.Configuration);

View File

@ -6,11 +6,23 @@
"Host": { "Host": {
"UseWindowsService": true "UseWindowsService": true
}, },
"Logging": { "Serilog": {
"LogLevel": { "MinimumLevel": {
"Default": "Debug", "Default": "Information",
"Microsoft": "Warning", "Override": {
"Microsoft.Hosting.Lifetime": "Information" "Microsoft": "Information"
}
}
},
"Logs": {
"SqlServer": {
"Enabled": false,
"Connection": "Server=#########;Database=#########;User Id=#########;Password=#########;MultipleActiveResultSets=true"
},
"Seq": {
"Enabled": false,
"Url": "",
"ApiKey": ""
} }
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
@ -18,7 +30,7 @@
"Code": "DEV_AGENT" "Code": "DEV_AGENT"
}, },
"IdentityServer": { "IdentityServer": {
"BaseAddress": "https://lab.code-rove.com/identity-server-api/" "BaseAddress": "http://<host>:<port>/api/"
}, },
"Restrictions": { "Restrictions": {
"EnforceActionOwner": true "EnforceActionOwner": true

View File

@ -31,7 +31,7 @@ namespace NetworkResurrector.Api
var exitCode = 0; var exitCode = 0;
try try
{ {
var urls = builder.Configuration.GetValue<string>("urls"); var urls = builder.Configuration.GetValue<string>("Urls");
Log.Information("Starting network resurrector API..."); Log.Information("Starting network resurrector API...");
Log.Information($"Network resurrector API listening on {urls}"); Log.Information($"Network resurrector API listening on {urls}");
Console.WriteLine("Application started. Press Ctrl+C to shut down."); Console.WriteLine("Application started. Press Ctrl+C to shut down.");

View File

@ -0,0 +1,8 @@
namespace NetworkResurrector.Server.Extensions
{
internal static class DataTypeExtensions
{
public static string Nullify(this string value)
=> string.IsNullOrWhiteSpace(value) ? null : value;
}
}

View File

@ -0,0 +1,41 @@
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Configuration;
using Serilog.Sinks.MSSqlServer;
using System;
namespace NetworkResurrector.Server.Extensions
{
internal static class LoggingExtensions
{
internal static LoggerSinkConfiguration ConfiguredDestinations(this LoggerSinkConfiguration writeTo, IConfiguration configuration)
{
var sqlServerEnabled = configuration.GetValue<bool>("Logs:SqlServer:Enabled");
var sqlServerConnection = configuration.GetValue<string>("Logs:SqlServer:Connection");
var seqEnabled = configuration.GetValue<bool>("Logs:Seq:Enabled");
var seqUrl = configuration.GetValue<string>("Logs:Seq:Url");
var seqApiKey = configuration.GetValue<string>("Logs:Seq:ApiKey");
if (sqlServerEnabled && string.IsNullOrWhiteSpace(sqlServerConnection))
throw new Exception("If SqlServer logging is enabled, the SqlServer connection must be configured.");
if (seqEnabled && string.IsNullOrWhiteSpace(seqUrl))
throw new Exception("If Seq logging is enabled, the Seq URL must be configured.");
if (sqlServerEnabled)
{
var columnOptions = new ColumnOptions();
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.Store.Add(StandardColumn.LogEvent);
var mssqlSinkOptions = new MSSqlServerSinkOptions() { AutoCreateSqlTable = true, TableName = "__Logs" };
writeTo.MSSqlServer(sqlServerConnection, mssqlSinkOptions, columnOptions: columnOptions);
}
if (seqEnabled)
writeTo.Seq(seqUrl, apiKey: seqApiKey.Nullify());
return writeTo;
}
}
}

View File

@ -9,29 +9,20 @@ using Netmash.Extensions.Swagger;
using Netmash.Extensions.Swagger.Constants; using Netmash.Extensions.Swagger.Constants;
using Netmash.Security.Authentication.Identity; using Netmash.Security.Authentication.Identity;
using NetworkResurrector.Server.Application; using NetworkResurrector.Server.Application;
using NetworkResurrector.Server.Extensions;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Reflection; using System.Reflection;
namespace NetworkResurrector.Server namespace NetworkResurrector.Server.Extensions
{ {
public class Startup public static class StartupExtensions
{ {
private readonly IConfiguration _configuration; public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllers() services.AddControllers()
.AddNewtonsoftJson(o => o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc); .AddNewtonsoftJson(o => o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);
// Add basic authentication // Add basic authentication
services.AddIdentityAuthentication(_configuration.GetSection("IdentityServer")["BaseAddress"]); services.AddIdentityAuthentication(configuration.GetSection("IdentityServer")["BaseAddress"]);
services.AddHttpContextAccessor(); services.AddHttpContextAccessor();
@ -51,11 +42,11 @@ namespace NetworkResurrector.Server
services.AddApplicationServices(); services.AddApplicationServices();
// WakeOnLan // WakeOnLan
services.AddWakeOnLan(_configuration); services.AddWakeOnLan(configuration);
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public static void Configure(this IApplicationBuilder app)
{ {
// global cors policy // global cors policy
app.UseCors(x => x app.UseCors(x => x
@ -63,11 +54,6 @@ namespace NetworkResurrector.Server
.AllowAnyMethod() .AllowAnyMethod()
.AllowAnyHeader()); .AllowAnyHeader());
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
@ -78,7 +64,7 @@ namespace NetworkResurrector.Server
app.ConfigureSwagger("NetworkResurrector Server API"); app.ConfigureSwagger("NetworkResurrector Server API");
} }
private Assembly[] GetMediatRAssemblies() private static Assembly[] GetMediatRAssemblies()
{ {
var assembly = typeof(Application.CommandHandlers.PingMachineHandler).Assembly; var assembly = typeof(Application.CommandHandlers.PingMachineHandler).Assembly;
return new Assembly[] { assembly }; return new Assembly[] { assembly };

View File

@ -15,6 +15,7 @@
<PackageReference Include="Serilog.AspNetCore" Version="$(SerilogPackageVersion)" /> <PackageReference Include="Serilog.AspNetCore" Version="$(SerilogPackageVersion)" />
<PackageReference Include="Serilog.Extensions.Logging" Version="$(SerilogExtensionsPackageVersion)" /> <PackageReference Include="Serilog.Extensions.Logging" Version="$(SerilogExtensionsPackageVersion)" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="$(SerilogSinksMSSqlServerPackageVersion)" /> <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="$(SerilogSinksMSSqlServerPackageVersion)" />
<PackageReference Include="Serilog.Sinks.Seq" Version="$(SerilogSinksSeqPackageVersion)" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="$(AutoMapperExtensionsPackageVersion)" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="$(AutoMapperExtensionsPackageVersion)" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="$(MediatRPackageVersion)" /> <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="$(MediatRPackageVersion)" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="$(MicrosoftExtensionsHostingPackageVersion)" /> <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="$(MicrosoftExtensionsHostingPackageVersion)" />

View File

@ -1,14 +1,10 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using NetworkResurrector.Server.Extensions;
using Serilog; using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.MSSqlServer;
using System; using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace NetworkResurrector.Server namespace NetworkResurrector.Server
{ {
@ -16,76 +12,46 @@ namespace NetworkResurrector.Server
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
var isConsole = Debugger.IsAttached || args.Contains("--console"); var builder = WebApplication.CreateBuilder(args);
if (!isConsole)
builder.Host.UseSerilog((_, lc) =>
{ {
var pathToExe = Process.GetCurrentProcess().MainModule.FileName; lc
var pathToContentRoot = Path.GetDirectoryName(pathToExe); .ReadFrom.Configuration(builder.Configuration)
Directory.SetCurrentDirectory(pathToContentRoot);
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var connectionString = configuration.GetConnectionString("DatabaseConnection");
var loggingLevelParam = configuration.GetValue<string>("Logging:LogLevel:Default");
var loggingLevelOk = Enum.TryParse(loggingLevelParam, out LogEventLevel loggingLevel);
if (!loggingLevelOk)
throw new Exception($"Logging level '{loggingLevelParam}' is not valid.");
var loggingLevelSwitch = new LoggingLevelSwitch(loggingLevel);
var columnOptions = new ColumnOptions();
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.Store.Add(StandardColumn.LogEvent);
var mssqlSinkOptions = new MSSqlServerSinkOptions() { AutoCreateSqlTable = true, TableName = "__Logs" };
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(loggingLevelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext() .Enrich.FromLogContext()
.WriteTo.Console() .WriteTo.Console()
.WriteTo.MSSqlServer(connectionString, mssqlSinkOptions, columnOptions: columnOptions) .WriteTo.ConfiguredDestinations(builder.Configuration);
.CreateLogger(); });
builder.Services.ConfigureServices(builder.Configuration);
var useWindowsService = builder.Configuration.GetValue<bool>("Host:UseWindowsService");
if (useWindowsService)
builder.Host.UseWindowsService();
var app = builder.Build();
app.Configure();
var exitCode = 0;
try try
{ {
var urls = configuration.GetValue<string>("urls"); var urls = builder.Configuration.GetValue<string>("Urls");
Log.Information("Starting network resurrector API..."); Log.Information("Starting network resurrector server...");
Log.Information($"API listening on {urls}"); Log.Information($"Server listening on {urls}");
Console.WriteLine("Application started. Press Ctrl+C to shut down."); Console.WriteLine("Application started. Press Ctrl+C to shut down.");
CreateHostBuilder(args, configuration, !isConsole).Build().Run(); app.Run();
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Fatal(ex, "Network resurrector API host terminated unexpectedly"); Log.Fatal(ex, "Network resurrector server host terminated unexpectedly");
} }
finally finally
{ {
Log.CloseAndFlush(); Log.CloseAndFlush();
} }
}
public static IHostBuilder CreateHostBuilder(string[] args, IConfiguration configuration, bool useWindowsService) Environment.Exit(exitCode);
{
var builder = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseConfiguration(configuration)
.UseSerilog();
});
if (useWindowsService)
builder.UseWindowsService();
return builder;
} }
} }
} }

View File

@ -1,19 +1,33 @@
{ {
"urls": "http://*:5062", "Urls": "http://*:5062",
"ConnectionStrings": { "ConnectionStrings": {
"DatabaseConnection": "Server=#########;Database=#########;User Id=#########;Password=#########;MultipleActiveResultSets=true" "DatabaseConnection": "Server=#########;Database=#########;User Id=#########;Password=#########;MultipleActiveResultSets=true"
}, },
"Logging": { "Host": {
"LogLevel": { "UseWindowsService": false
"Default": "Debug", },
"Microsoft": "Warning", "Serilog": {
"Microsoft.Hosting.Lifetime": "Information" "MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information"
}
}
},
"Logs": {
"SqlServer": {
"Enabled": false,
"Connection": "Server=#########;Database=#########;User Id=#########;Password=#########;MultipleActiveResultSets=true"
},
"Seq": {
"Enabled": false,
"Url": "",
"ApiKey": ""
} }
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"IdentityServer": { "IdentityServer": {
//"BaseAddress": "http://localhost:5063/" "BaseAddress": "http://<host>:<port>/api/"
"BaseAddress": "https://lab.code-rove.com/identity-server-api/"
}, },
"WakeOnLan": { "WakeOnLan": {
"Provider": { "Provider": {
@ -21,5 +35,5 @@
"Options": [ "Inhouse", "Nikeee" ] "Options": [ "Inhouse", "Nikeee" ]
} }
}, },
"Shutdown": { } "Shutdown": {}
} }