-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
TestcontainersContainer.cs
406 lines (344 loc) · 10.9 KB
/
TestcontainersContainer.cs
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
namespace DotNet.Testcontainers.Containers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using DotNet.Testcontainers.Clients;
using DotNet.Testcontainers.Configurations;
using DotNet.Testcontainers.Images;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
/// <inheritdoc cref="ITestcontainersContainer" />
public class TestcontainersContainer : ITestcontainersContainer
{
private const TestcontainersStates ContainerHasBeenCreatedStates = TestcontainersStates.Created | TestcontainersStates.Running | TestcontainersStates.Exited;
private readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
private readonly ITestcontainersClient client;
private readonly ITestcontainersConfiguration configuration;
private int disposed;
[NotNull]
private ContainerInspectResponse container = new ContainerInspectResponse();
/// <summary>
/// Initializes a new instance of the <see cref="TestcontainersContainer" /> class.
/// </summary>
/// <param name="configuration">The Testcontainers configuration.</param>
/// <param name="logger">The logger.</param>
protected TestcontainersContainer(ITestcontainersConfiguration configuration, ILogger logger)
{
this.client = new TestcontainersClient(configuration.SessionId, configuration.DockerEndpointAuthConfig, logger);
this.configuration = configuration;
this.Logger = logger;
}
/// <inheritdoc />
public string Id
{
get
{
this.ThrowIfContainerHasNotBeenCreated();
return this.container.ID;
}
}
/// <inheritdoc />
public string Name
{
get
{
this.ThrowIfContainerHasNotBeenCreated();
return this.container.Name;
}
}
/// <inheritdoc />
public string IpAddress
{
get
{
this.ThrowIfContainerHasNotBeenCreated();
return this.container.NetworkSettings.Networks.First().Value.IPAddress;
}
}
/// <inheritdoc />
public string MacAddress
{
get
{
this.ThrowIfContainerHasNotBeenCreated();
return this.container.NetworkSettings.Networks.First().Value.MacAddress;
}
}
/// <inheritdoc />
public string Hostname
{
get
{
var dockerHostUri = this.configuration.DockerEndpointAuthConfig.Endpoint;
switch (dockerHostUri.Scheme)
{
case "http":
case "https":
case "tcp":
return dockerHostUri.Host;
case "npipe":
case "unix":
return this.GetContainerGateway();
default:
throw new InvalidOperationException($"Docker endpoint {dockerHostUri} is not supported.");
}
}
}
/// <inheritdoc />
public IDockerImage Image
{
get
{
return this.configuration.Image;
}
}
/// <inheritdoc />
public TestcontainersStates State
{
get
{
if (this.container.State == null)
{
return TestcontainersStates.Undefined;
}
try
{
return (TestcontainersStates)Enum.Parse(typeof(TestcontainersStates), this.container.State.Status, true);
}
catch (Exception)
{
return TestcontainersStates.Undefined;
}
}
}
/// <summary>
/// Gets the logger.
/// </summary>
[NotNull]
internal ILogger Logger { get; }
/// <inheritdoc />
public ushort GetMappedPublicPort(int privatePort)
{
return this.GetMappedPublicPort(Convert.ToString(privatePort, CultureInfo.InvariantCulture));
}
/// <inheritdoc />
public ushort GetMappedPublicPort(string privatePort)
{
this.ThrowIfContainerHasNotBeenCreated();
if (this.container.NetworkSettings.Ports.TryGetValue($"{privatePort}/tcp", out var portMap) && ushort.TryParse(portMap.First().HostPort, out var publicPort))
{
return publicPort;
}
else
{
throw new InvalidOperationException($"Exposed port {privatePort} is not mapped.");
}
}
/// <inheritdoc />
public Task<long> GetExitCode(CancellationToken ct = default)
{
return this.client.GetContainerExitCode(this.Id, ct);
}
/// <inheritdoc />
public Task<(string Stdout, string Stderr)> GetLogs(DateTime since = default, DateTime until = default, CancellationToken ct = default)
{
return this.client.GetContainerLogs(this.Id, since, until, ct);
}
/// <inheritdoc />
public virtual async Task StartAsync(CancellationToken ct = default)
{
await this.semaphoreSlim.WaitAsync(ct)
.ConfigureAwait(false);
try
{
this.container = await this.Create(ct)
.ConfigureAwait(false);
this.container = await this.Start(this.Id, ct)
.ConfigureAwait(false);
}
finally
{
this.semaphoreSlim.Release();
}
}
/// <inheritdoc />
public virtual async Task StopAsync(CancellationToken ct = default)
{
await this.semaphoreSlim.WaitAsync(ct)
.ConfigureAwait(false);
try
{
this.container = await this.Stop(this.Id, ct)
.ConfigureAwait(false);
}
catch (DockerContainerNotFoundException)
{
this.container = new ContainerInspectResponse();
}
finally
{
this.semaphoreSlim.Release();
}
}
/// <inheritdoc />
public Task CopyFileAsync(string filePath, byte[] fileContent, int accessMode = 384, int userId = 0, int groupId = 0, CancellationToken ct = default)
{
return this.client.CopyFileAsync(this.Id, filePath, fileContent, accessMode, userId, groupId, ct);
}
/// <inheritdoc />
public Task<byte[]> ReadFileAsync(string filePath, CancellationToken ct = default)
{
return this.client.ReadFileAsync(this.Id, filePath, ct);
}
/// <inheritdoc />
public Task<ExecResult> ExecAsync(IList<string> command, CancellationToken ct = default)
{
return this.client.ExecAsync(this.Id, command, ct);
}
/// <summary>
/// Removes the Testcontainers.
/// </summary>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that represents the asynchronous clean up operation of a Testcontainers.</returns>
public async Task CleanUpAsync(CancellationToken ct = default)
{
await this.semaphoreSlim.WaitAsync(ct)
.ConfigureAwait(false);
try
{
this.container = await this.CleanUp(this.Id, ct)
.ConfigureAwait(false);
}
finally
{
this.semaphoreSlim.Release();
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
await this.DisposeAsyncCore()
.ConfigureAwait(false);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases any resources associated with the instance of <see cref="TestcontainersContainer" />.
/// </summary>
/// <returns>Value task that completes when any resources associated with the instance have been released.</returns>
protected virtual async ValueTask DisposeAsyncCore()
{
if (1.Equals(Interlocked.CompareExchange(ref this.disposed, 1, 0)))
{
return;
}
if (!ContainerHasBeenCreatedStates.HasFlag(this.State))
{
return;
}
// If someone calls `DisposeAsync`, we can immediately remove the container. We do not need to wait for the Resource Reaper.
if (Guid.Empty.Equals(this.configuration.SessionId))
{
await this.StopAsync()
.ConfigureAwait(false);
}
else
{
await this.CleanUpAsync()
.ConfigureAwait(false);
}
this.semaphoreSlim.Dispose();
}
private async Task<ContainerInspectResponse> Create(CancellationToken ct = default)
{
if (ContainerHasBeenCreatedStates.HasFlag(this.State))
{
return this.container;
}
var id = await this.client.RunAsync(this.configuration, ct)
.ConfigureAwait(false);
return await this.client.InspectContainer(id, ct)
.ConfigureAwait(false);
}
private async Task<ContainerInspectResponse> Start(string id, CancellationToken ct = default)
{
await this.client.AttachAsync(id, this.configuration.OutputConsumer, ct)
.ConfigureAwait(false);
await this.client.StartAsync(id, ct)
.ConfigureAwait(false);
this.container = await this.client.InspectContainer(id, ct)
.ConfigureAwait(false);
await this.configuration.StartupCallback(this, ct)
.ConfigureAwait(false);
// Do not use a too small frequency. Especially with a lot of containers,
// we send many operations to the Docker endpoint. The endpoint may cancel operations.
var frequency = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;
const int timeout = -1;
foreach (var waitStrategy in this.configuration.WaitStrategies)
{
await WaitStrategy.WaitUntil(
async () =>
{
this.container = await this.client.InspectContainer(id, ct)
.ConfigureAwait(false);
return await waitStrategy.Until(this, this.Logger)
.ConfigureAwait(false);
},
frequency,
timeout,
ct)
.ConfigureAwait(false);
}
return this.container;
}
private async Task<ContainerInspectResponse> Stop(string id, CancellationToken ct = default)
{
await this.client.StopAsync(id, ct)
.ConfigureAwait(false);
return await this.client.InspectContainer(id, ct)
.ConfigureAwait(false);
}
private async Task<ContainerInspectResponse> CleanUp(string id, CancellationToken ct = default)
{
await this.client.RemoveAsync(id, ct)
.ConfigureAwait(false);
return new ContainerInspectResponse();
}
private void ThrowIfContainerHasNotBeenCreated()
{
if (ContainerHasBeenCreatedStates.HasFlag(this.State))
{
return;
}
throw new InvalidOperationException("Testcontainers has not been created.");
}
private string GetContainerGateway()
{
const string localhost = "localhost";
if (!ContainerHasBeenCreatedStates.HasFlag(this.State))
{
return localhost;
}
if (!this.client.IsRunningInsideDocker)
{
return localhost;
}
var endpointSettings = this.container.NetworkSettings.Networks.TryGetValue("bridge", out var network) ? network : new EndpointSettings();
if (!string.IsNullOrWhiteSpace(endpointSettings.Gateway))
{
return endpointSettings.Gateway;
}
var networkSettings = this.container.NetworkSettings;
if (!string.IsNullOrWhiteSpace(networkSettings.Gateway))
{
return networkSettings.Gateway;
}
return localhost;
}
}
}