Select Git revision
Saml2Namespaces.cs
-
Anders Abel authoredAnders Abel authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
Program.cs 11.68 KiB
using CommandLine;
using Coscine.ApiClient.Core.Api;
using Coscine.ApiClient.Core.Client;
using Coscine.KpiGenerator.Logging;
using Coscine.KpiGenerator.Models.ConfigurationModels;
using Coscine.KpiGenerator.Reportings.ApplicationProfile;
using Coscine.KpiGenerator.Reportings.Complete;
using Coscine.KpiGenerator.Reportings.Project;
using Coscine.KpiGenerator.Reportings.Resource;
using Coscine.KpiGenerator.Reportings.System;
using Coscine.KpiGenerator.Reportings.User;
using Coscine.KpiGenerator.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using Winton.Extensions.Configuration.Consul;
using static KPIGenerator.Utils.CommandLineOptions;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Coscine.KpiGenerator;
public class Program
{
private static IServiceProvider _serviceProvider = null!;
private static string? _environmentName;
public static async Task<int> Main(string[] args)
{
_environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
Console.WriteLine($"Running in environment: {_environmentName ?? "environment is null"}");
InitializeServices();
var logger = _serviceProvider.GetRequiredService<ILogger<Program>>();
try
{
var parserResult = Parser.Default.ParseArguments<
CompleteReportingOptions,
ProjectReportingOptions,
ResourceReportingOptions,
UserReportingOptions,
ApplicationProfileReportingOptions,
SystemReportingOptions
>(args);
var result = await parserResult.MapResult(
(CompleteReportingOptions opts) => _serviceProvider.GetRequiredService<CompleteReporting>().RunAsync(opts),
(ProjectReportingOptions opts) => _serviceProvider.GetRequiredService<ProjectReporting>().RunAsync(opts),
(ResourceReportingOptions opts) => _serviceProvider.GetRequiredService<ResourceReporting>().RunAsync(opts),
(UserReportingOptions opts) => _serviceProvider.GetRequiredService<UserReporting>().RunAsync(opts),
(ApplicationProfileReportingOptions opts) => _serviceProvider.GetRequiredService<ApplicationProfileReporting>().RunAsync(opts),
(SystemReportingOptions opts) => _serviceProvider.GetRequiredService<SystemReporting>().RunAsync(opts),
HandleParseError
);
if (result)
{
logger.LogInformation("Finished.");
return 0; // Exit Code 0 for Success
}
else
{
logger.LogInformation("Program execution was interrupted.");
return -1; // Exit Code -1 for Failure
}
}
catch (Exception ex)
{
logger.LogError(ex, "Exception: {message}", ex.Message);
return -1; // Exit Code -1 for Failure
}
finally
{
DisposeServices();
}
}
private static void InitializeServices()
{
// Register custom layout renderers for NLog
LogManager.Setup().SetupExtensions(s =>
{
s.RegisterLayoutRenderer<AssemblyNameLayoutRenderer>("assembly-name");
s.RegisterLayoutRenderer<AssemblyVersionLayoutRenderer>("assembly-version");
});
// Create a new instance of ConfigurationBuilder
var configBuilder = new ConfigurationBuilder();
// Define the Consul URL
var consulUrl = Environment.GetEnvironmentVariable("CONSUL_URL") ?? "http://localhost:8500";
// Remove the default sources
configBuilder.Sources.Clear();
// Add Consul as a configuration source
var configuration = configBuilder
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
.AddConsul(
"coscine/Coscine.Infrastructure/KpiGenerator/appsettings",
options =>
{
options.ConsulConfigurationOptions =
cco => cco.Address = new Uri(consulUrl);
options.Optional = true;
options.ReloadOnChange = true;
options.PollWaitTime = TimeSpan.FromSeconds(5);
options.OnLoadException = exceptionContext => exceptionContext.Ignore = true;
}
)
.AddConsul(
$"coscine/Coscine.Infrastructure/KpiGenerator/appsettings.{_environmentName}.json",
options =>
{
options.ConsulConfigurationOptions =
cco => cco.Address = new Uri(consulUrl);
options.Optional = true;
options.ReloadOnChange = true;
options.PollWaitTime = TimeSpan.FromSeconds(5);
options.OnLoadException = exceptionContext => exceptionContext.Ignore = true;
}
)
.AddEnvironmentVariables()
.Build();
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(configuration);
// Add the configuration to the service collection
services.Configure<KpiConfiguration>(settings =>
{
configuration.GetSection(KpiConfiguration.Section).Bind(settings);
});
services.Configure<ReportingConfiguration>(settings =>
{
configuration.GetSection(ReportingConfiguration.Section).Bind(settings);
});
// Add logging
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddNLog();
});
var reportingConfiguration = new ReportingConfiguration();
configuration.Bind(ReportingConfiguration.Section, reportingConfiguration);
// Set the default LogLevel
LogManager.Configuration.Variables["logLevel"] = reportingConfiguration.Logger?.LogLevel ?? "Trace";
// Set the log location
LogManager.Configuration.Variables["logHome"] = reportingConfiguration.Logger?.LogHome ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
// Add AutoMapper
services.AddAutoMapper(typeof(Program));
// Register the in-memory cache service
services.AddMemoryCache();
// Register the storage services
services.AddKeyedSingleton<IStorageService, GitLabStorageService>("gitlab");
services.AddKeyedSingleton<IStorageService, FileSystemStorageService>("local");
// Register the HTTP client
services.AddHttpClient();
// Add the API clients
var apiConfiguration = new Configuration()
{
BasePath = $"{reportingConfiguration.Endpoint.TrimEnd('/')}/coscine",
ApiKeyPrefix = { { "Authorization", "Bearer" } },
ApiKey = { { "Authorization", reportingConfiguration.ApiKey } },
Timeout = TimeSpan.FromSeconds(300), // 5 minutes
};
services.AddSingleton<IAdminApi>(new AdminApi(apiConfiguration));
services.AddSingleton<IApplicationProfileApi>(new ApplicationProfileApi(apiConfiguration));
services.AddSingleton<IProjectApi>(new ProjectApi(apiConfiguration));
services.AddSingleton<IProjectQuotaApi>(new ProjectQuotaApi(apiConfiguration));
services.AddSingleton<IProjectResourceQuotaApi>(new ProjectResourceQuotaApi(apiConfiguration));
services.AddSingleton<IRoleApi>(new RoleApi(apiConfiguration));
services.AddSingleton<IUserApi>(new UserApi(apiConfiguration));
// Add services for reporting
services.AddTransient<CompleteReporting>();
services.AddTransient<ProjectReporting>();
services.AddTransient<ResourceReporting>();
services.AddTransient<UserReporting>();
services.AddTransient<SystemReporting>();
services.AddTransient<ApplicationProfileReporting>();
_serviceProvider = services.BuildServiceProvider();
}
private static void DisposeServices()
{
if (_serviceProvider == null)
{
return;
}
if (_serviceProvider is IDisposable disposable)
{
disposable.Dispose();
}
}
private static Task<bool> HandleParseError(IEnumerable<Error> errs)
{
var logger = _serviceProvider.GetService<ILogger<Program>>();
foreach (var err in errs)
{
if (err is HelpRequestedError || err is VersionRequestedError)
{
// Handle the display of help or version information
// Usually, the library will automatically display the help/version info,
// but you can customize it if needed.
}
else
{
// For other types of errors, you can log them or write them to the console
logger?.LogError("Error encountered parsing command-line options: {Error}", err.ToString());
Console.Error.WriteLine($"Error: {err}");
}
}
// Since there were errors, we typically return false to indicate that the program should not proceed
return Task.FromResult(false);
}
public static TResult SanitizeOptions<TResult>(TResult unsanitizedOptions)
{
// Sanitize all input that accepts an array or is a list of inputs.
if (unsanitizedOptions is not null)
{
var type = unsanitizedOptions.GetType();
if (type == typeof(CompleteReportingOptions))
{
var options = unsanitizedOptions as CompleteReportingOptions;
if (options is not null)
{
// Sanitize options here
return (TResult)(object)options;
}
}
else if (type == typeof(ProjectReportingOptions))
{
var options = unsanitizedOptions as ProjectReportingOptions;
if (options is not null)
{
// Sanitize options here
return (TResult)(object)options;
}
}
else if (type == typeof(ResourceReportingOptions))
{
var options = unsanitizedOptions as ResourceReportingOptions;
if (options is not null)
{
// Sanitize options here
return (TResult)(object)options;
}
}
else if (type == typeof(UserReportingOptions))
{
var options = unsanitizedOptions as UserReportingOptions;
if (options is not null)
{
// Sanitize options here
return (TResult)(object)options;
}
}
else if (type == typeof(ApplicationProfileReportingOptions))
{
var options = unsanitizedOptions as ApplicationProfileReportingOptions;
if (options is not null)
{
// Sanitize options here
return (TResult)(object)options;
}
}
else if (type == typeof(SystemReportingOptions))
{
var options = unsanitizedOptions as SystemReportingOptions;
if (options is not null)
{
// Sanitize options here
return (TResult)(object)options;
}
}
}
return unsanitizedOptions;
}
}