-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathApplication.cs
565 lines (495 loc) · 24.1 KB
/
Application.cs
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Cyberboss.AspNetCore.AsyncInitializer;
using Elastic.CommonSchema.Serilog;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Display;
using Serilog.Sinks.Elasticsearch;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Common.Http;
using Tgstation.Server.Host.Components;
using Tgstation.Server.Host.Components.Chat;
using Tgstation.Server.Host.Components.Deployment.Remote;
using Tgstation.Server.Host.Components.Engine;
using Tgstation.Server.Host.Components.Events;
using Tgstation.Server.Host.Components.Interop;
using Tgstation.Server.Host.Components.Interop.Bridge;
using Tgstation.Server.Host.Components.Repository;
using Tgstation.Server.Host.Components.Session;
using Tgstation.Server.Host.Components.Watchdog;
using Tgstation.Server.Host.Configuration;
using Tgstation.Server.Host.Controllers;
using Tgstation.Server.Host.Database;
using Tgstation.Server.Host.Extensions;
using Tgstation.Server.Host.Extensions.Converters;
using Tgstation.Server.Host.IO;
using Tgstation.Server.Host.Jobs;
using Tgstation.Server.Host.Properties;
using Tgstation.Server.Host.Security;
using Tgstation.Server.Host.Security.OAuth;
using Tgstation.Server.Host.Setup;
using Tgstation.Server.Host.Swarm;
using Tgstation.Server.Host.System;
using Tgstation.Server.Host.Transfer;
using Tgstation.Server.Host.Utils;
namespace Tgstation.Server.Host.Core
{
/// <summary>
/// Sets up dependency injection.
/// </summary>
#pragma warning disable CA1506
public sealed class Application : SetupApplication
{
/// <summary>
/// The <see cref="IWebHostEnvironment"/> for the <see cref="Application"/>.
/// </summary>
readonly IWebHostEnvironment hostingEnvironment;
/// <summary>
/// The <see cref="ITokenFactory"/> for the <see cref="Application"/>.
/// </summary>
ITokenFactory tokenFactory;
/// <summary>
/// Create the default <see cref="IServerFactory"/>.
/// </summary>
/// <returns>A new <see cref="IServerFactory"/> with the default settings.</returns>
public static IServerFactory CreateDefaultServerFactory()
{
var assemblyInformationProvider = new AssemblyInformationProvider();
var ioManager = new DefaultIOManager();
return new ServerFactory(
assemblyInformationProvider,
ioManager);
}
/// <summary>
/// Adds the <see cref="IWatchdogFactory"/> implementation.
/// </summary>
/// <typeparam name="TSystemWatchdogFactory">The <see cref="WatchdogFactory"/> child <see langword="class"/> for the current system.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to configure.</param>
/// <param name="postSetupServices">The <see cref="IPostSetupServices"/> to use.</param>
static void AddWatchdog<TSystemWatchdogFactory>(IServiceCollection services, IPostSetupServices postSetupServices)
where TSystemWatchdogFactory : class, IWatchdogFactory
{
if (postSetupServices.GeneralConfiguration.UseBasicWatchdog)
services.AddSingleton<IWatchdogFactory, WatchdogFactory>();
else
services.AddSingleton<IWatchdogFactory, TSystemWatchdogFactory>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Application"/> class.
/// </summary>
/// <param name="configuration">The <see cref="IConfiguration"/> for the <see cref="SetupApplication"/>.</param>
/// <param name="hostingEnvironment">The <see cref="IWebHostEnvironment"/> for the <see cref="SetupApplication"/>.</param>
public Application(
IConfiguration configuration,
IWebHostEnvironment hostingEnvironment)
: base(configuration)
{
this.hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
}
/// <summary>
/// Configure the <see cref="Application"/>'s services.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to configure.</param>
/// <param name="assemblyInformationProvider">The <see cref="IAssemblyInformationProvider"/> needed for configuration.</param>
/// <param name="ioManager">The <see cref="IIOManager"/> needed for configuration.</param>
/// <param name="postSetupServices">The <see cref="IPostSetupServices"/> needed for configuration.</param>
public void ConfigureServices(
IServiceCollection services,
IAssemblyInformationProvider assemblyInformationProvider,
IIOManager ioManager,
IPostSetupServices postSetupServices)
{
ConfigureServices(services, assemblyInformationProvider, ioManager);
ArgumentNullException.ThrowIfNull(postSetupServices);
// configure configuration
services.UseStandardConfig<UpdatesConfiguration>(Configuration);
services.UseStandardConfig<ControlPanelConfiguration>(Configuration);
services.UseStandardConfig<SwarmConfiguration>(Configuration);
services.UseStandardConfig<SessionConfiguration>(Configuration);
// enable options which give us config reloading
services.AddOptions();
// Set the timeout for IHostedService.StopAsync
services.Configure<HostOptions>(
opts => opts.ShutdownTimeout = TimeSpan.FromMinutes(postSetupServices.GeneralConfiguration.RestartTimeoutMinutes));
static LogEventLevel? ConvertSeriLogLevel(LogLevel logLevel) =>
logLevel switch
{
LogLevel.Critical => LogEventLevel.Fatal,
LogLevel.Debug => LogEventLevel.Debug,
LogLevel.Error => LogEventLevel.Error,
LogLevel.Information => LogEventLevel.Information,
LogLevel.Trace => LogEventLevel.Verbose,
LogLevel.Warning => LogEventLevel.Warning,
LogLevel.None => null,
_ => throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid log level {0}", logLevel)),
};
var microsoftEventLevel = ConvertSeriLogLevel(postSetupServices.FileLoggingConfiguration.MicrosoftLogLevel);
var elasticsearchConfiguration = postSetupServices.ElasticsearchConfiguration;
services.SetupLogging(
config =>
{
if (microsoftEventLevel.HasValue)
{
config.MinimumLevel.Override("Microsoft", microsoftEventLevel.Value);
config.MinimumLevel.Override("System.Net.Http.HttpClient", microsoftEventLevel.Value);
}
},
sinkConfig =>
{
if (postSetupServices.FileLoggingConfiguration.Disable)
return;
var logPath = postSetupServices.FileLoggingConfiguration.GetFullLogDirectory(
ioManager,
assemblyInformationProvider,
postSetupServices.PlatformIdentifier);
var logEventLevel = ConvertSeriLogLevel(postSetupServices.FileLoggingConfiguration.LogLevel);
var formatter = new MessageTemplateTextFormatter(
"{Timestamp:o} "
+ SerilogContextHelper.Template
+ "): [{Level:u3}] {SourceContext:l}: {Message} ({EventId:x8}){NewLine}{Exception}",
null);
logPath = ioManager.ConcatPath(logPath, "tgs-.log");
var rollingFileConfig = sinkConfig.File(
formatter,
logPath,
logEventLevel ?? LogEventLevel.Verbose,
50 * 1024 * 1024, // 50MB max size
flushToDiskInterval: TimeSpan.FromSeconds(2),
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true);
},
elasticsearchConfiguration.Enable
? new ElasticsearchSinkOptions(elasticsearchConfiguration.Host ?? throw new InvalidOperationException($"Missing {ElasticsearchConfiguration.Section}:{nameof(elasticsearchConfiguration.Host)}!"))
{
// Yes I know this means they cannot use a self signed cert unless they also have authentication, but lets be real here
// No one is going to be doing one of those but not the other
ModifyConnectionSettings = connectionConfigration => (!String.IsNullOrWhiteSpace(elasticsearchConfiguration.Username) && !String.IsNullOrWhiteSpace(elasticsearchConfiguration.Password))
? connectionConfigration
.BasicAuthentication(
elasticsearchConfiguration.Username,
elasticsearchConfiguration.Password)
.ServerCertificateValidationCallback((o, certificate, chain, errors) => true)
: null,
CustomFormatter = new EcsTextFormatter(),
AutoRegisterTemplate = true,
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
IndexFormat = "tgs-logs",
}
: null,
postSetupServices.InternalConfiguration,
postSetupServices.FileLoggingConfiguration);
// configure bearer token validation
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwtBearerOptions =>
{
// this line isn't actually run until the first request is made
// at that point tokenFactory will be populated
jwtBearerOptions.TokenValidationParameters = tokenFactory.ValidationParameters;
jwtBearerOptions.MapInboundClaims = false;
jwtBearerOptions.Events = new JwtBearerEvents
{
// Application is our composition root so this monstrosity of a line is okay
// At least, that's what I tell myself to sleep at night
OnTokenValidated = ctx => ctx
.HttpContext
.RequestServices
.GetRequiredService<IClaimsInjector>()
.InjectClaimsIntoContext(
ctx,
ctx.HttpContext.RequestAborted),
};
});
// add mvc, configure the json serializer settings
services
.AddMvc(options =>
{
options.EnableEndpointRouting = false;
options.ReturnHttpNotAcceptable = true;
options.RespectBrowserAcceptHeader = true;
})
.AddNewtonsoftJson(options =>
{
options.AllowInputFormatterExceptionMessages = true;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.CheckAdditionalContent = true;
options.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.Converters = new List<JsonConverter>
{
new VersionConverter(),
};
});
if (postSetupServices.GeneralConfiguration.HostApiDocumentation)
{
string GetDocumentationFilePath(string assemblyLocation) => ioManager.ConcatPath(ioManager.GetDirectoryName(assemblyLocation), String.Concat(ioManager.GetFileNameWithoutExtension(assemblyLocation), ".xml"));
var assemblyDocumentationPath = GetDocumentationFilePath(GetType().Assembly.Location);
var apiDocumentationPath = GetDocumentationFilePath(typeof(ApiHeaders).Assembly.Location);
services.AddSwaggerGen(genOptions => SwaggerConfiguration.Configure(genOptions, assemblyDocumentationPath, apiDocumentationPath));
services.AddSwaggerGenNewtonsoftSupport();
}
// CORS conditionally enabled later
services.AddCors();
// Enable managed HTTP clients
services.AddHttpClient();
services.AddSingleton<IAbstractHttpClientFactory, AbstractHttpClientFactory>();
void AddTypedContext<TContext>()
where TContext : DatabaseContext
{
var configureAction = DatabaseContext.GetConfigureAction<TContext>();
services.AddDbContextPool<TContext>((serviceProvider, builder) =>
{
if (hostingEnvironment.IsDevelopment())
builder.EnableSensitiveDataLogging();
var databaseConfigOptions = serviceProvider.GetRequiredService<IOptions<DatabaseConfiguration>>();
var databaseConfig = databaseConfigOptions.Value ?? throw new InvalidOperationException("DatabaseConfiguration missing!");
configureAction(builder, databaseConfig);
});
services.AddScoped<IDatabaseContext>(x => x.GetRequiredService<TContext>());
}
// add the correct database context type
var dbType = postSetupServices.DatabaseConfiguration.DatabaseType;
switch (dbType)
{
case DatabaseType.MySql:
case DatabaseType.MariaDB:
AddTypedContext<MySqlDatabaseContext>();
break;
case DatabaseType.SqlServer:
AddTypedContext<SqlServerDatabaseContext>();
break;
case DatabaseType.Sqlite:
AddTypedContext<SqliteDatabaseContext>();
break;
case DatabaseType.PostgresSql:
AddTypedContext<PostgresSqlDatabaseContext>();
break;
default:
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid {0}: {1}!", nameof(DatabaseType), dbType));
}
// configure other database services
services.AddSingleton<IDatabaseContextFactory, DatabaseContextFactory>();
services.AddSingleton<IDatabaseSeeder, DatabaseSeeder>();
// configure security services
services.AddScoped<IAuthenticationContextFactory, AuthenticationContextFactory>();
services.AddScoped<IClaimsInjector, ClaimsInjector>();
services.AddSingleton<IOAuthProviders, OAuthProviders>();
services.AddSingleton<IIdentityCache, IdentityCache>();
services.AddSingleton<ICryptographySuite, CryptographySuite>();
services.AddSingleton<ITokenFactory, TokenFactory>();
services.AddSingleton<IPasswordHasher<Models.User>, PasswordHasher<Models.User>>();
// configure platform specific services
if (postSetupServices.PlatformIdentifier.IsWindows)
{
AddWatchdog<WindowsWatchdogFactory>(services, postSetupServices);
services.AddSingleton<ISystemIdentityFactory, WindowsSystemIdentityFactory>();
services.AddSingleton<ISymlinkFactory, WindowsSymlinkFactory>();
services.AddSingleton<ByondInstallerBase, WindowsByondInstaller>();
services.AddSingleton<OpenDreamInstaller, WindowsOpenDreamInstaller>();
services.AddSingleton<IPostWriteHandler, WindowsPostWriteHandler>();
services.AddSingleton<IProcessFeatures, WindowsProcessFeatures>();
services.AddSingleton<WindowsNetworkPromptReaper>();
services.AddSingleton<INetworkPromptReaper>(x => x.GetRequiredService<WindowsNetworkPromptReaper>());
services.AddSingleton<IHostedService>(x => x.GetRequiredService<WindowsNetworkPromptReaper>());
}
else
{
AddWatchdog<PosixWatchdogFactory>(services, postSetupServices);
services.AddSingleton<ISystemIdentityFactory, PosixSystemIdentityFactory>();
services.AddSingleton<ISymlinkFactory, PosixSymlinkFactory>();
services.AddSingleton<ByondInstallerBase, PosixByondInstaller>();
services.AddSingleton<OpenDreamInstaller>();
services.AddSingleton<IPostWriteHandler, PosixPostWriteHandler>();
services.AddSingleton<IProcessFeatures, PosixProcessFeatures>();
// PosixProcessFeatures also needs a IProcessExecutor for gcore
services.AddSingleton(x => new Lazy<IProcessExecutor>(() => x.GetRequiredService<IProcessExecutor>(), true));
services.AddSingleton<INetworkPromptReaper, PosixNetworkPromptReaper>();
services.AddHostedService<PosixSignalHandler>();
}
// only global repo manager should be for the OD repo
var openDreamRepositoryDirectory = ioManager.ConcatPath(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
assemblyInformationProvider.VersionPrefix,
"OpenDreamRepository");
services.AddSingleton(
services => services
.GetRequiredService<IRepositoryManagerFactory>()
.CreateRepositoryManager(
new ResolvingIOManager(
services.GetRequiredService<IIOManager>(),
openDreamRepositoryDirectory),
new NoopEventConsumer()));
services.AddSingleton<IReadOnlyDictionary<EngineType, IEngineInstaller>>(
serviceProvider => new Dictionary<EngineType, IEngineInstaller>
{
{ EngineType.Byond, serviceProvider.GetRequiredService<ByondInstallerBase>() },
{ EngineType.OpenDream, serviceProvider.GetRequiredService<OpenDreamInstaller>() },
});
services.AddSingleton<IEngineInstaller, DelegatingEngineInstaller>();
if (postSetupServices.InternalConfiguration.UsingSystemD)
services.AddHostedService<SystemDManager>();
// configure file transfer services
services.AddSingleton<FileTransferService>();
services.AddSingleton<IFileTransferStreamHandler>(x => x.GetRequiredService<FileTransferService>());
services.AddSingleton<IFileTransferTicketProvider>(x => x.GetRequiredService<FileTransferService>());
services.AddTransient<IActionResultExecutor<LimitedStreamResult>, LimitedStreamResultExecutor>();
// configure swarm service
services.AddSingleton<SwarmService>();
services.AddSingleton<ISwarmService>(x => x.GetRequiredService<SwarmService>());
services.AddSingleton<ISwarmOperations>(x => x.GetRequiredService<SwarmService>());
services.AddSingleton<ISwarmServiceController>(x => x.GetRequiredService<SwarmService>());
// configure component services
services.AddScoped<IPortAllocator, PortAllocator>();
services.AddSingleton<IInstanceFactory, InstanceFactory>();
services.AddSingleton<IGitRemoteFeaturesFactory, GitRemoteFeaturesFactory>();
services.AddSingleton<ILibGit2RepositoryFactory, LibGit2RepositoryFactory>();
services.AddSingleton<ILibGit2Commands, LibGit2Commands>();
services.AddSingleton<IRepositoryManagerFactory, RepostoryManagerFactory>();
services.AddSingleton<IRemoteDeploymentManagerFactory, RemoteDeploymentManagerFactory>();
services.AddChatProviderFactory();
services.AddSingleton<IChatManagerFactory, ChatManagerFactory>();
services.AddSingleton<IServerUpdater, ServerUpdater>();
services.AddSingleton<IServerUpdateInitiator, ServerUpdateInitiator>();
// configure misc services
services.AddSingleton<IProcessExecutor, ProcessExecutor>();
services.AddSingleton<ISynchronousIOManager, SynchronousIOManager>();
services.AddSingleton<IServerPortProvider, ServerPortProivder>();
services.AddSingleton<ITopicClientFactory, TopicClientFactory>();
services.AddHostedService<CommandPipeManager>();
services.AddFileDownloader();
services.AddGitHub();
// configure root services
services.AddSingleton<IJobService, JobService>();
services.AddSingleton<IJobManager>(x => x.GetRequiredService<IJobService>());
services.AddSingleton<InstanceManager>();
services.AddSingleton<IBridgeDispatcher>(x => x.GetRequiredService<InstanceManager>());
services.AddSingleton<IInstanceManager>(x => x.GetRequiredService<InstanceManager>());
}
/// <summary>
/// Configure the <see cref="Application"/>.
/// </summary>
/// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure.</param>
/// <param name="serverControl">The <see cref="IServerControl"/> for the <see cref="Application"/>.</param>
/// <param name="tokenFactory">The value of <see cref="tokenFactory"/>.</param>
/// <param name="serverPortProvider">The <see cref="IServerPortProvider"/>.</param>
/// <param name="assemblyInformationProvider">The <see cref="IAssemblyInformationProvider"/>.</param>
/// <param name="controlPanelConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the <see cref="ControlPanelConfiguration"/> to use.</param>
/// <param name="generalConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the <see cref="GeneralConfiguration"/> to use.</param>
/// <param name="swarmConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the <see cref="SwarmConfiguration"/> to use.</param>
/// <param name="logger">The <see cref="Microsoft.Extensions.Logging.ILogger"/> for the <see cref="Application"/>.</param>
public void Configure(
IApplicationBuilder applicationBuilder,
IServerControl serverControl,
ITokenFactory tokenFactory,
IServerPortProvider serverPortProvider,
IAssemblyInformationProvider assemblyInformationProvider,
IOptions<ControlPanelConfiguration> controlPanelConfigurationOptions,
IOptions<GeneralConfiguration> generalConfigurationOptions,
IOptions<SwarmConfiguration> swarmConfigurationOptions,
ILogger<Application> logger)
{
ArgumentNullException.ThrowIfNull(applicationBuilder);
ArgumentNullException.ThrowIfNull(serverControl);
this.tokenFactory = tokenFactory ?? throw new ArgumentNullException(nameof(tokenFactory));
ArgumentNullException.ThrowIfNull(serverPortProvider);
ArgumentNullException.ThrowIfNull(assemblyInformationProvider);
var controlPanelConfiguration = controlPanelConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(controlPanelConfigurationOptions));
var generalConfiguration = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions));
var swarmConfiguration = swarmConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(swarmConfigurationOptions));
ArgumentNullException.ThrowIfNull(logger);
logger.LogDebug("Content Root: {contentRoot}", hostingEnvironment.ContentRootPath);
logger.LogTrace("Web Root: {webRoot}", hostingEnvironment.WebRootPath);
// setup the HTTP request pipeline
// Add additional logging context to the request
applicationBuilder.UseAdditionalRequestLoggingContext(swarmConfiguration);
// Wrap exceptions in a 500 (ErrorMessage) response
applicationBuilder.UseServerErrorHandling();
// Add the X-Powered-By response header
applicationBuilder.UseServerBranding(assemblyInformationProvider);
// suppress OperationCancelledExceptions, they are just aborted HTTP requests
applicationBuilder.UseCancelledRequestSuppression();
// 503 requests made while the application is starting
applicationBuilder.UseAsyncInitialization<IInstanceManager>(
(instanceManager, cancellationToken) => instanceManager.Ready.WaitAsync(cancellationToken));
if (generalConfiguration.HostApiDocumentation)
{
applicationBuilder.UseSwagger();
applicationBuilder.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TGS API"));
logger.LogTrace("Swagger API generation enabled");
}
// Set up CORS based on configuration if necessary
Action<CorsPolicyBuilder> corsBuilder = null;
if (controlPanelConfiguration.AllowAnyOrigin)
{
logger.LogTrace("Access-Control-Allow-Origin: *");
corsBuilder = builder => builder.AllowAnyOrigin();
}
else if (controlPanelConfiguration.AllowedOrigins?.Count > 0)
{
logger.LogTrace("Access-Control-Allow-Origin: {allowedOrigins}", String.Join(',', controlPanelConfiguration.AllowedOrigins));
corsBuilder = builder => builder.WithOrigins(controlPanelConfiguration.AllowedOrigins.ToArray());
}
var originalBuilder = corsBuilder;
corsBuilder = builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.SetPreflightMaxAge(TimeSpan.FromDays(1));
originalBuilder?.Invoke(builder);
};
applicationBuilder.UseCors(corsBuilder);
// spa loading if necessary
if (controlPanelConfiguration.Enable)
{
logger.LogInformation("Web control panel enabled.");
applicationBuilder.UseFileServer(new FileServerOptions
{
RequestPath = ControlPanelController.ControlPanelRoute,
EnableDefaultFiles = true,
EnableDirectoryBrowsing = false,
});
}
else
#if NO_WEBPANEL
logger.LogTrace("Web control panel was not included in TGS build!");
#else
logger.LogTrace("Web control panel disabled!");
#endif
// Do not cache a single thing beyond this point, it's all API
applicationBuilder.UseDisabledClientCache();
// authenticate JWT tokens using our security pipeline if present, returns 401 if bad
applicationBuilder.UseAuthentication();
// suppress and log database exceptions
applicationBuilder.UseDbConflictHandling();
// majority of handling is done in the controllers
applicationBuilder.UseMvc();
// 404 anything that gets this far
// End of request pipeline setup
logger.LogTrace("Configuration version: {configVersion}", GeneralConfiguration.CurrentConfigVersion);
logger.LogTrace("DMAPI Interop version: {interopVersion}", DMApiConstants.InteropVersion);
if (controlPanelConfiguration.Enable)
logger.LogTrace("Web control panel version: {webCPVersion}", MasterVersionsAttribute.Instance.RawControlPanelVersion);
logger.LogDebug("Starting hosting on port {httpApiPort}...", serverPortProvider.HttpApiPort);
}
/// <inheritdoc />
protected override void ConfigureHostedService(IServiceCollection services)
=> services.AddSingleton<IHostedService>(x => x.GetRequiredService<InstanceManager>());
}
}