-
Notifications
You must be signed in to change notification settings - Fork 962
/
DockerCommandManager.cs
447 lines (387 loc) · 20 KB
/
DockerCommandManager.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
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using GitHub.Runner.Common;
using GitHub.Runner.Sdk;
namespace GitHub.Runner.Worker.Container
{
[ServiceLocator(Default = typeof(DockerCommandManager))]
public interface IDockerCommandManager : IRunnerService
{
string DockerPath { get; }
string DockerInstanceLabel { get; }
Task<DockerVersion> DockerVersion(IExecutionContext context);
Task<int> DockerPull(IExecutionContext context, string image);
Task<int> DockerBuild(IExecutionContext context, string workingDirectory, string dockerFile, string dockerContext, string tag);
Task<string> DockerCreate(IExecutionContext context, ContainerInfo container);
Task<int> DockerRun(IExecutionContext context, ContainerInfo container, EventHandler<ProcessDataReceivedEventArgs> stdoutDataReceived, EventHandler<ProcessDataReceivedEventArgs> stderrDataReceived);
Task<int> DockerStart(IExecutionContext context, string containerId);
Task<int> DockerLogs(IExecutionContext context, string containerId);
Task<List<string>> DockerPS(IExecutionContext context, string options);
Task<int> DockerRemove(IExecutionContext context, string containerId);
Task<int> DockerNetworkCreate(IExecutionContext context, string network);
Task<int> DockerNetworkRemove(IExecutionContext context, string network);
Task<int> DockerNetworkPrune(IExecutionContext context);
Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command);
Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command, List<string> outputs);
Task<List<string>> DockerInspect(IExecutionContext context, string dockerObject, string options);
Task<List<PortMapping>> DockerPort(IExecutionContext context, string containerId);
}
public class DockerCommandManager : RunnerService, IDockerCommandManager
{
public string DockerPath { get; private set; }
public string DockerInstanceLabel { get; private set; }
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
DockerPath = WhichUtil.Which("docker", true, Trace);
DockerInstanceLabel = IOUtil.GetPathHash(hostContext.GetDirectory(WellKnownDirectory.Root)).Substring(0, 6);
}
public async Task<DockerVersion> DockerVersion(IExecutionContext context)
{
string serverVersionStr = (await ExecuteDockerCommandAsync(context, "version", "--format '{{.Server.APIVersion}}'")).FirstOrDefault();
ArgUtil.NotNullOrEmpty(serverVersionStr, "Docker.Server.Version");
context.Output($"Docker daemon API version: {serverVersionStr}");
string clientVersionStr = (await ExecuteDockerCommandAsync(context, "version", "--format '{{.Client.APIVersion}}'")).FirstOrDefault();
ArgUtil.NotNullOrEmpty(serverVersionStr, "Docker.Client.Version");
context.Output($"Docker client API version: {clientVersionStr}");
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
Version serverVersion = null;
var serverVersionMatchResult = verRegex.Match(serverVersionStr);
if (serverVersionMatchResult.Success && !string.IsNullOrEmpty(serverVersionMatchResult.Value))
{
if (!Version.TryParse(serverVersionMatchResult.Value, out serverVersion))
{
serverVersion = null;
}
}
Version clientVersion = null;
var clientVersionMatchResult = verRegex.Match(serverVersionStr);
if (clientVersionMatchResult.Success && !string.IsNullOrEmpty(clientVersionMatchResult.Value))
{
if (!Version.TryParse(clientVersionMatchResult.Value, out clientVersion))
{
clientVersion = null;
}
}
return new DockerVersion(serverVersion, clientVersion);
}
public async Task<int> DockerPull(IExecutionContext context, string image)
{
return await ExecuteDockerCommandAsync(context, "pull", image, context.CancellationToken);
}
public async Task<int> DockerBuild(IExecutionContext context, string workingDirectory, string dockerFile, string dockerContext, string tag)
{
return await ExecuteDockerCommandAsync(context, "build", $"-t {tag} -f \"{dockerFile}\" \"{dockerContext}\"", workingDirectory, context.CancellationToken);
}
public async Task<string> DockerCreate(IExecutionContext context, ContainerInfo container)
{
IList<string> dockerOptions = new List<string>();
// OPTIONS
dockerOptions.Add($"--name {container.ContainerDisplayName}");
dockerOptions.Add($"--label {DockerInstanceLabel}");
if (!string.IsNullOrEmpty(container.ContainerWorkDirectory))
{
dockerOptions.Add($"--workdir {container.ContainerWorkDirectory}");
}
if (!string.IsNullOrEmpty(container.ContainerNetwork))
{
dockerOptions.Add($"--network {container.ContainerNetwork}");
}
if (!string.IsNullOrEmpty(container.ContainerNetworkAlias))
{
dockerOptions.Add($"--network-alias {container.ContainerNetworkAlias}");
}
foreach (var port in container.UserPortMappings)
{
dockerOptions.Add($"-p {port.Value}");
}
dockerOptions.Add($"{container.ContainerCreateOptions}");
foreach (var env in container.ContainerEnvironmentVariables)
{
if (String.IsNullOrEmpty(env.Value))
{
dockerOptions.Add($"-e \"{env.Key}\"");
}
else
{
dockerOptions.Add($"-e \"{env.Key}={env.Value.Replace("\"", "\\\"")}\"");
}
}
// Watermark for GitHub Action environment
dockerOptions.Add("-e GITHUB_ACTIONS=true");
// Set CI=true when no one else already set it.
// CI=true is common set in most CI provider in GitHub
if (!container.ContainerEnvironmentVariables.ContainsKey("CI"))
{
dockerOptions.Add("-e CI=true");
}
foreach (var volume in container.MountVolumes)
{
// replace `"` with `\"` and add `"{0}"` to all path.
String volumeArg;
if (String.IsNullOrEmpty(volume.SourceVolumePath))
{
// Anonymous docker volume
volumeArg = $"-v \"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
}
else
{
// Named Docker volume / host bind mount
volumeArg = $"-v \"{volume.SourceVolumePath.Replace("\"", "\\\"")}\":\"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
}
if (volume.ReadOnly)
{
volumeArg += ":ro";
}
dockerOptions.Add(volumeArg);
}
if (!string.IsNullOrEmpty(container.ContainerEntryPoint))
{
dockerOptions.Add($"--entrypoint \"{container.ContainerEntryPoint}\"");
}
// IMAGE
dockerOptions.Add($"{container.ContainerImage}");
// COMMAND
// Intentionally blank. Always overwrite ENTRYPOINT and/or send ARGs
// [ARG...]
dockerOptions.Add($"{container.ContainerEntryPointArgs}");
var optionsString = string.Join(" ", dockerOptions);
List<string> outputStrings = await ExecuteDockerCommandAsync(context, "create", optionsString);
return outputStrings.FirstOrDefault();
}
public async Task<int> DockerRun(IExecutionContext context, ContainerInfo container, EventHandler<ProcessDataReceivedEventArgs> stdoutDataReceived, EventHandler<ProcessDataReceivedEventArgs> stderrDataReceived)
{
IList<string> dockerOptions = new List<string>();
// OPTIONS
dockerOptions.Add($"--name {container.ContainerDisplayName}");
dockerOptions.Add($"--label {DockerInstanceLabel}");
dockerOptions.Add($"--workdir {container.ContainerWorkDirectory}");
dockerOptions.Add($"--rm");
foreach (var env in container.ContainerEnvironmentVariables)
{
// e.g. -e MY_SECRET maps the value into the exec'ed process without exposing
// the value directly in the command
dockerOptions.Add($"-e {env.Key}");
}
// Watermark for GitHub Action environment
dockerOptions.Add("-e GITHUB_ACTIONS=true");
// Set CI=true when no one else already set it.
// CI=true is common set in most CI provider in GitHub
if (!container.ContainerEnvironmentVariables.ContainsKey("CI"))
{
dockerOptions.Add("-e CI=true");
}
if (!string.IsNullOrEmpty(container.ContainerEntryPoint))
{
dockerOptions.Add($"--entrypoint \"{container.ContainerEntryPoint}\"");
}
if (!string.IsNullOrEmpty(container.ContainerNetwork))
{
dockerOptions.Add($"--network {container.ContainerNetwork}");
}
foreach (var volume in container.MountVolumes)
{
// replace `"` with `\"` and add `"{0}"` to all path.
String volumeArg;
if (String.IsNullOrEmpty(volume.SourceVolumePath))
{
// Anonymous docker volume
volumeArg = $"-v \"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
}
else
{
// Named Docker volume / host bind mount
volumeArg = $"-v \"{volume.SourceVolumePath.Replace("\"", "\\\"")}\":\"{volume.TargetVolumePath.Replace("\"", "\\\"")}\"";
}
if (volume.ReadOnly)
{
volumeArg += ":ro";
}
dockerOptions.Add(volumeArg);
}
// IMAGE
dockerOptions.Add($"{container.ContainerImage}");
// COMMAND
// Intentionally blank. Always overwrite ENTRYPOINT and/or send ARGs
// [ARG...]
dockerOptions.Add($"{container.ContainerEntryPointArgs}");
var optionsString = string.Join(" ", dockerOptions);
return await ExecuteDockerCommandAsync(context, "run", optionsString, container.ContainerEnvironmentVariables, stdoutDataReceived, stderrDataReceived, context.CancellationToken);
}
public async Task<int> DockerStart(IExecutionContext context, string containerId)
{
return await ExecuteDockerCommandAsync(context, "start", containerId, context.CancellationToken);
}
public async Task<int> DockerRemove(IExecutionContext context, string containerId)
{
return await ExecuteDockerCommandAsync(context, "rm", $"--force {containerId}", context.CancellationToken);
}
public async Task<int> DockerLogs(IExecutionContext context, string containerId)
{
return await ExecuteDockerCommandAsync(context, "logs", $"--details {containerId}", context.CancellationToken);
}
public async Task<List<string>> DockerPS(IExecutionContext context, string options)
{
return await ExecuteDockerCommandAsync(context, "ps", options);
}
public async Task<int> DockerNetworkCreate(IExecutionContext context, string network)
{
#if OS_WINDOWS
return await ExecuteDockerCommandAsync(context, "network", $"create --label {DockerInstanceLabel} {network} --driver nat", context.CancellationToken);
#else
return await ExecuteDockerCommandAsync(context, "network", $"create --label {DockerInstanceLabel} {network}", context.CancellationToken);
#endif
}
public async Task<int> DockerNetworkRemove(IExecutionContext context, string network)
{
return await ExecuteDockerCommandAsync(context, "network", $"rm {network}", context.CancellationToken);
}
public async Task<int> DockerNetworkPrune(IExecutionContext context)
{
return await ExecuteDockerCommandAsync(context, "network", $"prune --force --filter \"label={DockerInstanceLabel}\"", context.CancellationToken);
}
public async Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command)
{
return await ExecuteDockerCommandAsync(context, "exec", $"{options} {containerId} {command}", context.CancellationToken);
}
public async Task<int> DockerExec(IExecutionContext context, string containerId, string options, string command, List<string> output)
{
ArgUtil.NotNull(output, nameof(output));
string arg = $"exec {options} {containerId} {command}".Trim();
context.Command($"{DockerPath} {arg}");
object outputLock = new object();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
lock (outputLock)
{
output.Add(message.Data);
}
}
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
lock (outputLock)
{
output.Add(message.Data);
}
}
};
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
return await processInvoker.ExecuteAsync(
workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Work),
fileName: DockerPath,
arguments: arg,
environment: null,
requireExitCodeZero: false,
outputEncoding: null,
cancellationToken: CancellationToken.None);
}
public async Task<List<string>> DockerInspect(IExecutionContext context, string dockerObject, string options)
{
return await ExecuteDockerCommandAsync(context, "inspect", $"{options} {dockerObject}");
}
public async Task<List<PortMapping>> DockerPort(IExecutionContext context, string containerId)
{
List<string> portMappingLines = await ExecuteDockerCommandAsync(context, "port", containerId);
return DockerUtil.ParseDockerPort(portMappingLines);
}
private Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, CancellationToken cancellationToken = default(CancellationToken))
{
return ExecuteDockerCommandAsync(context, command, options, null, cancellationToken);
}
private async Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, IDictionary<string, string> environment, EventHandler<ProcessDataReceivedEventArgs> stdoutDataReceived, EventHandler<ProcessDataReceivedEventArgs> stderrDataReceived, CancellationToken cancellationToken = default(CancellationToken))
{
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += stdoutDataReceived;
processInvoker.ErrorDataReceived += stderrDataReceived;
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
return await processInvoker.ExecuteAsync(
workingDirectory: context.GetGitHubContext("workspace"),
fileName: DockerPath,
arguments: arg,
environment: environment,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
cancellationToken: cancellationToken);
}
private async Task<int> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options, string workingDirectory, CancellationToken cancellationToken = default(CancellationToken))
{
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
return await processInvoker.ExecuteAsync(
workingDirectory: workingDirectory ?? context.GetGitHubContext("workspace"),
fileName: DockerPath,
arguments: arg,
environment: null,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
redirectStandardIn: null,
cancellationToken: cancellationToken);
}
private async Task<List<string>> ExecuteDockerCommandAsync(IExecutionContext context, string command, string options)
{
string arg = $"{command} {options}".Trim();
context.Command($"{DockerPath} {arg}");
List<string> output = new List<string>();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
output.Add(message.Data);
context.Output(message.Data);
}
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
if (!string.IsNullOrEmpty(message.Data))
{
context.Output(message.Data);
}
};
await processInvoker.ExecuteAsync(
workingDirectory: context.GetGitHubContext("workspace"),
fileName: DockerPath,
arguments: arg,
environment: null,
requireExitCodeZero: true,
outputEncoding: null,
cancellationToken: CancellationToken.None);
return output;
}
}
}