-
Notifications
You must be signed in to change notification settings - Fork 885
Expand file tree
/
Copy pathDcpHost.cs
More file actions
460 lines (393 loc) · 17.8 KB
/
DcpHost.cs
File metadata and controls
460 lines (393 loc) · 17.8 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections;
using System.IO.Pipelines;
using System.Net.Sockets;
using System.Text;
using Aspire.Dashboard.Utils;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Dcp.Process;
using Aspire.Hosting.Resources;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Aspire.Hosting.Dcp;
#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.
internal sealed class DcpHost
{
private const int LoggingSocketConnectionBacklog = 3;
private readonly DistributedApplicationModel _applicationModel;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;
private readonly DcpOptions _dcpOptions;
private readonly IDcpDependencyCheckService _dependencyCheckService;
private readonly IInteractionService _interactionService;
private readonly Locations _locations;
private readonly TimeProvider _timeProvider;
private readonly CancellationTokenSource _shutdownCts = new();
private Task? _logProcessorTask;
// These environment variables should never be inherited by DCP from app host.
private static readonly string[] s_doNotInheritEnvironmentVars =
{
"ASPNETCORE_URLS",
"DOTNET_LAUNCH_PROFILE",
"ASPNETCORE_ENVIRONMENT",
"DOTNET_ENVIRONMENT"
};
public DcpHost(
ILoggerFactory loggerFactory,
IOptions<DcpOptions> dcpOptions,
IDcpDependencyCheckService dependencyCheckService,
IInteractionService interactionService,
Locations locations,
DistributedApplicationModel applicationModel,
TimeProvider timeProvider)
{
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<DcpHost>();
_dcpOptions = dcpOptions.Value;
_dependencyCheckService = dependencyCheckService;
_interactionService = interactionService;
_locations = locations;
_applicationModel = applicationModel;
_timeProvider = timeProvider;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await EnsureDcpContainerRuntimeAsync(cancellationToken).ConfigureAwait(false);
EnsureDcpHostRunning();
}
internal async Task EnsureDcpContainerRuntimeAsync(CancellationToken cancellationToken)
{
// Ensure DCP is installed and has all required dependencies
var dcpInfo = await _dependencyCheckService.GetDcpInfoAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (dcpInfo is null)
{
return;
}
// If we don't have any resources that need a container then we
// don't need to check for a healthy container runtime.
if (!_applicationModel.Resources.Any(c => c.IsContainer()))
{
return;
}
AspireEventSource.Instance.ContainerRuntimeHealthCheckStart();
try
{
bool requireContainerRuntimeInitialization = _dcpOptions.ContainerRuntimeInitializationTimeout > TimeSpan.Zero;
if (requireContainerRuntimeInitialization)
{
using var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCancellation.CancelAfter(_dcpOptions.ContainerRuntimeInitializationTimeout);
try
{
while (dcpInfo is not null && !IsContainerRuntimeHealthy(dcpInfo))
{
await Task.Delay(TimeSpan.FromSeconds(2), timeoutCancellation.Token).ConfigureAwait(false);
dcpInfo = await _dependencyCheckService.GetDcpInfoAsync(force: true, cancellationToken: timeoutCancellation.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (timeoutCancellation.IsCancellationRequested)
{
// Swallow the cancellation exception and let it bubble up as a more helpful error
// about the container runtime in CheckDcpInfoAndLogErrors.
}
}
if (dcpInfo is not null)
{
DcpDependencyCheck.CheckDcpInfoAndLogErrors(_logger, _dcpOptions, dcpInfo, throwIfUnhealthy: requireContainerRuntimeInitialization);
// Show UI notification if container runtime is unhealthy
TryShowContainerRuntimeNotification(dcpInfo, cancellationToken);
}
}
finally
{
AspireEventSource.Instance?.ContainerRuntimeHealthCheckStop();
}
}
public async Task StopAsync()
{
_shutdownCts.Cancel();
await TaskHelpers.WaitIgnoreCancelAsync(_logProcessorTask, _logger, "Error in logging socket processor.").ConfigureAwait(false);
}
private void EnsureDcpHostRunning()
{
AspireEventSource.Instance.DcpApiServerLaunchStart();
try
{
var dcpProcessSpec = CreateDcpProcessSpec(_locations);
// Enable Unix Domain Socket based log streaming from DCP
try
{
AspireEventSource.Instance.DcpLogSocketCreateStart();
var loggingSocket = CreateLoggingSocket(_locations.DcpLogSocket);
loggingSocket.Listen(LoggingSocketConnectionBacklog);
dcpProcessSpec.EnvironmentVariables.Add("DCP_LOG_SOCKET", _locations.DcpLogSocket);
if (!string.IsNullOrWhiteSpace(_dcpOptions.LogFileNameSuffix))
{
dcpProcessSpec.EnvironmentVariables.Add("DCP_LOG_FILE_NAME_SUFFIX", _dcpOptions.LogFileNameSuffix);
}
_logProcessorTask = Task.Run(() => StartLoggingSocketAsync(loggingSocket));
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to enable orchestration logging.");
}
finally
{
AspireEventSource.Instance.DcpLogSocketCreateStop();
}
_ = ProcessUtil.Run(dcpProcessSpec);
}
finally
{
AspireEventSource.Instance.DcpApiServerLaunchStop();
}
}
private ProcessSpec CreateDcpProcessSpec(Locations locations)
{
var dcpExePath = _dcpOptions.CliPath;
if (!File.Exists(dcpExePath))
{
throw new FileNotFoundException($"The Developer Control Plane is not installed at \"{dcpExePath}\". The application cannot be run without it.", dcpExePath);
}
var arguments = $"start-apiserver --monitor {Environment.ProcessId} --detach --kubeconfig \"{locations.DcpKubeconfigPath}\"";
if (!string.IsNullOrEmpty(_dcpOptions.ContainerRuntime))
{
arguments += $" --container-runtime \"{_dcpOptions.ContainerRuntime}\"";
}
var dcpProcessSpec = new ProcessSpec(dcpExePath)
{
WorkingDirectory = Directory.GetCurrentDirectory(),
Arguments = arguments,
OnOutputData = Console.Out.Write,
OnErrorData = Console.Error.Write,
InheritEnv = false,
};
_logger.LogInformation("Starting DCP with arguments: {Arguments}", dcpProcessSpec.Arguments);
if (!string.IsNullOrEmpty(_dcpOptions.ExtensionsPath))
{
dcpProcessSpec.EnvironmentVariables.Add("DCP_EXTENSIONS_PATH", _dcpOptions.ExtensionsPath);
}
if (!string.IsNullOrEmpty(_dcpOptions.BinPath))
{
dcpProcessSpec.EnvironmentVariables.Add("DCP_BIN_PATH", _dcpOptions.BinPath);
}
// Set an environment variable to contain session info that should be deleted when DCP is done
// Currently this contains the Unix socket for logging and the kubeconfig
dcpProcessSpec.EnvironmentVariables.Add("DCP_SESSION_FOLDER", locations.DcpSessionDir);
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
var key = de.Key?.ToString();
var val = de.Value?.ToString();
if (key is not null && val is not null && !s_doNotInheritEnvironmentVars.Contains(key))
{
dcpProcessSpec.EnvironmentVariables[key] = val;
}
}
return dcpProcessSpec;
}
private static Socket CreateLoggingSocket(string socketPath)
{
var directoryName = Path.GetDirectoryName(socketPath);
if (!string.IsNullOrEmpty(directoryName))
{
if (OperatingSystem.IsWindows())
{
Directory.CreateDirectory(directoryName);
}
else
{
Directory.CreateDirectory(directoryName, UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead);
}
}
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
socket.Bind(new UnixDomainSocketEndPoint(socketPath));
return socket;
}
private async Task StartLoggingSocketAsync(Socket socket)
{
List<Task> outputLoggers = [];
while (!_shutdownCts.IsCancellationRequested)
{
try
{
var acceptedSocket = await socket.AcceptAsync(_shutdownCts.Token).ConfigureAwait(false);
outputLoggers.Add(Task.Run(() => LogSocketOutputAsync(acceptedSocket, _shutdownCts.Token)));
}
catch
{
// Suppress exceptions reading logs from DCP controllers
}
}
await Task.WhenAll(outputLoggers).ConfigureAwait(false);
socket.Dispose();
}
private async Task LogSocketOutputAsync(Socket socket, CancellationToken cancellationToken)
{
using var stream = new NetworkStream(socket, ownsSocket: true);
using var _ = cancellationToken.Register(s => ((NetworkStream)s!).Close(), stream);
var reader = PipeReader.Create(stream);
// Logger cache to avoid creating a new string per log line, for a few categories
var loggerCache = new Dictionary<int, ILogger>();
(ILogger, LogLevel, string message) GetLogInfo(ReadOnlySpan<byte> line)
{
if (!DcpLogParser.TryParseDcpLog(line, out var parsedMessage, out var logLevel, out var category))
{
// If parsing fails, return a default logger and the line as-is
return (_logger, LogLevel.Information, Encoding.UTF8.GetString(line));
}
var hash = new HashCode();
hash.AddBytes(Encoding.UTF8.GetBytes(category));
var hashValue = hash.ToHashCode();
if (!loggerCache.TryGetValue(hashValue, out var logger))
{
// loggerFactory.CreateLogger internally caches, but we may as well cache the logger as well as the string
// for the lifetime of this socket
loggerCache[hashValue] = logger = _loggerFactory.CreateLogger($"Aspire.Hosting.Dcp.{category}");
}
return (logger, logLevel, parsedMessage);
}
try
{
void LogLines(in ReadOnlySequence<byte> buffer, out SequencePosition position)
{
var seq = new SequenceReader<byte>(buffer);
while (seq.TryReadTo(out ReadOnlySpan<byte> line, (byte)'\n'))
{
var (logger, logLevel, message) = GetLogInfo(line);
logger.Log(logLevel, 0, message, null, static (value, ex) => value);
}
position = seq.Position;
}
while (!cancellationToken.IsCancellationRequested)
{
var result = await reader.ReadAsync(CancellationToken.None).ConfigureAwait(false);
if (result.IsCompleted || result.IsCanceled)
{
break;
}
LogLines(result.Buffer, out var position);
reader.AdvanceTo(position, result.Buffer.End);
}
}
catch
{
// Suppress exceptions reading logs from DCP controllers
}
finally
{
reader.Complete();
}
}
private void TryShowContainerRuntimeNotification(DcpInfo dcpInfo, CancellationToken cancellationToken)
{
// Check if the interaction service is available (dashboard enabled)
if (!_interactionService.IsAvailable)
{
return;
}
var containerRuntime = _dcpOptions.ContainerRuntime;
if (string.IsNullOrEmpty(containerRuntime))
{
// Default runtime is Docker
containerRuntime = "docker";
}
var installed = dcpInfo.Containers?.Installed ?? false;
var running = dcpInfo.Containers?.Running ?? false;
// Early check: if container runtime is not installed, show notification and return immediately (no polling)
if (!installed)
{
string title = InteractionStrings.ContainerRuntimeNotInstalledTitle;
string message = InteractionStrings.ContainerRuntimeNotInstalledMessage;
var options = new NotificationInteractionOptions
{
Intent = MessageIntent.Error,
LinkText = InteractionStrings.ContainerRuntimeLinkText,
LinkUrl = "https://aka.ms/dotnet/aspire/containers"
};
// Show notification without polling (non-auto-dismiss)
_ = _interactionService.PromptNotificationAsync(title, message, options, cancellationToken);
return;
}
// Only show notification if container runtime is installed but not running
// If not installed, that's usually a more fundamental setup issue that would be addressed differently
if (installed && !running)
{
string title = InteractionStrings.ContainerRuntimeUnhealthyTitle;
var (message, linkUrl) = DcpDependencyCheck.BuildContainerRuntimeUnhealthyMessage(containerRuntime);
var options = new NotificationInteractionOptions
{
Intent = MessageIntent.Error,
LinkText = linkUrl is not null ? InteractionStrings.ContainerRuntimeLinkText : null,
LinkUrl = linkUrl
};
// Create a cancellation token source that can be cancelled when runtime becomes healthy
var notificationCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _shutdownCts.Token);
// Single background task to show notification and poll for health updates
_ = Task.Run(async () =>
{
try
{
// First, show the notification
var notificationTask = _interactionService.PromptNotificationAsync(title, message, options, notificationCts.Token);
// Then poll for container runtime health updates every 5 seconds
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), _timeProvider);
while (await timer.WaitForNextTickAsync(notificationCts.Token).ConfigureAwait(false))
{
try
{
var dcpInfo = await _dependencyCheckService.GetDcpInfoAsync(force: true, cancellationToken: notificationCts.Token).ConfigureAwait(false);
if (dcpInfo is not null && IsContainerRuntimeHealthy(dcpInfo))
{
// Container runtime is now healthy, exit the polling loop
break;
}
}
catch (OperationCanceledException)
{
// Expected when cancellation is requested
break;
}
catch (Exception ex)
{
// Log but continue polling
_logger.LogDebug(ex, "Error while polling container runtime health for notification");
}
}
// Cancel the notification at the end of the loop
notificationCts.Cancel();
// Wait for notification task to complete
try
{
await notificationTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Expected when notification is cancelled
}
}
catch (OperationCanceledException)
{
// Expected when cancellation is requested
}
catch (Exception ex)
{
// Log but don't propagate notification errors
_logger.LogDebug(ex, "Failed to show container runtime notification or poll for health");
}
finally
{
notificationCts.Dispose();
}
}, cancellationToken);
}
}
private static bool IsContainerRuntimeHealthy(DcpInfo dcpInfo)
{
var installed = dcpInfo.Containers?.Installed ?? false;
var running = dcpInfo.Containers?.Running ?? false;
return installed && running;
}
}
#pragma warning restore ASPIREINTERACTION001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.