-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathStartup.cs
More file actions
234 lines (204 loc) · 8.75 KB
/
Startup.cs
File metadata and controls
234 lines (204 loc) · 8.75 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
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.Json;
using Google.Apis.Auth.OAuth2;
using JustEat.StatsD;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Sentry.Extensibility;
using SymbolCollector.Core;
using SymbolCollector.Server.Properties;
namespace SymbolCollector.Server;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SuffixGenerator>();
services.AddSingleton<BundleIdGenerator>();
// TODO: When replacing this to a real (external storage backed), fix lifetimes below (scoped)
services.AddSingleton<ISymbolService, InMemorySymbolService>();
services.AddSingleton<ObjectFileParser>();
services.AddSingleton<FatBinaryReader>();
services.AddSingleton<SentryClientMetrics>();
services.AddSingleton<ClientMetrics>(sp => sp.GetRequiredService<SentryClientMetrics>());
services.AddSingleton<IBatchFinalizer, SymsorterBatchFinalizer>();
services.AddSingleton<ISymbolGcsWriter, SymbolGcsWriter>();
services.AddSingleton<IStorageClientFactory, StorageClientFactory>();
services.AddSingleton<ISentryEventProcessor, SymbolServiceEventProcessor>();
services.AddOptions<SymbolServiceOptions>();
services.AddOptions<ObjectFileParserOptions>();
services.AddOptions<JsonCredentialParameters>()
.Configure<IConfiguration>((o, c) => c.Bind("GoogleCloud:JsonCredentialParameters", o));
services.AddOptions<ObjectFileParserOptions>()
.Configure<IConfiguration>((o, c) => c.Bind("ObjectFileParser", o));
services.AddOptions<SymbolServiceOptions>()
.Configure<IConfiguration>((o, c) =>
{
o.BaseAddress = c.GetValue<string>("Kestrel:EndPoints:Http:Url");
c.Bind("SymbolService", o);
})
.Configure(o => o.SymsorterPath = GetSymsorterPath())
.Validate(o => !string.IsNullOrWhiteSpace(o.SymsorterPath), "SymsorterPath is required.")
.Validate(o => !string.IsNullOrWhiteSpace(o.BaseWorkingPath), "BaseWorkingPath is required.")
.Validate(o => !Directory.Exists(o.SymsorterPath), $"SymsorterPath doesn't exist.");
services.AddOptions<GoogleCloudStorageOptions>()
.Configure<IConfiguration>((o, c) => c.Bind("GoogleCloud", o))
.Configure<IOptions<JsonCredentialParameters>>((g, o) =>
{
// Massive hack because the Google SDK config system doesn't play well with ASP.NET Core's
var jsonCredentials = o.Value;
if (jsonCredentials.PrivateKey == "smoke-test")
{
jsonCredentials.PrivateKey = SmokeTest.SamplePrivateKey;
}
if (string.IsNullOrWhiteSpace(jsonCredentials?.PrivateKey))
{
g.Credential = GoogleCredential.GetApplicationDefault();
}
else
{
var json = JsonConvert.SerializeObject(jsonCredentials, Formatting.Indented);
g.Credential = GoogleCredential.FromJson(json);
}
})
.Validate(o => !string.IsNullOrWhiteSpace(o.BucketName), "The GCS Bucket name is required.");
services.AddSingleton(c => c.GetRequiredService<IOptions<GoogleCloudStorageOptions>>().Value);
services.AddMvc()
.AddJsonOptions(options =>
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase);
services.AddOptions<StatsDOptions>()
.Configure<IConfiguration>((o, c) => c.Bind("StatsD", o))
.Validate(o => !string.IsNullOrWhiteSpace(o.Host), "StatD host is required.");
services.AddStatsD(
provider =>
{
var options = provider.GetRequiredService<IOptions<StatsDOptions>>().Value;
var logger = provider.GetRequiredService<ILogger<StatsDConfiguration>>();
logger.LogInformation("Configuring statsd with {host}:{port} and prefix: {prefix}",
options.Host, options.Port, options.Prefix);
return new StatsDConfiguration()
{
Host = options.Host,
Port = options.Port,
Prefix = options.Prefix,
OnError = ex =>
{
// How spammy is this going to be?
logger.LogError(ex, "StatsD error.");
return true; // Don't rethrow
}
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Make sure this resolves.
using (var s = app.ApplicationServices.CreateScope())
{
_ = s.ServiceProvider.GetRequiredService<ISymbolService>();
var options = s.ServiceProvider.GetRequiredService<IOptions<SymbolServiceOptions>>().Value;
var logger = s.ServiceProvider.GetRequiredService<ILogger<Core.Startup>>();
if (options.DeleteBaseWorkingPathOnStartup)
{
var paths = new[] { "symsorter_output", "done", "processing", "conflict" }
.Select(p => Path.Combine(options.BaseWorkingPath, p));
foreach (var path in paths)
{
logger.LogDebug("Attempting to clean up {path}", path);
try
{
Directory.Delete(path, true);
}
catch (DirectoryNotFoundException)
{
logger.LogDebug("Directory didn't exist {path}", path);
}
catch (Exception e)
{
logger.LogError(e, "Failed to clean up {path}", path);
}
}
}
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.Map("/smoke-test", context =>
{
// TODO: Proper smoke-test (used to make sure DI is correct. Can't expect working config for GCS.
context.Response.StatusCode = (int)HttpStatusCode.OK;
return Task.CompletedTask;
});
endpoints.Map("/health", context =>
{
// TODO: Proper health check: Ensure config to GCS is proper (hit by load balancer)
context.Response.StatusCode = (int)HttpStatusCode.OK;
return Task.CompletedTask;
});
});
}
private string GetSymsorterPath()
{
string fileName;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
fileName = "symsorter-linux";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
fileName = "symsorter-mac";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
fileName = "symsorter.exe";
}
else
{
throw new InvalidOperationException("No symsorter added for this platform.");
}
return "./" + fileName;
}
private class SymbolServiceEventProcessor : ISentryEventProcessor
{
private readonly IWebHostEnvironment _environment;
private readonly SymbolServiceOptions _options;
private readonly string _cores = Environment.ProcessorCount.ToString();
public SymbolServiceEventProcessor(
IWebHostEnvironment environment,
IOptions<SymbolServiceOptions> options)
{
_environment = environment;
_options = options.Value;
}
public SentryEvent? Process(SentryEvent @event)
{
@event.SetTag("server-endpoint", _options.BaseAddress ?? "?");
@event.Contexts["SymbolServiceOptions"] = _options;
@event.SetTag("cores", _cores);
// In dev, ignore statsd errors
if (_environment.IsDevelopment())
{
if (@event.Exception is SocketException ex
&& ex.ToString().Contains("StatsD"))
{
return null;
}
}
return @event;
}
}
public class StatsDOptions
{
public string Host { get; set; } = null!;
public int Port { get; set; }
public string Prefix { get; set; } = "";
}
}