-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathDaprDistributedApplicationLifecycleHook.cs
More file actions
681 lines (568 loc) · 34.3 KB
/
DaprDistributedApplicationLifecycleHook.cs
File metadata and controls
681 lines (568 loc) · 34.3 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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Aspire.Hosting;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Eventing;
using Aspire.Hosting.Lifecycle;
using Aspire.Hosting.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net.Sockets;
using static CommunityToolkit.Aspire.Hosting.Dapr.CommandLineArgs;
namespace CommunityToolkit.Aspire.Hosting.Dapr;
internal sealed class DaprDistributedApplicationLifecycleHook(
IConfiguration configuration,
IHostEnvironment environment,
ILogger<DaprDistributedApplicationLifecycleHook> logger,
IOptions<DaprOptions> options) : IDistributedApplicationEventingSubscriber, IDisposable
{
private readonly DaprOptions _options = options.Value;
private string? _onDemandResourcesRootPath;
public Task SubscribeAsync(IDistributedApplicationEventing eventing, DistributedApplicationExecutionContext executionContext, CancellationToken cancellationToken)
{
eventing.Subscribe<BeforeStartEvent>(OnBeforeStartAsync);
return Task.CompletedTask;
}
private async Task OnBeforeStartAsync(BeforeStartEvent @event, CancellationToken cancellationToken = default)
{
var appModel = @event.Model;
string appHostDirectory = GetAppHostDirectory();
// Set up WaitAnnotations for Dapr components based on their value provider dependencies
SetupComponentLifecycle(appModel);
var onDemandResourcesPaths = await StartOnDemandDaprComponentsAsync(appModel, cancellationToken).ConfigureAwait(false);
var sideCars = new List<ExecutableResource>();
foreach (var resource in appModel.Resources)
{
if (!resource.TryGetLastAnnotation<DaprSidecarAnnotation>(out var daprAnnotation))
{
continue;
}
var fileName = _options.DaprPath
?? GetDefaultDaprPath()
?? throw new DistributedApplicationException("Unable to locate the Dapr CLI.");
var daprSidecar = daprAnnotation.Sidecar;
// Propagate WaitAnnotations from the original resource to the Dapr sidecar
if (resource.TryGetAnnotationsOfType<WaitAnnotation>(out var waitAnnotations))
{
foreach (var waitAnnotation in waitAnnotations)
{
daprSidecar.Annotations.Add(waitAnnotation);
}
}
var sidecarOptionsAnnotation = daprSidecar.Annotations.OfType<DaprSidecarOptionsAnnotation>().LastOrDefault();
var sidecarOptions = sidecarOptionsAnnotation?.Options;
[return: NotNullIfNotNull(nameof(path))]
string? NormalizePath(string? path)
{
if (path is null)
{
return null;
}
return Path.GetFullPath(Path.Combine(appHostDirectory, path));
}
var aggregateResourcesPaths = sidecarOptions?.ResourcesPaths.Select(path => NormalizePath(path)).ToHashSet() ?? [];
var componentReferenceAnnotations = daprSidecar.Annotations.OfType<DaprComponentReferenceAnnotation>();
var secretValueProviders = new Dictionary<string, IValueProvider>();
var endpointEnvironmentVars = new Dictionary<string, IValueProvider>();
var hasValueProviders = false;
foreach (var componentReferenceAnnotation in componentReferenceAnnotations)
{
// Check if there are any value provider references that need to be added as environment variables
if (componentReferenceAnnotation.Component.TryGetAnnotationsOfType<DaprComponentValueProviderAnnotation>(out var endpointAnnotations))
{
foreach (var endpointAnnotation in endpointAnnotations)
{
endpointEnvironmentVars[endpointAnnotation.EnvironmentVariableName] = endpointAnnotation.ValueProvider;
hasValueProviders = true;
}
}
// Collect secret value providers to be resolved later when environment is set up
if (componentReferenceAnnotation.Component.TryGetAnnotationsOfType<DaprComponentSecretAnnotation>(out var secretAnnotations))
{
foreach (var secretAnnotation in secretAnnotations)
{
secretValueProviders[secretAnnotation.Key] = secretAnnotation.Value;
}
}
// If we have any secrets or value providers, ensure the secret store path is added
if ((secretValueProviders.Count > 0 || hasValueProviders) && onDemandResourcesPaths.TryGetValue("secretstore", out var secretStorePath))
{
string onDemandResourcesPathDirectory = Path.GetDirectoryName(secretStorePath)!;
if (onDemandResourcesPathDirectory is not null)
{
aggregateResourcesPaths.Add(onDemandResourcesPathDirectory);
}
}
if (componentReferenceAnnotation.Component.Options?.LocalPath is not null)
{
var localPathDirectory = Path.GetDirectoryName(NormalizePath(componentReferenceAnnotation.Component.Options.LocalPath));
if (localPathDirectory is not null)
{
aggregateResourcesPaths.Add(localPathDirectory);
}
}
else if (onDemandResourcesPaths.TryGetValue(componentReferenceAnnotation.Component.Name, out var onDemandResourcesPath))
{
string onDemandResourcesPathDirectory = Path.GetDirectoryName(onDemandResourcesPath)!;
if (onDemandResourcesPathDirectory is not null)
{
aggregateResourcesPaths.Add(onDemandResourcesPathDirectory);
}
}
}
if (secretValueProviders.Count > 0 || endpointEnvironmentVars.Count > 0)
{
daprSidecar.Annotations.Add(new EnvironmentCallbackAnnotation(async context =>
{
// Resolve secrets when environment is being set up (when parameter values are available)
foreach (var (secretKey, secretValueProvider) in secretValueProviders)
{
var secretValue = await secretValueProvider.GetValueAsync(context.CancellationToken);
context.EnvironmentVariables.TryAdd(secretKey, secretValue ?? string.Empty);
}
// Add value provider references
foreach (var (envVarName, valueProvider) in endpointEnvironmentVars)
{
var value = await valueProvider.GetValueAsync(context.CancellationToken);
context.EnvironmentVariables.TryAdd(envVarName, value ?? string.Empty);
}
}));
}
var daprAppPortArg = (int? port) => ModelNamedArg("--app-port", port);
var daprGrpcPortArg = (object port) => ModelNamedObjectArg("--dapr-grpc-port", port);
var daprHttpPortArg = (object port) => ModelNamedObjectArg("--dapr-http-port", port);
var daprMetricsPortArg = (object port) => ModelNamedObjectArg("--metrics-port", port);
var daprProfilePortArg = (object port) => ModelNamedObjectArg("--profile-port", port);
var daprAppChannelAddressArg = (string? address) => ModelNamedArg("--app-channel-address", address);
var daprAppProtocol = (string? protocol) => ModelNamedArg("--app-protocol", protocol);
var appId = sidecarOptions?.AppId ?? resource.Name;
#pragma warning disable CS0618 // Type or member is obsolete
string? maxBodySize = GetValueIfSet(sidecarOptions?.DaprMaxBodySize, sidecarOptions?.DaprHttpMaxRequestSize, "Mi");
string? readBufferSize = GetValueIfSet(sidecarOptions?.DaprReadBufferSize, sidecarOptions?.DaprHttpReadBufferSize, "Ki");
#pragma warning restore CS0618 // Type or member is obsolete
var daprCommandLine =
CommandLineBuilder
.Create(
fileName,
Command("run"),
daprAppPortArg(sidecarOptions?.AppPort),
ModelNamedArg("--app-channel-address", sidecarOptions?.AppChannelAddress),
ModelNamedArg("--app-health-check-path", sidecarOptions?.AppHealthCheckPath),
ModelNamedArg("--app-health-probe-interval", sidecarOptions?.AppHealthProbeInterval),
ModelNamedArg("--app-health-probe-timeout", sidecarOptions?.AppHealthProbeTimeout),
ModelNamedArg("--app-health-threshold", sidecarOptions?.AppHealthThreshold),
ModelNamedArg("--app-id", appId),
ModelNamedArg("--app-max-concurrency", sidecarOptions?.AppMaxConcurrency),
ModelNamedArg("--app-protocol", sidecarOptions?.AppProtocol),
ModelNamedArg("--config", NormalizePath(sidecarOptions?.Config)),
ModelNamedArg("--max-body-size", sidecarOptions?.DaprMaxBodySize),
ModelNamedArg("--read-buffer-size", sidecarOptions?.DaprReadBufferSize),
ModelNamedArg("--dapr-internal-grpc-port", sidecarOptions?.DaprInternalGrpcPort),
ModelNamedArg("--dapr-listen-addresses", sidecarOptions?.DaprListenAddresses),
Flag("--enable-api-logging", sidecarOptions?.EnableApiLogging),
Flag("--enable-app-health-check", sidecarOptions?.EnableAppHealthCheck),
Flag("--enable-profiling", sidecarOptions?.EnableProfiling),
ModelNamedArg("--log-level", sidecarOptions?.LogLevel),
ModelNamedArg("--placement-host-address", sidecarOptions?.PlacementHostAddress),
ModelNamedArg("--resources-path", aggregateResourcesPaths),
ModelNamedArg("--run-file", NormalizePath(sidecarOptions?.RunFile)),
ModelNamedArg("--runtime-path", NormalizePath(sidecarOptions?.RuntimePath)),
ModelNamedArg("--scheduler-host-address", sidecarOptions?.SchedulerHostAddress),
ModelNamedArg("--unix-domain-socket", sidecarOptions?.UnixDomainSocket),
PostOptionsArgs(Args(sidecarOptions?.Command)));
var daprCliResourceName = sidecarOptions?.SidecarName ?? $"{daprSidecar.Name}-cli";
var daprCli = new ExecutableResource(daprCliResourceName, fileName, appHostDirectory);
// Propagate WaitAnnotations from the original resource to the Dapr CLI executable
if (resource.TryGetAnnotationsOfType<WaitAnnotation>(out var resourceWaitAnnotations))
{
foreach (var waitAnnotation in resourceWaitAnnotations)
{
daprCli.Annotations.Add(waitAnnotation);
}
}
// Make the Dapr CLI wait for the component resources it references
foreach (var componentRef in componentReferenceAnnotations)
{
daprCli.Annotations.Add(new WaitAnnotation(componentRef.Component, WaitType.WaitUntilHealthy));
}
resource.Annotations.Add(
new EnvironmentCallbackAnnotation(
context =>
{
if (context.ExecutionContext.IsPublishMode)
{
return;
}
var http = daprCli.GetEndpoint("http");
var grpc = daprCli.GetEndpoint("grpc");
context.EnvironmentVariables.TryAdd("DAPR_HTTP_PORT", http.Port.ToString(CultureInfo.InvariantCulture));
context.EnvironmentVariables.TryAdd("DAPR_GRPC_PORT", grpc.Port.ToString(CultureInfo.InvariantCulture));
context.EnvironmentVariables.TryAdd("DAPR_GRPC_ENDPOINT", grpc);
context.EnvironmentVariables.TryAdd("DAPR_HTTP_ENDPOINT", http);
}));
daprCli.Annotations.Add(new EndpointAnnotation(ProtocolType.Tcp, uriScheme: "http", name: "grpc", port: sidecarOptions?.DaprGrpcPort));
daprCli.Annotations.Add(new EndpointAnnotation(ProtocolType.Tcp, uriScheme: "http", name: "http", port: sidecarOptions?.DaprHttpPort));
daprCli.Annotations.Add(new EndpointAnnotation(ProtocolType.Tcp, uriScheme: "http", name: "metrics", port: sidecarOptions?.MetricsPort));
if (sidecarOptions?.EnableProfiling == true)
{
daprCli.Annotations.Add(new EndpointAnnotation(ProtocolType.Tcp, name: "profile", port: sidecarOptions?.ProfilePort, uriScheme: "http"));
}
// NOTE: Telemetry is enabled by default.
if (_options.EnableTelemetry != false)
{
OtlpConfigurationExtensions.AddOtlpEnvironment(daprCli, configuration, environment);
}
daprCli.Annotations.Add(
new CommandLineArgsCallbackAnnotation(
updatedArgs =>
{
updatedArgs.AddRange(daprCommandLine.Arguments);
var endPoint = GetEndpointReference(sidecarOptions, resource);
if (sidecarOptions?.AppPort is null && endPoint is { appEndpoint.IsAllocated: true })
{
updatedArgs.AddRange(daprAppPortArg(endPoint.Value.appEndpoint.Port)());
}
var grpc = daprCli.GetEndpoint("grpc");
var http = daprCli.GetEndpoint("http");
var metrics = daprCli.GetEndpoint("metrics");
updatedArgs.AddRange(daprGrpcPortArg(grpc.Property(EndpointProperty.TargetPort))());
updatedArgs.AddRange(daprHttpPortArg(http.Property(EndpointProperty.TargetPort))());
updatedArgs.AddRange(daprMetricsPortArg(metrics.Property(EndpointProperty.TargetPort))());
if (sidecarOptions?.EnableProfiling == true)
{
var profiling = daprCli.GetEndpoint("profiling");
updatedArgs.AddRange(daprProfilePortArg(profiling.Property(EndpointProperty.TargetPort))());
}
if (sidecarOptions?.AppChannelAddress is null && endPoint is { appEndpoint.IsAllocated: true })
{
updatedArgs.AddRange(daprAppChannelAddressArg(endPoint.Value.appEndpoint.Host)());
}
if (sidecarOptions?.AppProtocol is null && endPoint is { appEndpoint.IsAllocated: true })
{
updatedArgs.AddRange(daprAppProtocol(endPoint.Value.protocol)());
}
}));
// Apply environment variables to the CLI...
daprCli.Annotations.AddRange(daprSidecar.Annotations.OfType<EnvironmentCallbackAnnotation>());
// The CLI is an artifact of a local run, so it should not be published...
daprCli.Annotations.Add(ManifestPublishingCallbackAnnotation.Ignore);
// https://github.com/CommunityToolkit/Aspire/issues/507
// The CLI should be a child of the resource that it is associated with.
daprCli.Annotations.Add(new ResourceRelationshipAnnotation(resource, "Parent"));
daprSidecar.Annotations.Add(
new ManifestPublishingCallbackAnnotation(
context =>
{
context.Writer.WriteString("type", "dapr.v0");
context.Writer.WriteStartObject("dapr");
context.Writer.WriteString("application", resource.Name);
context.Writer.TryWriteString("appChannelAddress", sidecarOptions?.AppChannelAddress);
context.Writer.TryWriteString("appHealthCheckPath", sidecarOptions?.AppHealthCheckPath);
context.Writer.TryWriteNumber("appHealthProbeInterval", sidecarOptions?.AppHealthProbeInterval);
context.Writer.TryWriteNumber("appHealthProbeTimeout", sidecarOptions?.AppHealthProbeTimeout);
context.Writer.TryWriteNumber("appHealthThreshold", sidecarOptions?.AppHealthThreshold);
context.Writer.TryWriteString("appId", appId);
context.Writer.TryWriteNumber("appMaxConcurrency", sidecarOptions?.AppMaxConcurrency);
context.Writer.TryWriteNumber("appPort", sidecarOptions?.AppPort);
context.Writer.TryWriteString("appProtocol", sidecarOptions?.AppProtocol);
context.Writer.TryWriteStringArray("command", sidecarOptions?.Command);
context.Writer.TryWriteStringArray("components", componentReferenceAnnotations.Select(componentReferenceAnnotation => componentReferenceAnnotation.Component.Name));
context.Writer.TryWriteString("config", context.GetManifestRelativePath(sidecarOptions?.Config));
context.Writer.TryWriteNumber("daprGrpcPort", sidecarOptions?.DaprGrpcPort);
context.Writer.TryWriteString("daprMaxBodySize", sidecarOptions?.DaprMaxBodySize);
context.Writer.TryWriteNumber("daprHttpPort", sidecarOptions?.DaprHttpPort);
context.Writer.TryWriteString("daprReadBufferSize", sidecarOptions?.DaprReadBufferSize);
context.Writer.TryWriteNumber("daprInternalGrpcPort", sidecarOptions?.DaprInternalGrpcPort);
context.Writer.TryWriteString("daprListenAddresses", sidecarOptions?.DaprListenAddresses);
context.Writer.TryWriteBoolean("enableApiLogging", sidecarOptions?.EnableApiLogging);
context.Writer.TryWriteBoolean("enableAppHealthCheck", sidecarOptions?.EnableAppHealthCheck);
context.Writer.TryWriteString("logLevel", sidecarOptions?.LogLevel);
context.Writer.TryWriteNumber("metricsPort", sidecarOptions?.MetricsPort);
context.Writer.TryWriteString("placementHostAddress", sidecarOptions?.PlacementHostAddress);
context.Writer.TryWriteNumber("profilePort", sidecarOptions?.ProfilePort);
context.Writer.TryWriteStringArray("resourcesPath", sidecarOptions?.ResourcesPaths.Select(path => context.GetManifestRelativePath(path)));
context.Writer.TryWriteString("runFile", context.GetManifestRelativePath(sidecarOptions?.RunFile));
context.Writer.TryWriteString("runtimePath", context.GetManifestRelativePath(sidecarOptions?.RuntimePath));
context.Writer.TryWriteString("schedulerHostAddress", sidecarOptions?.SchedulerHostAddress);
context.Writer.TryWriteString("unixDomainSocket", sidecarOptions?.UnixDomainSocket);
context.Writer.WriteEndObject();
}));
if (_options.PublishingConfigurationAction is Action<IResource, DaprSidecarOptions?> configurePublishAction)
{
configurePublishAction(resource, sidecarOptions);
}
sideCars.Add(daprCli);
}
appModel.Resources.AddRange(sideCars);
}
private static string? GetValueIfSet(string? newValue, int? obsoleteValue, string notation)
{
if (newValue is not null) return newValue;
if (obsoleteValue is not null) return $"{obsoleteValue}{notation}";
return null;
}
private string GetAppHostDirectory() =>
configuration["AppHost:Directory"]
?? throw new InvalidOperationException("Unable to obtain the application host directory.");
// This method resolves the application's endpoint and the protocol that the dapr side car will use.
// It depends on DaprSidecarOptions.AppProtocol and DaprSidecarOptions.AppEndpoint.
// - If both are null default to 'http' for both.
// - If AppProtocol is not null try to get an endpoint with the name of the protocol.
// - if AppEndpoint is not null try to use the scheme as the protocol.
// - if both are not null just use both options.
static (EndpointReference appEndpoint, string protocol)? GetEndpointReference(DaprSidecarOptions? sidecarOptions, IResource resource)
{
if (resource is IResourceWithEndpoints resourceWithEndpoints)
{
return (sidecarOptions?.AppProtocol, sidecarOptions?.AppEndpoint) switch
{
(null, null) => (resourceWithEndpoints.GetEndpoint("http"), "http"),
(null, string appEndpoint) => (resourceWithEndpoints.GetEndpoint(appEndpoint), resourceWithEndpoints.GetEndpoint(appEndpoint).Scheme),
(string appProtocol, null) => (resourceWithEndpoints.GetEndpoint(appProtocol), appProtocol),
(string appProtocol, string appEndpoint) => (resourceWithEndpoints.GetEndpoint(appEndpoint), appProtocol)
};
}
return null;
}
/// <summary>
/// Return the first verified dapr path
/// </summary>
static string? GetDefaultDaprPath()
{
foreach (var path in GetAvailablePaths())
{
if (File.Exists(path))
{
return path;
}
}
return default;
// Return all the possible paths for dapr
static IEnumerable<string> GetAvailablePaths()
{
if (OperatingSystem.IsWindows())
{
var pathRoot = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.Windows)) ?? "C:";
// Installed windows paths:
yield return Path.Combine(pathRoot, "dapr", "dapr.exe");
// Add all the paths that are reachable via the `PATH` environment variable:
var possibleWindowsDaprPaths = Environment.GetEnvironmentVariable("PATH")?
.Split(Path.PathSeparator)
.Select(path => Path.Combine(path, "dapr.exe"))
.Where(File.Exists) ?? [];
foreach (var path in possibleWindowsDaprPaths)
{
yield return path;
}
yield break;
}
// Add $HOME/dapr path:
var homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
yield return Path.Combine(homePath, "dapr", "dapr");
// Linux & MacOS path:
yield return "/usr/local/bin/dapr";
// Arch Linux path:
yield return "/usr/bin/dapr";
// MacOS Homebrew path:
if (OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("HOMEBREW_PREFIX") is string homebrewPrefix)
{
yield return Path.Combine(homebrewPrefix, "bin", "dapr");
}
// Add all the paths that are reachable via the `PATH` environment variable:
var possibleDaprPaths = Environment.GetEnvironmentVariable("PATH")?
.Split(Path.PathSeparator)
.Select(path => Path.Combine(path, "dapr"))
.Where(File.Exists) ?? [];
foreach (var path in possibleDaprPaths)
{
yield return path;
}
}
}
private static void SetupComponentLifecycle(DistributedApplicationModel appModel)
{
// Setup proper lifecycle for Dapr components with their dependencies
// Components will manage their own state and wait for their dependencies
foreach (var component in appModel.Resources.OfType<IDaprComponentResource>())
{
var dependencies = new HashSet<IResource>();
if (component.TryGetAnnotationsOfType<DaprComponentValueProviderAnnotation>(out var valueProviderAnnotations))
{
foreach (var annotation in valueProviderAnnotations)
{
// Extract resource references from value providers - following the same pattern as SetupSidecarLifecycle
if (annotation.ValueProvider is IResourceWithoutLifetime)
{
// Skip waiting for resources without a lifetime
continue;
}
if (annotation.ValueProvider is IResource resource)
{
dependencies.Add(resource);
}
else if (annotation.ValueProvider is IValueWithReferences valueWithReferences)
{
foreach (var innerRef in valueWithReferences.References.OfType<IResource>())
{
if (innerRef is not IResourceWithoutLifetime)
{
dependencies.Add(innerRef);
}
}
}
}
}
// Add WaitAnnotations for each unique dependency
// This ensures the component waits for its dependencies before becoming ready
foreach (var dependency in dependencies)
{
component.Annotations.Add(new WaitAnnotation(dependency, WaitType.WaitUntilHealthy));
}
}
}
public void Dispose()
{
if (_onDemandResourcesRootPath is not null)
{
logger.LogInformation("Stopping Dapr-related resources...");
try
{
Directory.Delete(_onDemandResourcesRootPath, recursive: true);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to delete temporary Dapr resources directory: {OnDemandResourcesRootPath}", _onDemandResourcesRootPath);
}
}
}
private async Task<IReadOnlyDictionary<string, string>> StartOnDemandDaprComponentsAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken)
{
var onDemandComponents =
appModel
.Resources
.OfType<DaprComponentResource>()
.Where(component => component.Options?.LocalPath is null)
.ToList();
// If any of the components have secrets or value provider references, we will add an on-demand secret store component.
bool needsSecretStore = onDemandComponents.Any(component =>
(component.TryGetAnnotationsOfType<DaprComponentSecretAnnotation>(out var secretAnnotations) && secretAnnotations.Any()) ||
(component.TryGetAnnotationsOfType<DaprComponentValueProviderAnnotation>(out var valueProviderAnnotations) && valueProviderAnnotations.Any()));
if (needsSecretStore)
{
onDemandComponents.Add(new DaprComponentResource("secretstore", DaprConstants.BuildingBlocks.SecretStore));
}
var onDemandResourcesPaths = new Dictionary<string, string>();
if (onDemandComponents.Any())
{
logger.LogInformation("Starting Dapr-related resources...");
_onDemandResourcesRootPath = Directory.CreateTempSubdirectory("aspire-dapr.").FullName;
foreach (var component in onDemandComponents)
{
Func<string, Task<string>> contentWriter =
async content =>
{
logger.LogDebug("Creating on-demand configuration for component '{ComponentName}' with content: {content}.", component.Name, content);
string componentDirectory = Path.Combine(_onDemandResourcesRootPath, component.Name);
Directory.CreateDirectory(componentDirectory);
string componentPath = Path.Combine(componentDirectory, $"{component.Name}.yaml");
await File.WriteAllTextAsync(componentPath, content, cancellationToken).ConfigureAwait(false);
return componentPath;
};
string componentPath = await (component.Type switch
{
DaprConstants.BuildingBlocks.PubSub => GetBuildingBlockComponentAsync(component, contentWriter, "pubsub.in-memory", cancellationToken), // NOTE: In memory component can only be used within a single Dapr application.
DaprConstants.BuildingBlocks.StateStore => GetBuildingBlockComponentAsync(component, contentWriter, "state.in-memory", cancellationToken),
DaprConstants.BuildingBlocks.SecretStore => GetBuildingBlockComponentAsync(component, contentWriter, "secretstores.local.env", cancellationToken),
_ => GetComponentAsync(component, contentWriter, cancellationToken)
}).ConfigureAwait(false);
onDemandResourcesPaths.Add(component.Name, componentPath);
}
}
return onDemandResourcesPaths;
}
private async Task<string> GetComponentAsync(DaprComponentResource component, Func<string, Task<string>> contentWriter, CancellationToken cancellationToken)
{
// We should try to read content from a known location (such as aspire root directory)
logger.LogInformation("Unvalidated configuration {specType} for component '{ComponentName}'.", component.Type, component.Name);
return await contentWriter(await GetDaprComponent(component, component.Type, cancellationToken)).ConfigureAwait(false);
}
private async Task<string> GetBuildingBlockComponentAsync(DaprComponentResource component, Func<string, Task<string>> contentWriter, string defaultProvider, CancellationToken cancellationToken)
{
// Start by trying to get the component from the app host directory
string daprAppHostRelativePath = GetAppHostRelativePath(component.Type);
if (File.Exists(daprAppHostRelativePath))
{
logger.LogInformation("Using apphost relative path for dapr component '{ComponentName}'.", component.Name);
string newContent = await GetDefaultContent(component, daprAppHostRelativePath, cancellationToken).ConfigureAwait(false);
return await contentWriter(newContent).ConfigureAwait(false);
}
// If the component is not found in the app host directory, try to get it from the default components directory
string daprDefaultStorePath = GetDefaultComponentPath(component.Type);
if (File.Exists(daprDefaultStorePath))
{
logger.LogInformation("Using default dapr path for component '{ComponentName}'.", component.Name);
string newContent = await GetDefaultContent(component, daprDefaultStorePath, cancellationToken).ConfigureAwait(false);
return await contentWriter(newContent).ConfigureAwait(false);
}
// If the component is not found in the default components directory, use the in-memory secret store
logger.LogInformation("Using in-memory provider for dapr component '{ComponentName}'.", component.Name);
var content = new DaprComponentSchema(component.Name, defaultProvider).ToString();
return await contentWriter(content).ConfigureAwait(false);
}
private string GetAppHostRelativePath(string componentName)
{
string appHostDirectory = GetAppHostDirectory();
string daprDefaultComponentsDirectory = Path.Combine(appHostDirectory, ".dapr", "components");
return Path.Combine(daprDefaultComponentsDirectory, $"{componentName}.yaml");
}
private static string GetDefaultComponentPath(string componentName)
{
string userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string daprDefaultComponentsDirectory = Path.Combine(userDirectory, ".dapr", "components");
return Path.Combine(daprDefaultComponentsDirectory, $"{componentName}.yaml");
}
private static async Task<string> GetDefaultContent(DaprComponentResource component, string defaultContentPath, CancellationToken cancellationToken)
{
string defaultContent = await File.ReadAllTextAsync(defaultContentPath, cancellationToken).ConfigureAwait(false);
string yaml = defaultContent.Replace($"name: {component.Type}", $"name: {component.Name}");
DaprComponentSchema content = DaprComponentSchema.FromYaml(yaml);
await ConfigureDaprComponent(component, content, cancellationToken);
await content.ResolveAllValuesAsync(cancellationToken);
return content.ToString();
}
private static async Task<string> GetDaprComponent(DaprComponentResource component, string type, CancellationToken cancellationToken = default)
{
var content = new DaprComponentSchema(component.Name, type);
await ConfigureDaprComponent(component, content, cancellationToken);
await content.ResolveAllValuesAsync(cancellationToken);
return content.ToString();
}
private static async Task ConfigureDaprComponent(DaprComponentResource component, DaprComponentSchema content, CancellationToken cancellationToken = default)
{
if (component.TryGetAnnotationsOfType<DaprComponentSecretAnnotation>(out var secrets) && secrets.Any())
{
content.Auth = new DaprComponentAuth { SecretStore = "secretstore" };
}
if (component.TryGetAnnotationsOfType<DaprComponentConfigurationAnnotation>(out var annotations))
{
foreach (var annotation in annotations)
{
await annotation.Configure(content, cancellationToken);
}
}
}
}
internal static class IListExtensions
{
public static void AddRange<T>(this IList<T> list, IEnumerable<T> collection)
{
foreach (var item in collection)
{
list.Add(item);
}
}
}