forked from dotnet/aspire
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceHealthCheckServiceTests.cs
More file actions
428 lines (332 loc) · 15.7 KB
/
ResourceHealthCheckServiceTests.cs
File metadata and controls
428 lines (332 loc) · 15.7 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using Aspire.Hosting.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Xunit;
using Xunit.Abstractions;
namespace Aspire.Hosting.Tests.Health;
public class ResourceHealthCheckServiceTests(ITestOutputHelper testOutputHelper)
{
[Fact()]
public async Task ResourcesWithoutHealthCheck_HealthyWhenRunning()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var resource = builder.AddResource(new ParentResource("resource"));
await using var app = await builder.BuildAsync();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
await app.StartAsync();
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Starting, null)
});
var startingEvent = await rns.WaitForResourceAsync("resource", e => e.Snapshot.State?.Text == KnownResourceStates.Starting);
Assert.Null(startingEvent.Snapshot.HealthStatus);
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
var healthyEvent = await rns.WaitForResourceHealthyAsync("resource");
Assert.Equal(HealthStatus.Healthy, healthyEvent.Snapshot.HealthStatus);
await app.StopAsync();
}
[Fact()]
[ActiveIssue("https://github.com/dotnet/aspire/issues/6385")]
public async Task ResourcesWithHealthCheck_NotHealthyUntilCheckSucceeds()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
builder.Services.AddHealthChecks().AddCheck("healthcheck_a", () => HealthCheckResult.Healthy());
var resource = builder.AddResource(new ParentResource("resource"))
.WithHealthCheck("healthcheck_a");
await using var app = await builder.BuildAsync();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
await app.StartAsync();
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Starting, null)
});
var startingEvent = await rns.WaitForResourceAsync("resource", e => e.Snapshot.State?.Text == KnownResourceStates.Starting);
Assert.Null(startingEvent.Snapshot.HealthStatus);
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
var runningEvent = await rns.WaitForResourceAsync("resource", e => e.Snapshot.State?.Text == KnownResourceStates.Running);
Assert.Null(runningEvent.Snapshot.HealthStatus);
var hasHealthReportsEvent = await rns.WaitForResourceAsync("resource", e => e.Snapshot.HealthReports.Length > 0);
Assert.Equal(HealthStatus.Healthy, hasHealthReportsEvent.Snapshot.HealthStatus);
await app.StopAsync();
}
[Fact()]
[ActiveIssue("https://github.com/dotnet/aspire/issues/6363")]
public async Task HealthCheckIntervalSlowsAfterSteadyHealthyState()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
AutoResetEvent? are = null;
builder.Services.AddHealthChecks().AddCheck("resource_check", () =>
{
are?.Set();
return HealthCheckResult.Healthy();
});
var resource = builder.AddResource(new ParentResource("resource"))
.WithHealthCheck("resource_check");
using var app = builder.Build();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
var abortTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120));
await app.StartAsync(abortTokenSource.Token);
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = KnownResourceStates.Running
});
await rns.WaitForResourceHealthyAsync(resource.Resource.Name, abortTokenSource.Token);
are = new AutoResetEvent(false);
// Allow one event to through since it could be half way through.
are.WaitOne();
var stopwatch = Stopwatch.StartNew();
are.WaitOne();
stopwatch.Stop();
// Delay is 30 seconds but we allow for a (ridiculous) 10 second margin of error.
Assert.True(stopwatch.ElapsedMilliseconds > 20000);
await app.StopAsync(abortTokenSource.Token);
}
[Fact()]
public async Task HealthCheckIntervalDoesNotSlowBeforeSteadyHealthyState()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
AutoResetEvent? are = null;
builder.Services.AddHealthChecks().AddCheck("resource_check", () =>
{
are?.Set();
return HealthCheckResult.Unhealthy();
});
var resource = builder.AddResource(new ParentResource("resource"))
.WithHealthCheck("resource_check");
using var app = builder.Build();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
var abortTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120));
await app.StartAsync(abortTokenSource.Token);
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = KnownResourceStates.Running
});
await rns.WaitForResourceAsync(resource.Resource.Name, KnownResourceStates.Running, abortTokenSource.Token);
are = new AutoResetEvent(false);
// Allow one event to through since it could be half way through.
are.WaitOne();
var stopwatch = Stopwatch.StartNew();
are.WaitOne();
stopwatch.Stop();
// When not in a healthy state the delay should be ~3 seconds but
// we'll check for 10 seconds to make sure we haven't got down
// the 30 second slow path.
Assert.True(stopwatch.ElapsedMilliseconds < 10000);
await app.StopAsync(abortTokenSource.Token);
}
[Fact()]
public async Task ResourcesWithoutHealthCheckAnnotationsGetReadyEventFired()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var resource = builder.AddResource(new ParentResource("resource"));
var blockAssert = new TaskCompletionSource<ResourceReadyEvent>();
builder.Eventing.Subscribe<ResourceReadyEvent>(resource.Resource, (@event, ct) =>
{
blockAssert.SetResult(@event);
return Task.CompletedTask;
});
using var app = builder.Build();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
var pendingStart = app.StartAsync();
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
var @event = await blockAssert.Task;
Assert.Equal(resource.Resource, @event.Resource);
await pendingStart;
await app.StopAsync();
}
[Fact(Skip = "")]
public async Task PoorlyImplementedHealthChecksDontCauseMonitoringLoopToCrashout()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var hitCount = 0;
builder.Services.AddHealthChecks().AddCheck("resource_check", (check) =>
{
hitCount++;
throw new InvalidOperationException("Random failure instead of result!");
});
var resource = builder.AddResource(new ParentResource("resource"))
.WithHealthCheck("resource_check");
using var app = builder.Build();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
var abortTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120));
var pendingStart = app.StartAsync(abortTokenSource.Token);
await rns.PublishUpdateAsync(resource.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
while (!abortTokenSource.Token.IsCancellationRequested)
{
if (hitCount > 2)
{
break;
}
await Task.Delay(100);
}
await pendingStart;
await app.StopAsync();
}
[Fact(Skip = "Test")]
public async Task ResourceHealthCheckServiceDoesNotRunHealthChecksUnlessResourceIsRunning()
{
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper);
// The custom resource we are using for our test.
var hitCount = 0;
var checkStatus = HealthCheckResult.Unhealthy();
builder.Services.AddHealthChecks().AddCheck("parent_test", () =>
{
hitCount++;
return checkStatus;
});
var parent = builder.AddResource(new ParentResource("parent"))
.WithHealthCheck("parent_test");
// Handle ResourceReadyEvent and use it to control when we drop through to do our assert
// on the health test being executed.
var resourceReadyEventFired = new TaskCompletionSource<ResourceReadyEvent>();
builder.Eventing.Subscribe<ResourceReadyEvent>(parent.Resource, (@event, ct) =>
{
resourceReadyEventFired.SetResult(@event);
return Task.CompletedTask;
});
// Make sure that this test doesn't run longer than a minute (should finish in a second or two)
// but allow enough time to debug things without having to adjust timings.
var abortTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120));
using var app = builder.Build();
var pendingStart = app.StartAsync(abortTokenSource.Token);
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
// Verify that the health check does not get run before we move the resource into the
// the running state. There isn't a great way to do this using a completition source
// so I'm just going to spin for up to ten seconds to be sure that no local perf
// issues lead to a false pass here.
var giveUpAfter = DateTime.Now.AddSeconds(10);
while (!abortTokenSource.Token.IsCancellationRequested)
{
Assert.Equal(0, hitCount);
await Task.Delay(100);
if (DateTime.Now > giveUpAfter)
{
break;
}
}
Assert.False(abortTokenSource.IsCancellationRequested);
await rns.PublishUpdateAsync(parent.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
// Wait for the ResourceReadyEvent
checkStatus = HealthCheckResult.Healthy();
await Task.WhenAll([resourceReadyEventFired.Task]);
Assert.True(hitCount > 0);
await pendingStart;
await app.StopAsync();
}
[Fact(Skip = "")]
public async Task ResourceHealthCheckServiceOnlyRaisesResourceReadyOnce()
{
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper);
// The custom resource we are using for our test.
var healthCheckHits = 0;
builder.Services.AddHealthChecks().AddCheck("parent_test", () =>
{
healthCheckHits++;
return HealthCheckResult.Healthy();
});
var parent = builder.AddResource(new ParentResource("parent"))
.WithHealthCheck("parent_test");
// Handle ResourceReadyEvent and use it to control when we drop through to do our assert
// on the health test being executed.
var eventHits = 0;
var resourceReadyEventFired = new TaskCompletionSource<ResourceReadyEvent>();
builder.Eventing.Subscribe<ResourceReadyEvent>(parent.Resource, (@event, ct) =>
{
eventHits++;
return Task.CompletedTask;
});
// Make sure that this test doesn't run longer than a minute (should finish in a second or two)
// but allow enough time to debug things without having to adjust timings.
var abortTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120));
using var app = builder.Build();
var pendingStart = app.StartAsync(abortTokenSource.Token);
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
// Get the custom resource to a running state.
await rns.PublishUpdateAsync(parent.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
while (!abortTokenSource.Token.IsCancellationRequested)
{
// We wait for this hit count to reach 3
// because it means that we've had a chance
// to fire the ready event twice.
if (healthCheckHits > 2)
{
break;
}
await Task.Delay(100);
}
Assert.False(abortTokenSource.IsCancellationRequested);
Assert.Equal(1, eventHits);
await pendingStart;
await app.StopAsync();
}
[Fact]
public async Task VerifyThatChildResourceWillBecomeHealthyOnceParentBecomesHealthy()
{
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper);
builder.Services.AddHealthChecks().AddCheck("parent_test", () => HealthCheckResult.Healthy());
var parent = builder.AddResource(new ParentResource("parent"))
.WithHealthCheck("parent_test");
var parentReady = new TaskCompletionSource<ResourceReadyEvent>();
builder.Eventing.Subscribe<ResourceReadyEvent>(parent.Resource, (@event, ct) =>
{
parentReady.SetResult(@event);
return Task.CompletedTask;
});
var child = builder.AddResource(new ChildResource("child", parent.Resource));
var childReady = new TaskCompletionSource<ResourceReadyEvent>();
builder.Eventing.Subscribe<ResourceReadyEvent>(child.Resource, (@event, ct) =>
{
childReady.SetResult(@event);
return Task.CompletedTask;
});
using var app = builder.Build();
var pendingStart = app.StartAsync();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();
// Get the custom resource to a running state.
await rns.PublishUpdateAsync(parent.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
// ... only need to do this with custom resources, for containers this
// is handled by app executor. When we get operators we won't need to do
// this at all.
await rns.PublishUpdateAsync(child.Resource, s => s with
{
State = new ResourceStateSnapshot(KnownResourceStates.Running, null)
});
var parentReadyEvent = await parentReady.Task;
Assert.Equal(parentReadyEvent.Resource, parent.Resource);
var childReadyEvent = await childReady.Task;
Assert.Equal(childReadyEvent.Resource, child.Resource);
await pendingStart;
await app.StopAsync();
}
private sealed class ParentResource(string name) : Resource(name)
{
}
private sealed class ChildResource(string name, ParentResource parent) : Resource(name), IResourceWithParent<ParentResource>
{
public ParentResource Parent => parent;
}
}