This repository was archived by the owner on Nov 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathDockerRunner.cs
More file actions
660 lines (525 loc) · 28.2 KB
/
Copy pathDockerRunner.cs
File metadata and controls
660 lines (525 loc) · 28.2 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Tye.Hosting.Model;
namespace Microsoft.Tye.Hosting
{
public class DockerRunner : IApplicationProcessor
{
private const string DockerReplicaStore = "docker";
private static readonly TimeSpan DockerStopTimeout = TimeSpan.FromSeconds(30);
private readonly ILogger _logger;
private readonly ReplicaRegistry _replicaRegistry;
private readonly DockerRunnerOptions _options;
public DockerRunner(ILogger logger, ReplicaRegistry replicaRegistry, DockerRunnerOptions options)
{
_logger = logger;
_replicaRegistry = replicaRegistry;
_options = options;
}
public async Task StartAsync(Application application)
{
await PurgeFromPreviousRun(application);
var containers = new List<Service>();
foreach (var s in application.Services)
{
if (s.Value.Description.RunInfo is DockerRunInfo)
{
containers.Add(s.Value);
}
}
if (containers.Count == 0)
{
return;
}
var proxies = new List<Service>();
foreach (var service in application.Services.Values)
{
if (service.Description.RunInfo is DockerRunInfo ||
service.Description.RunInfo is IngressRunInfo ||
service.Description.Bindings.Count == 0)
{
continue;
}
// Inject a proxy per non-container service. This allows the container to use normal host names within the
// container network to talk to services on the host
var proxyContainer = new DockerRunInfo($"mcr.microsoft.com/dotnet/sdk:6.0", "dotnet Microsoft.Tye.Proxy.dll")
{
WorkingDirectory = "/app",
NetworkAlias = service.Description.Name,
Private = true,
IsProxy = true
};
var proxyLocation = Path.GetDirectoryName(typeof(Microsoft.Tye.Proxy.Program).Assembly.Location);
proxyContainer.VolumeMappings.Add(new DockerVolume(proxyLocation, name: null, target: "/app"));
var proxyDescription = new ServiceDescription($"{service.Description.Name}-proxy", proxyContainer);
foreach (var binding in service.Description.Bindings)
{
if (binding.Port == null)
{
continue;
}
if (string.Equals(binding.Protocol, "udp", StringComparison.InvariantCultureIgnoreCase))
{
throw new CommandException("Proxy does not support the udp protocol yet.");
}
var b = new ServiceBinding()
{
ConnectionString = binding.ConnectionString,
Host = binding.Host,
ContainerPort = binding.ContainerPort,
Name = binding.Name,
Port = binding.Port,
Protocol = binding.Protocol
};
b.ReplicaPorts.Add(b.Port.Value);
b.Routes.AddRange(binding.Routes);
proxyDescription.Bindings.Add(b);
}
var proxyContainerService = new Service(proxyDescription, ServiceSource.Host);
containers.Add(proxyContainerService);
proxies.Add(proxyContainerService);
}
string? dockerNetwork = null;
if (!string.IsNullOrEmpty(application.Network))
{
var dockerNetworkResult = await application.ContainerEngine.RunAsync($"network ls --filter \"name={application.Network}\" --format \"{{{{.ID}}}}\"", throwOnError: false);
if (dockerNetworkResult.ExitCode != 0)
{
_logger.LogError("{Network}: Run docker network ls command failed", application.Network);
throw new CommandException("Run docker network ls command failed");
}
if (!string.IsNullOrWhiteSpace(dockerNetworkResult.StandardOutput))
{
_logger.LogInformation("The specified network {Network} exists", application.Network);
dockerNetwork = application.Network;
}
else
{
_logger.LogWarning("The specified network {Network} doesn't exist.", application.Network);
application.Network = null;
}
}
// We're going to be making containers, only make a network if we have more than one (we assume they'll need to talk)
if (string.IsNullOrEmpty(dockerNetwork) && containers.Count > 1)
{
dockerNetwork = "tye_network_" + Guid.NewGuid().ToString().Substring(0, 10);
application.Items["dockerNetwork"] = dockerNetwork;
_logger.LogInformation("Creating docker network {Network}", dockerNetwork);
var command = $"network create --driver bridge {dockerNetwork}";
_logger.LogInformation("Running docker command {Command}", command);
var dockerNetworkResult = await application.ContainerEngine.RunAsync(command, throwOnError: false);
if (dockerNetworkResult.ExitCode != 0)
{
_logger.LogInformation("Running docker command with exception info {ExceptionStdOut} {ExceptionStdErr}", dockerNetworkResult.StandardOutput, dockerNetworkResult.StandardError);
throw new CommandException("Run docker network create command failed");
}
}
// Stash information outside of the application services
application.Items[typeof(DockerApplicationInformation)] = new DockerApplicationInformation(dockerNetwork, proxies);
foreach (var s in containers)
{
var docker = (DockerRunInfo)s.Description.RunInfo!;
StartContainerAsync(application, s, docker, dockerNetwork);
}
}
public async Task StopAsync(Application application)
{
if (!application.Items.TryGetValue(typeof(DockerApplicationInformation), out var value))
{
return;
}
var info = (DockerApplicationInformation)value;
var services = application.Services;
var index = 0;
var tasks = new Task[services.Count + info.Proxies.Count];
foreach (var s in services.Values)
{
tasks[index++] = StopContainerAsync(s);
}
foreach (var s in info.Proxies)
{
tasks[index++] = StopContainerAsync(s);
}
await Task.WhenAll(tasks);
if (string.IsNullOrEmpty(application.Network) && !string.IsNullOrEmpty(info.DockerNetwork))
{
_logger.LogInformation("Removing docker network {Network}", info.DockerNetwork);
var command = $"network rm {info.DockerNetwork}";
_logger.LogInformation("Running docker command {Command}", command);
// Clean up the network we created
await application.ContainerEngine.RunAsync(command, throwOnError: false);
}
}
private void StartContainerAsync(Application application, Service service, DockerRunInfo docker, string? dockerNetwork)
{
var serviceDescription = service.Description;
var workingDirectory = docker.WorkingDirectory != null ? $"-w \"{docker.WorkingDirectory}\"" : "";
var hostname = application.ContainerEngine.ContainerHost;
if (hostname == null)
{
_logger.LogWarning("Configuration doesn't allow containers to access services on the host.");
// Set a value even though it won't be usable.
hostname = "host.docker.internal";
}
var dockerImage = docker.Image ?? service.Description.Name;
async Task RunDockerContainer(IEnumerable<(int ExternalPort, int Port, int? ContainerPort, string? Protocol, string? Host)> ports, CancellationToken cancellationToken)
{
var hasPorts = ports.Any();
var replica = service.Description.Name.ToLower() + "_" + Guid.NewGuid().ToString().Substring(0, 10).ToLower();
var status = new DockerStatus(service, replica);
service.Replicas[replica] = status;
service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Added, status));
var environment = new Dictionary<string, string>();
var portString = "";
if (hasPorts)
{
status.Ports = ports.Select(p => p.Port);
status.Bindings = ports.Select(p => new ReplicaBinding() { Port = p.Port, ExternalPort = p.ExternalPort, Protocol = p.Protocol }).ToList();
// These are the ports that the application should use for binding
// 1. Tell the docker container what port to bind to
portString = docker.Private ? "" : string.Join(" ", ports.Select(p => $"-p {(!string.IsNullOrWhiteSpace(p.Host) ? $"{p.Host}:" : string.Empty)}{p.Port}:{p.ContainerPort ?? p.Port}{(string.Equals(p.Protocol, "udp", StringComparison.OrdinalIgnoreCase) ? "/udp" : string.Empty)}"));
if (docker.IsAspNet)
{
// 2. Configure ASP.NET Core to bind to those same ports
var urlPorts = ports.Where(p => p.Protocol == null || p.Protocol == "http" || p.Protocol == "https");
environment["ASPNETCORE_URLS"] = string.Join(";", urlPorts.Select(p => $"{p.Protocol ?? "http"}://*:{p.ContainerPort ?? p.Port}"));
// Set the HTTPS port for the redirect middleware
foreach (var p in ports)
{
if (string.Equals(p.Protocol, "https", StringComparison.OrdinalIgnoreCase))
{
// We need to set the redirect URL to the exposed port so the redirect works cleanly
environment["HTTPS_PORT"] = p.ExternalPort.ToString();
}
}
}
// 3. For non-ASP.NET Core apps, pass the same information in the PORT env variable as a semicolon separated list.
environment["PORT"] = string.Join(";", ports.Select(p => $"{p.ContainerPort ?? p.Port}"));
// This the port for the container proxy (containerport:externalport)
environment["PROXY_PORT"] = string.Join(";", ports.Select(p => $"{p.ContainerPort ?? p.Port}:{p.ExternalPort}"));
}
// See: https://github.com/docker/for-linux/issues/264
//
// The way we do proxying here doesn't really work for multi-container scenarios on linux
// without some more setup.
application.PopulateEnvironment(service, (key, value) => environment[key] = value, hostname!);
environment["APP_INSTANCE"] = replica;
environment["CONTAINER_HOST"] = hostname!;
status.Environment = environment;
var environmentArguments = "";
foreach (var pair in environment)
{
environmentArguments += $"-e \"{pair.Key}={pair.Value}\" ";
}
var volumes = "";
foreach (var volumeMapping in docker.VolumeMappings)
{
if (volumeMapping.Source != null)
{
var sourcePath = Path.GetFullPath(Path.Combine(application.ContextDirectory, volumeMapping.Source));
if (application.ContainerEngine.IsPodman)
{
// unlike docker, podman doesn't create the host directory when it doesn't exist.
// https://github.com/containers/podman/issues/10471
if (!File.Exists(sourcePath) && !Directory.Exists(sourcePath))
{
Directory.CreateDirectory(sourcePath);
}
}
volumes += $"-v \"{sourcePath}:{volumeMapping.Target}:{(volumeMapping.ReadOnly ? "ro," : "")}z\" ";
}
else if (volumeMapping.Name != null)
{
volumes += $"-v \"{volumeMapping.Name}:{volumeMapping.Target}\" ";
}
}
var command = $"run -d {workingDirectory} {volumes} {environmentArguments} {portString} --name {replica} --restart=unless-stopped";
if (!string.IsNullOrEmpty(dockerNetwork))
{
status.DockerNetworkAlias = docker.NetworkAlias ?? serviceDescription!.Name;
command += $" --network {dockerNetwork} --network-alias {status.DockerNetworkAlias}";
}
command += $" {dockerImage} {docker.Args ?? ""}";
if (!docker.IsProxy)
{
_logger.LogInformation("Running image {Image} for {Replica}", docker.Image, replica);
}
else
{
_logger.LogDebug("Running proxy image {Image} for {Replica}", docker.Image, replica);
}
service.Logs.OnNext($"[{replica}]: docker {command}");
status.DockerCommand = command;
status.DockerNetwork = dockerNetwork;
WriteReplicaToStore(replica);
var stderr = new StringBuilder();
var result = await application.ContainerEngine.RunAsync(
command,
throwOnError: false,
cancellationToken: cancellationToken,
outputDataReceived: data => service.Logs.OnNext($"[{replica}]: {data}"),
errorDataReceived: data => { service.Logs.OnNext($"[{replica}]: {data}"); stderr.AppendLine(data); });
if (result.ExitCode != 0)
{
_logger.LogError("docker run failed for {ServiceName} with exit code {ExitCode}: " + stderr, service.Description.Name, result.ExitCode);
service.Replicas.TryRemove(replica, out var _);
service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status));
PrintStdOutAndErr(service, replica, result);
return;
}
var containerId = (string?)result.StandardOutput.Trim();
// There's a race condition that sometimes makes us miss the output
// so keep trying to get the container id
while (string.IsNullOrEmpty(containerId))
{
// Try to get the ID of the container
result = await application.ContainerEngine.RunAsync($"ps --no-trunc -f name={replica} --format " + "{{.ID}}");
containerId = result.ExitCode == 0 ? result.StandardOutput.Trim() : null;
}
var shortContainerId = containerId.Substring(0, Math.Min(12, containerId.Length));
status.ContainerId = shortContainerId;
_logger.LogInformation("Running container {ContainerName} with ID {ContainerId}", replica, shortContainerId);
var sentStartedEvent = false;
while (!cancellationToken.IsCancellationRequested)
{
if (sentStartedEvent)
{
using var restartCts = new CancellationTokenSource(DockerStopTimeout);
result = await application.ContainerEngine.RunAsync($"restart {containerId}", throwOnError: false, cancellationToken: restartCts.Token);
if (restartCts.IsCancellationRequested)
{
_logger.LogWarning($"Failed to restart container after {DockerStopTimeout.Seconds} seconds.", replica, shortContainerId);
break; // implement retry mechanism?
}
else if (result.ExitCode != 0)
{
_logger.LogWarning($"Failed to restart container due to exit code {result.ExitCode}.", replica, shortContainerId);
break;
}
service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status));
}
using var stoppingCts = new CancellationTokenSource();
status.StoppingTokenSource = stoppingCts;
service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Started, status));
sentStartedEvent = true;
await using var _ = cancellationToken.Register(() => status.StoppingTokenSource.Cancel());
_logger.LogInformation("Collecting docker logs for {ContainerName}.", replica);
var backOff = TimeSpan.FromSeconds(5);
while (!status.StoppingTokenSource.Token.IsCancellationRequested)
{
var logsRes = await application.ContainerEngine.RunAsync($"logs -f {containerId}",
outputDataReceived: data => service.Logs.OnNext($"[{replica}]: {data}"),
errorDataReceived: data => service.Logs.OnNext($"[{replica}]: {data}"),
throwOnError: false,
cancellationToken: status.StoppingTokenSource.Token);
if (logsRes.ExitCode != 0)
{
break;
}
if (!status.StoppingTokenSource.IsCancellationRequested)
{
try
{
// Avoid spamming logs if restarts are happening
await Task.Delay(backOff, status.StoppingTokenSource.Token);
}
catch (OperationCanceledException)
{
break;
}
}
backOff *= 2;
}
_logger.LogInformation("docker logs collection for {ContainerName} complete with exit code {ExitCode}", replica, result.ExitCode);
status.StoppingTokenSource = null;
}
// Docker has a tendency to get stuck so we're going to timeout this shutdown process
var timeoutCts = new CancellationTokenSource(DockerStopTimeout);
_logger.LogInformation("Stopping container {ContainerName} with ID {ContainerId}", replica, shortContainerId);
result = await application.ContainerEngine.RunAsync($"stop {containerId}", throwOnError: false, cancellationToken: timeoutCts.Token);
if (timeoutCts.IsCancellationRequested)
{
_logger.LogWarning($"Failed to stop container after {DockerStopTimeout.Seconds} seconds, container will most likely be running.", replica, shortContainerId);
}
PrintStdOutAndErr(service, replica, result);
if (sentStartedEvent)
{
service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status));
}
_logger.LogInformation("Stopped container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode);
result = await application.ContainerEngine.RunAsync($"rm {containerId}", throwOnError: false, cancellationToken: timeoutCts.Token);
if (timeoutCts.IsCancellationRequested)
{
_logger.LogWarning($"Failed to remove container after {DockerStopTimeout.Seconds} seconds, container will most likely still exist.", replica, shortContainerId);
}
PrintStdOutAndErr(service, replica, result);
_logger.LogInformation("Removed container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode);
service.Replicas.TryRemove(replica, out var _);
service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status));
};
async Task DockerBuildAsync(CancellationToken cancellationToken)
{
if (docker.DockerFile != null)
{
_logger.LogInformation("Building docker image {Image} from docker file", dockerImage);
void Log(string data)
{
_logger.LogInformation("[" + serviceDescription!.Name + "]:" + data);
service.Logs.OnNext(data);
}
var arguments = new StringBuilder($"build \"{docker.DockerFileContext?.FullName}\" -t {dockerImage} -f \"{docker.DockerFile}\"");
foreach (var buildArg in docker.BuildArgs)
{
arguments.Append($" --build-arg {buildArg.Key}={buildArg.Value}");
}
var dockerBuildResult = await application.ContainerEngine.RunAsync(
arguments.ToString(),
outputDataReceived: Log,
errorDataReceived: Log,
workingDirectory: docker.WorkingDirectory,
cancellationToken: cancellationToken,
throwOnError: false);
if (dockerBuildResult.ExitCode != 0)
{
throw new CommandException("'docker build' failed.");
}
}
}
Task DockerRunAsync(CancellationToken cancellationToken)
{
var tasks = new Task[serviceDescription!.Replicas];
if (serviceDescription.Bindings.Count > 0)
{
// Each replica is assigned a list of internal ports, one mapped to each external
// port
for (var i = 0; i < serviceDescription.Replicas; i++)
{
var ports = new List<(int, int, int?, string?, string?)>();
foreach (var binding in serviceDescription.Bindings)
{
if (binding.Port == null)
{
continue;
}
ports.Add((binding.Port.Value, binding.ReplicaPorts[i], binding.ContainerPort, binding.Protocol, binding.Host));
}
tasks[i] = RunDockerContainer(ports, cancellationToken);
}
}
else
{
for (var i = 0; i < service.Description.Replicas; i++)
{
tasks[i] = RunDockerContainer(Enumerable.Empty<(int, int, int?, string?, string?)>(), cancellationToken);
}
}
return Task.WhenAll(tasks);
}
var dockerInfo = new DockerInformation();
async Task BuildAndRunAsync(CancellationToken cancellationToken)
{
await DockerBuildAsync(cancellationToken);
await DockerRunAsync(cancellationToken);
}
dockerInfo.SetBuildAndRunTask(BuildAndRunAsync);
if (!_options.ManualStartServices &&
!(_options.ServicesNotToStart?.Contains(service.Description.Name, StringComparer.OrdinalIgnoreCase) ?? false))
{
dockerInfo.BuildAndRun();
}
service.Items[typeof(DockerInformation)] = dockerInfo;
}
private async Task PurgeFromPreviousRun(Application application)
{
var dockerReplicas = await _replicaRegistry.GetEvents(DockerReplicaStore);
foreach (var replica in dockerReplicas)
{
var container = replica["container"];
await application.ContainerEngine.RunAsync($"rm -f {container}", throwOnError: false);
_logger.LogInformation("removed container {container} from previous run", container);
}
_replicaRegistry.DeleteStore(DockerReplicaStore);
}
private void WriteReplicaToStore(string container)
{
_replicaRegistry.WriteReplicaEvent(DockerReplicaStore, new Dictionary<string, string>()
{
["container"] = container
});
}
private static void PrintStdOutAndErr(Service service, string replica, ProcessResult result)
{
if (result.ExitCode != 0)
{
if (result.StandardOutput != null)
{
service.Logs.OnNext($"[{replica}]: {result.StandardOutput}");
}
if (result.StandardError != null)
{
service.Logs.OnNext($"[{replica}]: {result.StandardError}");
}
}
}
public static async Task RestartContainerAsync(Service service)
{
if (service.Items.TryGetValue(typeof(DockerInformation), out var value) && value is DockerInformation di)
{
await StopContainerAsync(service);
di.BuildAndRun();
service.Restarts++;
await di.Task;
}
}
public static Task StopContainerAsync(Service service)
{
if (service.Items.TryGetValue(typeof(DockerInformation), out var value) && value is DockerInformation di)
{
di.CancelAndResetStoppingTokenSource();
return di.Task ?? Task.CompletedTask;
}
return Task.CompletedTask;
}
private class DockerInformation
{
private Func<CancellationToken, Task>? _buildAndRunAsync;
public Task Task { get; private set; } = default!;
public CancellationTokenSource StoppingTokenSource { get; private set; } = new CancellationTokenSource();
public void SetBuildAndRunTask(Func<CancellationToken, Task> func)
{
_buildAndRunAsync = func;
}
public void BuildAndRun()
{
Task = _buildAndRunAsync?.Invoke(StoppingTokenSource.Token) ?? Task.CompletedTask;
}
internal void CancelAndResetStoppingTokenSource()
{
StoppingTokenSource.Cancel();
StoppingTokenSource.Dispose();
StoppingTokenSource = new CancellationTokenSource();
}
}
private class DockerApplicationInformation
{
public DockerApplicationInformation(string? dockerNetwork, List<Service> proxies)
{
DockerNetwork = dockerNetwork;
Proxies = proxies;
}
public string? DockerNetwork { get; set; }
public List<Service> Proxies { get; }
}
}
}