-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
274 lines (227 loc) · 11.6 KB
/
Program.cs
File metadata and controls
274 lines (227 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Serilog;
using ThingConnect.Pulse.Server.Data;
using ThingConnect.Pulse.Server.Infrastructure;
using ThingConnect.Pulse.Server.Services;
using ThingConnect.Pulse.Server.Services.Monitoring;
using ThingConnect.Pulse.Server.Services.Prune;
using ThingConnect.Pulse.Server.Services.Rollup;
namespace ThingConnect.Pulse.Server;
public class Program
{
public static async Task Main(string[] args)
{
// Initialize path service for directory management
var pathService = new PathService();
// Create initial configuration to read Serilog settings
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true)
.Build();
// Configure Serilog from configuration files
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithProcessId()
.CreateLogger();
try
{
Log.Information("Starting ThingConnect Pulse Server");
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Use Serilog as the logging provider
builder.Host.UseSerilog();
// NOTE: Sentry initialization removed - will be initialized conditionally
// based on user consent in the ConsentAwareSentryService
// Configure Windows Service hosting
builder.Host.UseWindowsService();
// Add services to the container.
builder.Services.AddDbContext<PulseDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// Configure Identity and Authentication
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// Password settings
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 5;
// User settings
options.User.RequireUniqueEmail = true;
// Sign in settings
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false;
})
.AddEntityFrameworkStores<PulseDbContext>()
.AddDefaultTokenProviders()
.AddClaimsPrincipalFactory<ApplicationUserClaimsPrincipalFactory>();
// Configure cookie authentication to override Identity defaults
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/api/auth/logout";
options.AccessDeniedPath = "/access-denied";
options.ExpireTimeSpan = TimeSpan.FromHours(24);
options.SlidingExpiration = true;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = builder.Environment.IsDevelopment()
? CookieSecurePolicy.SameAsRequest
: CookieSecurePolicy.None;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.Name = "ThingConnect.Pulse.Auth";
options.Events.OnRedirectToLogin = context =>
{
// For API requests, return 401 instead of redirect
if (context.Request.Path.StartsWithSegments("/api"))
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
}
// For regular requests, redirect to frontend login page
context.Response.Redirect("/login");
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
// For API requests, return 403 instead of redirect
if (context.Request.Path.StartsWithSegments("/api"))
{
context.Response.StatusCode = 403;
return Task.CompletedTask;
}
// For regular requests, redirect to access denied page
context.Response.Redirect("/access-denied");
return Task.CompletedTask;
};
});
// Configure Authorization
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
policy.RequireRole(UserRoles.Administrator));
options.AddPolicy("AuthenticatedUser", policy =>
policy.RequireAuthenticatedUser());
});
// Add memory cache for settings service
builder.Services.AddMemoryCache();
// Add HTTP client for probes
builder.Services.AddHttpClient();
// Add path service
builder.Services.AddSingleton<IPathService, PathService>();
// Add consent-aware Sentry service
builder.Services.AddSingleton<IConsentAwareSentryService, ConsentAwareSentryService>();
// Add configuration services
builder.Services.AddSingleton<ConfigurationParser>(serviceProvider =>
{
ILogger<ConfigurationParser> logger = serviceProvider.GetRequiredService<ILogger<ConfigurationParser>>();
IDiscoveryService discoveryService = serviceProvider.GetRequiredService<IDiscoveryService>();
return ConfigurationParser.CreateAsync(logger, discoveryService).GetAwaiter().GetResult();
});
builder.Services.AddScoped<IConfigurationService, ConfigurationService>();
builder.Services.AddSingleton<ISettingsService, SettingsService>();
// Add monitoring services
builder.Services.AddScoped<IProbeService, ProbeService>();
builder.Services.AddSingleton<IOutageDetectionService, OutageDetectionService>();
builder.Services.AddSingleton<IDiscoveryService, DiscoveryService>();
builder.Services.AddScoped<IStatusService, StatusService>();
builder.Services.AddScoped<IHistoryService, HistoryService>();
builder.Services.AddScoped<IEndpointService, EndpointService>();
builder.Services.AddHostedService<MonitoringBackgroundService>();
// Add rollup services
builder.Services.AddScoped<IRollupService, RollupService>();
builder.Services.AddHostedService<RollupBackgroundService>();
// Add prune services
builder.Services.AddScoped<IPruneService, PruneService>();
// Add log cleanup service
builder.Services.AddHostedService<LogCleanupBackgroundService>();
// Add notification service
builder.Services.AddSingleton<NotificationBackgroundService>();
builder.Services.AddSingleton<INotificationService>(provider => provider.GetRequiredService<NotificationBackgroundService>());
builder.Services.AddHostedService<NotificationBackgroundService>(provider => provider.GetRequiredService<NotificationBackgroundService>());
// Add CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
policy.WithOrigins("https://localhost:55610", "http://localhost:55610", "https://localhost:5173", "http://localhost:5173", "https://localhost:55605", "https://localhost:55606", "http://localhost:55606")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("Authorization");
});
});
builder.Services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new PlainTextInputFormatter());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
WebApplication app = builder.Build();
// Ensure all required directories exist
using (IServiceScope scope = app.Services.CreateScope())
{
IPathService pathSvc = scope.ServiceProvider.GetRequiredService<IPathService>();
await pathSvc.EnsureDirectoriesExistAsync();
Log.Information("Directory structure verified at {RootPath}", pathSvc.GetRootDirectory());
}
// Ensure database exists and is up to date
using (IServiceScope scope = app.Services.CreateScope())
{
PulseDbContext context = scope.ServiceProvider.GetRequiredService<PulseDbContext>();
// Apply any pending migrations or create database if it doesn't exist
await context.Database.MigrateAsync();
Log.Information("Database migration completed");
// Initialize database with seed data in development only
if (app.Environment.IsDevelopment())
{
SeedData.Initialize(context);
}
}
// Initialize sample configuration if no configuration exists
using (IServiceScope scope = app.Services.CreateScope())
{
IConfigurationService configService = scope.ServiceProvider.GetRequiredService<IConfigurationService>();
await configService.InitializeSampleConfigurationAsync();
Log.Information("Sample configuration initialization completed");
}
// Initialize Sentry based on user consent
using (IServiceScope scope = app.Services.CreateScope())
{
IConsentAwareSentryService sentryService = scope.ServiceProvider.GetRequiredService<IConsentAwareSentryService>();
await sentryService.InitializeIfConsentedAsync();
Log.Information("Consent-aware Sentry initialization completed");
}
app.UseDefaultFiles();
app.UseStaticFiles();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors("AllowFrontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("/index.html");
Log.Information("ThingConnect Pulse Server configured successfully");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "ThingConnect Pulse Server terminated unexpectedly");
}
finally
{
Log.Information("ThingConnect Pulse Server stopped");
Log.CloseAndFlush();
}
}
}