-
Notifications
You must be signed in to change notification settings - Fork 882
Expand file tree
/
Copy pathRunModeProvisioningContextProvider.cs
More file actions
276 lines (240 loc) · 12.4 KB
/
RunModeProvisioningContextProvider.cs
File metadata and controls
276 lines (240 loc) · 12.4 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
#pragma warning disable ASPIREINTERACTION001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
#pragma warning disable ASPIREPIPELINES002 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Cryptography;
using Aspire.Hosting.Azure.Resources;
using Aspire.Hosting.Azure.Utils;
using Aspire.Hosting.Pipelines;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Aspire.Hosting.Azure.Provisioning.Internal;
/// <summary>
/// Run mode implementation of <see cref="IProvisioningContextProvider"/>.
/// </summary>
internal sealed class RunModeProvisioningContextProvider(
IInteractionService interactionService,
IOptions<AzureProvisionerOptions> options,
IHostEnvironment environment,
ILogger<RunModeProvisioningContextProvider> logger,
IArmClientProvider armClientProvider,
IUserPrincipalProvider userPrincipalProvider,
ITokenCredentialProvider tokenCredentialProvider,
IDeploymentStateManager deploymentStateManager,
DistributedApplicationExecutionContext distributedApplicationExecutionContext) : BaseProvisioningContextProvider(
interactionService,
options,
environment,
logger,
armClientProvider,
userPrincipalProvider,
tokenCredentialProvider,
deploymentStateManager,
distributedApplicationExecutionContext)
{
private readonly TaskCompletionSource _provisioningOptionsAvailable = new(TaskCreationOptions.RunContinuationsAsynchronously);
protected override string GetDefaultResourceGroupName()
{
var prefix = "rg-aspire";
if (!string.IsNullOrWhiteSpace(_options.ResourceGroupPrefix))
{
prefix = _options.ResourceGroupPrefix;
}
var suffix = RandomNumberGenerator.GetHexString(8, lowercase: true);
var maxApplicationNameSize = ResourceGroupNameHelpers.MaxResourceGroupNameLength - prefix.Length - suffix.Length - 2; // extra '-'s
var normalizedApplicationName = ResourceGroupNameHelpers.NormalizeResourceGroupName(_environment.ApplicationName.ToLowerInvariant());
if (normalizedApplicationName.Length > maxApplicationNameSize)
{
normalizedApplicationName = normalizedApplicationName[..maxApplicationNameSize];
}
// Run mode always includes random suffix for uniqueness
return $"{prefix}-{normalizedApplicationName}-{suffix}";
}
private void EnsureProvisioningOptions()
{
if (!_interactionService.IsAvailable ||
(!string.IsNullOrEmpty(_options.Location) && !string.IsNullOrEmpty(_options.SubscriptionId)))
{
// If the interaction service is not available, or
// if all options are already set, we can skip the prompt
_provisioningOptionsAvailable.TrySetResult();
return;
}
// Start the loop that will allow the user to specify the Azure provisioning options
_ = Task.Run(async () =>
{
try
{
await RetrieveAzureProvisioningOptions().ConfigureAwait(false);
_logger.LogDebug("Azure provisioning options have been handled successfully.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve Azure provisioning options.");
_provisioningOptionsAvailable.SetException(ex);
}
});
}
public override async Task<ProvisioningContext> CreateProvisioningContextAsync(CancellationToken cancellationToken = default)
{
EnsureProvisioningOptions();
await _provisioningOptionsAvailable.Task.ConfigureAwait(false);
return await base.CreateProvisioningContextAsync(cancellationToken).ConfigureAwait(false);
}
private async Task RetrieveAzureProvisioningOptions(CancellationToken cancellationToken = default)
{
while (_options.Location == null || _options.SubscriptionId == null)
{
var messageBarResult = await _interactionService.PromptNotificationAsync(
AzureProvisioningStrings.NotificationTitle,
AzureProvisioningStrings.NotificationMessage,
new NotificationInteractionOptions
{
Intent = MessageIntent.Warning,
PrimaryButtonText = AzureProvisioningStrings.NotificationPrimaryButtonText
},
cancellationToken)
.ConfigureAwait(false);
if (messageBarResult.Canceled)
{
// User canceled the prompt, so we exit the loop
_provisioningOptionsAvailable.SetException(new MissingConfigurationException("Azure provisioning options were not provided."));
return;
}
if (messageBarResult.Data)
{
var inputs = new List<InteractionInput>();
// Skip tenant prompting if subscription ID is already set
if (string.IsNullOrEmpty(_options.SubscriptionId))
{
inputs.Add(new InteractionInput
{
Name = TenantName,
InputType = InputType.Choice,
Label = AzureProvisioningStrings.TenantLabel,
Required = true,
AllowCustomChoice = true,
Placeholder = AzureProvisioningStrings.TenantPlaceholder,
DynamicLoading = new InputLoadOptions
{
LoadCallback = async (context) =>
{
var (tenantOptions, fetchSucceeded) =
await TryGetTenantsAsync(cancellationToken).ConfigureAwait(false);
context.Input.Options = fetchSucceeded
? tenantOptions!
: [];
}
}
});
}
// If the subscription ID is already set
// show the value as from the configuration and disable the input
// there should be no option to change it
InputLoadOptions? subscriptionLoadOptions = null;
if (string.IsNullOrEmpty(_options.SubscriptionId))
{
subscriptionLoadOptions = new InputLoadOptions
{
LoadCallback = async (context) =>
{
// Get tenant ID from input if tenant selection is enabled, otherwise use configured value
var tenantId = context.AllInputs[TenantName].Value ?? string.Empty;
var (subscriptionOptions, fetchSucceeded) =
await TryGetSubscriptionsAsync(tenantId, cancellationToken).ConfigureAwait(false);
context.Input.Options = fetchSucceeded
? subscriptionOptions!
: [];
context.Input.Disabled = false;
},
DependsOnInputs = [TenantName]
};
}
inputs.Add(new InteractionInput
{
Name = SubscriptionIdName,
InputType = string.IsNullOrEmpty(_options.SubscriptionId) ? InputType.Choice : InputType.Text,
Label = AzureProvisioningStrings.SubscriptionIdLabel,
Required = true,
AllowCustomChoice = true,
Placeholder = AzureProvisioningStrings.SubscriptionIdPlaceholder,
Disabled = true,
Value = _options.SubscriptionId,
DynamicLoading = subscriptionLoadOptions
});
inputs.Add(new InteractionInput
{
Name = LocationName,
InputType = InputType.Choice,
Label = AzureProvisioningStrings.LocationLabel,
Placeholder = AzureProvisioningStrings.LocationPlaceholder,
Required = true,
Disabled = string.IsNullOrEmpty(_options.SubscriptionId),
DynamicLoading = new InputLoadOptions
{
LoadCallback = async (context) =>
{
var subscriptionId = context.AllInputs[SubscriptionIdName].Value ?? string.Empty;
var (locationOptions, _) = await TryGetLocationsAsync(subscriptionId, cancellationToken).ConfigureAwait(false);
context.Input.Options = locationOptions;
context.Input.Disabled = false;
},
DependsOnInputs = string.IsNullOrEmpty(_options.SubscriptionId) ? [SubscriptionIdName] : []
}
});
inputs.Add(new InteractionInput
{
Name = ResourceGroupName,
InputType = InputType.Text,
Label = AzureProvisioningStrings.ResourceGroupLabel,
Value = GetDefaultResourceGroupName()
});
var result = await _interactionService.PromptInputsAsync(
AzureProvisioningStrings.InputsTitle,
AzureProvisioningStrings.InputsMessage,
inputs,
new InputsDialogInteractionOptions
{
EnableMessageMarkdown = true,
ValidationCallback = (validationContext) =>
{
// Only validate tenant if it's included in the inputs
if (validationContext.Inputs.TryGetByName(TenantName, out var tenantInput))
{
if (!string.IsNullOrWhiteSpace(tenantInput.Value) && !Guid.TryParse(tenantInput.Value, out _))
{
validationContext.AddValidationError(tenantInput, AzureProvisioningStrings.ValidationTenantIdInvalid);
}
}
var subscriptionInput = validationContext.Inputs[SubscriptionIdName];
if (!string.IsNullOrWhiteSpace(subscriptionInput.Value) && !Guid.TryParse(subscriptionInput.Value, out _))
{
validationContext.AddValidationError(subscriptionInput, AzureProvisioningStrings.ValidationSubscriptionIdInvalid);
}
var resourceGroupInput = validationContext.Inputs[ResourceGroupName];
if (!IsValidResourceGroupName(resourceGroupInput.Value))
{
validationContext.AddValidationError(resourceGroupInput, AzureProvisioningStrings.ValidationResourceGroupNameInvalid);
}
return Task.CompletedTask;
}
},
cancellationToken).ConfigureAwait(false);
if (!result.Canceled)
{
// Only set tenant ID if it was part of the input (when subscription ID wasn't already set)
if (result.Data.TryGetByName(TenantName, out var tenantInput))
{
_options.TenantId = tenantInput.Value;
}
_options.Location = result.Data[LocationName].Value;
_options.SubscriptionId ??= result.Data[SubscriptionIdName].Value;
_options.ResourceGroup = result.Data[ResourceGroupName].Value;
_options.AllowResourceGroupCreation = true; // Allow the creation of the resource group if it does not exist.
_provisioningOptionsAvailable.SetResult();
}
}
}
}
}