-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
IMachineBuilderExtensions.cs
423 lines (377 loc) · 16 KB
/
IMachineBuilderExtensions.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
using Serval.Translation.V1;
namespace Microsoft.Extensions.DependencyInjection;
public static class IMachineBuilderExtensions
{
public static IMachineBuilder AddServiceOptions(
this IMachineBuilder builder,
Action<ServiceOptions> configureOptions
)
{
builder.Services.Configure(configureOptions);
return builder;
}
public static IMachineBuilder AddServiceOptions(this IMachineBuilder builder, IConfiguration config)
{
builder.Services.Configure<ServiceOptions>(config);
return builder;
}
public static IMachineBuilder AddSmtTransferEngineOptions(
this IMachineBuilder builder,
Action<SmtTransferEngineOptions> configureOptions
)
{
builder.Services.Configure(configureOptions);
return builder;
}
public static IMachineBuilder AddSmtTransferEngineOptions(this IMachineBuilder builder, IConfiguration config)
{
builder.Services.Configure<SmtTransferEngineOptions>(config);
return builder;
}
public static IMachineBuilder AddClearMLOptions(
this IMachineBuilder builder,
Action<ClearMLOptions> configureOptions
)
{
builder.Services.Configure(configureOptions);
return builder;
}
public static IMachineBuilder AddClearMLOptions(this IMachineBuilder builder, IConfiguration config)
{
builder.Services.Configure<ClearMLOptions>(config);
return builder;
}
public static IMachineBuilder AddSharedFileOptions(
this IMachineBuilder builder,
Action<SharedFileOptions> configureOptions
)
{
builder.Services.Configure(configureOptions);
return builder;
}
public static IMachineBuilder AddSharedFileOptions(this IMachineBuilder builder, IConfiguration config)
{
builder.Services.Configure<SharedFileOptions>(config);
return builder;
}
public static IMachineBuilder AddThotSmtModel(this IMachineBuilder builder)
{
if (builder.Configuration is null)
return builder.AddThotSmtModel(o => { });
else
return builder.AddThotSmtModel(builder.Configuration.GetSection(ThotSmtModelOptions.Key));
}
public static IMachineBuilder AddThotSmtModel(
this IMachineBuilder builder,
Action<ThotSmtModelOptions> configureOptions
)
{
builder.Services.Configure(configureOptions);
builder.Services.AddSingleton<ISmtModelFactory, ThotSmtModelFactory>();
return builder;
}
public static IMachineBuilder AddThotSmtModel(this IMachineBuilder builder, IConfiguration config)
{
builder.Services.Configure<ThotSmtModelOptions>(config);
builder.Services.AddSingleton<ISmtModelFactory, ThotSmtModelFactory>();
return builder;
}
public static IMachineBuilder AddTransferEngine(this IMachineBuilder builder)
{
builder.Services.AddSingleton<ITransferEngineFactory, TransferEngineFactory>();
return builder;
}
public static IMachineBuilder AddUnigramTruecaser(this IMachineBuilder builder)
{
builder.Services.AddSingleton<ITruecaserFactory, UnigramTruecaserFactory>();
return builder;
}
public static IMachineBuilder AddClearMLService(this IMachineBuilder builder, string? connectionString = null)
{
connectionString ??= builder.Configuration?.GetConnectionString("ClearML");
if (connectionString is null)
throw new InvalidOperationException("ClearML connection string is required");
builder
.Services.AddHttpClient("ClearML")
.ConfigureHttpClient(httpClient => httpClient.BaseAddress = new Uri(connectionString!))
// Add retry policy; fail after approx. 2 + 4 + 8 = 14 seconds
.AddTransientHttpErrorPolicy(b =>
b.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
);
builder.Services.AddSingleton<IClearMLService, ClearMLService>();
// workaround register satisfying the interface and as a hosted service.
builder.Services.AddSingleton<IClearMLAuthenticationService, ClearMLAuthenticationService>();
builder.Services.AddHostedService(p => p.GetRequiredService<IClearMLAuthenticationService>());
builder
.Services.AddHttpClient("ClearML-NoRetry")
.ConfigureHttpClient(httpClient => httpClient.BaseAddress = new Uri(connectionString!));
builder.Services.AddSingleton<ClearMLHealthCheck>();
builder.Services.AddHealthChecks().AddCheck<ClearMLHealthCheck>("ClearML Health Check");
return builder;
}
private static IMachineBuilder AddClearMLBuildJobRunner(this IMachineBuilder builder)
{
builder.Services.AddScoped<IBuildJobRunner, ClearMLBuildJobRunner>();
builder.Services.AddScoped<IClearMLBuildJobFactory, NmtClearMLBuildJobFactory>();
builder.Services.AddSingleton<ClearMLMonitorService>();
builder.Services.AddHostedService(p => p.GetRequiredService<ClearMLMonitorService>());
return builder;
}
private static IMachineBuilder AddHangfireBuildJobRunner(this IMachineBuilder builder)
{
builder.Services.AddScoped<IBuildJobRunner, HangfireBuildJobRunner>();
builder.Services.AddScoped<IHangfireBuildJobFactory, SmtTransferHangfireBuildJobFactory>();
builder.Services.AddScoped<IHangfireBuildJobFactory, NmtHangfireBuildJobFactory>();
return builder;
}
public static IMachineBuilder AddMongoHangfireJobClient(
this IMachineBuilder builder,
string? connectionString = null
)
{
connectionString ??= builder.Configuration?.GetConnectionString("Hangfire");
if (connectionString is null)
throw new InvalidOperationException("Hangfire connection string is required");
builder.Services.AddHangfire(c =>
c.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseMongoStorage(
connectionString,
new MongoStorageOptions
{
MigrationOptions = new MongoMigrationOptions
{
MigrationStrategy = new MigrateMongoMigrationStrategy(),
BackupStrategy = new CollectionMongoBackupStrategy()
},
CheckConnection = true,
CheckQueuedJobsStrategy = CheckQueuedJobsStrategy.TailNotificationsCollection,
}
)
.UseFilter(new AutomaticRetryAttribute { Attempts = 0 })
);
builder.Services.AddHealthChecks().AddCheck<HangfireHealthCheck>(name: "Hangfire");
return builder;
}
public static IMachineBuilder AddHangfireJobServer(
this IMachineBuilder builder,
IEnumerable<TranslationEngineType>? engineTypes = null
)
{
engineTypes ??=
builder.Configuration?.GetSection("TranslationEngines").Get<TranslationEngineType[]?>()
?? [TranslationEngineType.SmtTransfer, TranslationEngineType.Nmt];
var queues = new List<string>();
foreach (TranslationEngineType engineType in engineTypes.Distinct())
{
switch (engineType)
{
case TranslationEngineType.SmtTransfer:
builder.AddThotSmtModel().AddTransferEngine().AddUnigramTruecaser();
queues.Add("smt_transfer");
break;
case TranslationEngineType.Nmt:
queues.Add("nmt");
break;
}
}
builder.Services.AddHangfireServer(o =>
{
o.Queues = queues.ToArray();
});
return builder;
}
public static IMachineBuilder AddMemoryDataAccess(this IMachineBuilder builder)
{
builder.Services.AddMemoryDataAccess(o =>
{
o.AddRepository<TranslationEngine>();
o.AddRepository<RWLock>();
o.AddRepository<TrainSegmentPair>();
});
return builder;
}
public static IMachineBuilder AddMongoDataAccess(this IMachineBuilder builder, string? connectionString = null)
{
connectionString ??= builder.Configuration?.GetConnectionString("Mongo");
if (connectionString is null)
throw new InvalidOperationException("Mongo connection string is required");
builder.Services.AddMongoDataAccess(
connectionString!,
"SIL.Machine.AspNetCore.Models",
o =>
{
o.AddRepository<TranslationEngine>(
"translation_engines",
mapSetup: m => m.SetIgnoreExtraElements(true),
init: async c =>
{
await c.Indexes.CreateOrUpdateAsync(
new CreateIndexModel<TranslationEngine>(
Builders<TranslationEngine>
.IndexKeys.Ascending(e => e.EngineId)
.Ascending("currentBuild._id")
)
);
await c.Indexes.CreateOrUpdateAsync(
new CreateIndexModel<TranslationEngine>(
Builders<TranslationEngine>.IndexKeys.Ascending(e => e.CurrentBuild!.JobRunner)
)
);
}
);
o.AddRepository<RWLock>("locks");
o.AddRepository<TrainSegmentPair>(
"train_segment_pairs",
init: c =>
c.Indexes.CreateOrUpdateAsync(
new CreateIndexModel<TrainSegmentPair>(
Builders<TrainSegmentPair>.IndexKeys.Ascending(p => p.TranslationEngineRef)
)
)
);
}
);
builder.Services.AddHealthChecks().AddMongoDb(connectionString!, name: "Mongo");
return builder;
}
public static IMachineBuilder AddServalPlatformService(
this IMachineBuilder builder,
string? connectionString = null
)
{
connectionString ??= builder.Configuration?.GetConnectionString("Serval");
if (connectionString is null)
throw new InvalidOperationException("Serval connection string is required");
builder.Services.AddScoped<IPlatformService, ServalPlatformService>();
builder
.Services.AddGrpcClient<TranslationPlatformApi.TranslationPlatformApiClient>(o =>
{
o.Address = new Uri(connectionString);
})
.ConfigureChannel(o =>
{
o.MaxRetryAttempts = null;
o.ServiceConfig = new ServiceConfig
{
MethodConfigs =
{
new MethodConfig
{
Names = { MethodName.Default },
RetryPolicy = new Grpc.Net.Client.Configuration.RetryPolicy
{
MaxAttempts = 10,
InitialBackoff = TimeSpan.FromSeconds(1),
MaxBackoff = TimeSpan.FromSeconds(5),
BackoffMultiplier = 1.5,
RetryableStatusCodes = { StatusCode.Unavailable }
}
},
new MethodConfig
{
Names =
{
new MethodName
{
Service = "serval.translation.v1.TranslationPlatformApi",
Method = "UpdateBuildStatus"
}
}
},
}
};
});
return builder;
}
public static IMachineBuilder AddServalTranslationEngineService(
this IMachineBuilder builder,
string? connectionString = null,
IEnumerable<TranslationEngineType>? engineTypes = null
)
{
builder.Services.AddGrpc(options =>
{
options.Interceptors.Add<CancellationInterceptor>();
options.Interceptors.Add<UnimplementedInterceptor>();
});
builder.AddServalPlatformService(connectionString);
engineTypes ??=
builder.Configuration?.GetSection("TranslationEngines").Get<TranslationEngineType[]?>()
?? [TranslationEngineType.SmtTransfer, TranslationEngineType.Nmt];
foreach (TranslationEngineType engineType in engineTypes.Distinct())
{
switch (engineType)
{
case TranslationEngineType.SmtTransfer:
builder.Services.AddSingleton<SmtTransferEngineStateService>();
builder.Services.AddHostedService<SmtTransferEngineCommitService>();
builder.AddThotSmtModel().AddTransferEngine().AddUnigramTruecaser();
builder.Services.AddScoped<ITranslationEngineService, SmtTransferEngineService>();
break;
case TranslationEngineType.Nmt:
builder.Services.AddScoped<ITranslationEngineService, NmtEngineService>();
break;
}
}
return builder;
}
public static IMachineBuilder AddBuildJobService(
this IMachineBuilder builder,
Action<BuildJobOptions> configureOptions
)
{
builder.Services.Configure(configureOptions);
var options = new BuildJobOptions();
configureOptions(options);
return builder.AddBuildJobService(options);
}
public static IMachineBuilder AddBuildJobService(this IMachineBuilder builder, IConfiguration config)
{
builder.Services.Configure<BuildJobOptions>(config);
var buildJobOptions = new BuildJobOptions();
config.GetSection(BuildJobOptions.Key).Bind(buildJobOptions);
return builder.AddBuildJobService(buildJobOptions);
}
public static IMachineBuilder AddBuildJobService(this IMachineBuilder builder)
{
if (builder.Configuration is null)
builder.AddBuildJobService(o => { });
else
{
builder.AddBuildJobService(builder.Configuration.GetSection(BuildJobOptions.Key));
var smtTransferEngineOptions = new SmtTransferEngineOptions();
builder.Configuration.GetSection(SmtTransferEngineOptions.Key).Bind(smtTransferEngineOptions);
string? driveLetter = Path.GetPathRoot(smtTransferEngineOptions.EnginesDir)?[..1];
if (driveLetter is null)
throw new InvalidOperationException("SMT Engine directory is required");
// add health check for disk storage capacity
builder
.Services.AddHealthChecks()
.AddDiskStorageHealthCheck(
x => x.AddDrive(driveLetter, 1_000), // 1GB
"SMT Engine Storage Capacity",
HealthStatus.Degraded
);
}
return builder;
}
private static IMachineBuilder AddBuildJobService(this IMachineBuilder builder, BuildJobOptions options)
{
builder.Services.AddScoped<IBuildJobService, BuildJobService>();
foreach (BuildJobRunner runnerType in options.Runners.Values.Distinct())
{
switch (runnerType)
{
case BuildJobRunner.ClearML:
builder.AddClearMLBuildJobRunner();
break;
case BuildJobRunner.Hangfire:
builder.AddHangfireBuildJobRunner();
break;
}
}
return builder;
}
}