-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathStartup.cs
233 lines (199 loc) · 9.32 KB
/
Startup.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
using Gov.Lclb.Cllb.Interfaces;
using Hangfire;
using Hangfire.Console;
using Hangfire.MemoryStorage;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Exceptions;
using System.Net.Http;
using System.Net;
using Grpc.Net.Client;
using static Gov.Lclb.Cllb.Services.FileManager.FileManager;
using Gov.Lclb.Cllb.Services.FileManager;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using HealthChecks.UI.Client;
namespace Gov.Lclb.Cllb.FederalReportingService
{
public class Startup
{
private readonly ILoggerFactory _loggerFactory;
public IConfiguration Configuration { get; }
public IWebHostEnvironment _env { get; set; }
public FileManagerClient _fileManagerClient { get; set; }
public Startup(IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
_env = env;
_loggerFactory = loggerFactory;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
if (!System.Diagnostics.Debugger.IsAttached)
builder.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.Extensions.Logging.ILogger>(_loggerFactory.CreateLogger("FederalReportingService"));
services.AddHangfire(config =>
{
// Change this line if you wish to have Hangfire use persistent storage.
config.UseMemoryStorage();
// enable console logs for jobs
config.UseConsole();
});
// health checks.
services.AddHealthChecks()
.AddCheck("Federal Reporting Service", () => HealthCheckResult.Healthy());
// add the file manager.
string fileManagerURI = Configuration["FILE_MANAGER_URI"];
if (!_env.IsProduction()) // needed for macOS TLS being turned off
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
}
if (!string.IsNullOrEmpty (fileManagerURI))
{
var httpClientHandler = new HttpClientHandler();
if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
// This allows you to use OpenShift self-signed certificates for testing.
{
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
}
var httpClient = new HttpClient(httpClientHandler);
// set default request version to HTTP 2. Note that Dotnet Core does not currently respect this setting for all requests.
httpClient.DefaultRequestVersion = HttpVersion.Version20;
var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions { HttpClient = httpClient });
var initialClient = new FileManagerClient(initialChannel);
// call the token service to get a token.
var tokenRequest = new TokenRequest()
{
Secret = Configuration["FILE_MANAGER_SECRET"]
};
var tokenReply = initialClient.GetToken(tokenRequest);
if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
{
// Add the bearer token to the client.
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");
var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions() { HttpClient = httpClient });
_fileManagerClient = new FileManagerClient(channel);
services.AddTransient<FileManagerClient>(_ => _fileManagerClient);
}
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
bool startHangfire = true;
#if DEBUG
// do not start Hangfire if we are running tests.
foreach (var assem in Assembly.GetEntryAssembly().GetReferencedAssemblies())
{
if (assem.FullName.ToLowerInvariant().StartsWith("xunit"))
{
startHangfire = false;
break;
}
}
#endif
if (startHangfire)
{
// enable Hangfire, using the default authentication model (local connections only)
app.UseHangfireServer();
DashboardOptions dashboardOptions = new DashboardOptions
{
AppPath = null
};
app.UseHangfireDashboard("/hangfire", dashboardOptions);
}
if (!string.IsNullOrEmpty(Configuration["ENABLE_HANGFIRE_JOBS"]))
{
SetupHangfireJobs(app, loggerFactory);
}
app.UseHealthChecks("/hc", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
if (!string.IsNullOrEmpty(Configuration["SPLUNK_COLLECTOR_URL"]) &&
!string.IsNullOrEmpty(Configuration["SPLUNK_TOKEN"])
)
{
// enable Splunk logger using Serilog
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.Console()
.WriteTo.EventCollector( splunkHost: Configuration["SPLUNK_COLLECTOR_URL"],
sourceType: "manual", eventCollectorToken: Configuration["SPLUNK_TOKEN"],
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
#pragma warning disable CA2000 // Dispose objects before losing scope
messageHandler: new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; }
}
#pragma warning restore CA2000 // Dispose objects before losing scope
)
.CreateLogger();
Serilog.Debugging.SelfLog.Enable(Console.Error);
}
else
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.Console()
.CreateLogger();
}
}
/// <summary>
/// Setup the Hangfire jobs.
/// </summary>
/// <param name="app"></param>
/// <param name="loggerFactory"></param>
private void SetupHangfireJobs(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
Microsoft.Extensions.Logging.ILogger log = loggerFactory.CreateLogger(typeof(Startup));
log.LogInformation("Starting setup of Hangfire job ...");
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
log.LogInformation($"Creating Hangfire jobs for {typeof(Startup)} ...");
// Run every 10 minutes
RecurringJob.AddOrUpdate(() => new FederalReportingController(Configuration, loggerFactory, _fileManagerClient).ExportFederalReports(null), "*/10 * * * *");
log.LogInformation("Hangfire jobs setup.");
}
}
catch (Exception e)
{
StringBuilder msg = new StringBuilder();
msg.AppendLine("Failed to setup Hangfire job.");
log.LogCritical(new EventId(-1, "Hangfire job setup failed"), e, msg.ToString());
}
}
}
}