forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageBuilder.cs
336 lines (294 loc) · 14.1 KB
/
ImageBuilder.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using Microsoft.NET.Build.Containers.Resources;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
using System.Text.Json;
namespace Microsoft.NET.Build.Containers;
/// <summary>
/// The class builds new image based on the base image.
/// </summary>
internal sealed class ImageBuilder
{
// a snapshot of the manifest that this builder is based on
private readonly ManifestV2 _baseImageManifest;
// the mutable internal manifest that we're building by modifying the base and applying customizations
private readonly ManifestV2 _manifest;
private readonly string _manifestMediaType;
private readonly ImageConfig _baseImageConfig;
private readonly ILogger _logger;
/// <summary>
/// This is a parser for ASPNETCORE_URLS based on https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http/src/BindingAddress.cs
/// We can cut corners a bit here because we really only care about ports, if they exist.
/// </summary>
internal static Regex aspnetPortRegex = new(@"(?<scheme>\w+)://(?<domain>([*+]|).+):(?<port>\d+)");
public ImageConfig BaseImageConfig => _baseImageConfig;
/// <summary>
/// MediaType of the output manifest.
/// </summary>
public string ManifestMediaType => _manifestMediaType; // output the same media type as the base image manifest.
internal ImageBuilder(ManifestV2 manifest, string manifestMediaType, ImageConfig baseImageConfig, ILogger logger)
{
_baseImageManifest = manifest;
_manifest = new ManifestV2() { SchemaVersion = manifest.SchemaVersion, Config = manifest.Config, Layers = new(manifest.Layers), MediaType = manifest.MediaType };
_manifestMediaType = manifestMediaType;
_baseImageConfig = baseImageConfig;
_logger = logger;
}
/// <summary>
/// Gets a value indicating whether the base image is has a Windows operating system.
/// </summary>
public bool IsWindows => _baseImageConfig.IsWindows;
// For tests
internal string ManifestConfigDigest => _manifest.Config.digest;
/// <summary>
/// Builds the image configuration <see cref="BuiltImage"/> ready for further processing.
/// </summary>
internal BuiltImage Build()
{
// before we build, we need to make sure that any image customizations occur
AssignUserFromEnvironment();
AssignPortsFromEnvironment();
string imageJsonStr = _baseImageConfig.BuildConfig();
string imageSha = DigestUtils.GetSha(imageJsonStr);
string imageDigest = DigestUtils.GetDigestFromSha(imageSha);
long imageSize = Encoding.UTF8.GetBytes(imageJsonStr).Length;
ManifestConfig newManifestConfig = _manifest.Config with
{
digest = imageDigest,
size = imageSize
};
ManifestV2 newManifest = new ManifestV2()
{
Config = newManifestConfig,
SchemaVersion = _manifest.SchemaVersion,
MediaType = _manifest.MediaType,
Layers = _manifest.Layers
};
return new BuiltImage()
{
Config = imageJsonStr,
ImageDigest = imageDigest,
ImageSha = imageSha,
Manifest = JsonSerializer.SerializeToNode(newManifest)?.ToJsonString() ?? "",
ManifestDigest = newManifest.GetDigest(),
ManifestMediaType = ManifestMediaType,
Layers = _manifest.Layers
};
}
/// <summary>
/// Adds a <see cref="Layer"/> to a base image.
/// </summary>
internal void AddLayer(Layer l)
{
_manifest.Layers.Add(new(l.Descriptor.MediaType, l.Descriptor.Size, l.Descriptor.Digest, l.Descriptor.Urls));
_baseImageConfig.AddLayer(l);
}
internal void AddBaseImageDigestLabel()
{
AddLabel("org.opencontainers.image.base.digest", _baseImageManifest.GetDigest());
}
/// <summary>
/// Adds a label to a base image.
/// </summary>
internal void AddLabel(string name, string value) => _baseImageConfig.AddLabel(name, value);
/// <summary>
/// Adds environment variables to a base image.
/// </summary>
internal void AddEnvironmentVariable(string envVarName, string value) => _baseImageConfig.AddEnvironmentVariable(envVarName, value);
/// <summary>
/// Exposes additional port.
/// </summary>
internal void ExposePort(int number, PortType type) => _baseImageConfig.ExposePort(number, type);
/// <summary>
/// Sets working directory for the image.
/// </summary>
internal void SetWorkingDirectory(string workingDirectory) => _baseImageConfig.SetWorkingDirectory(workingDirectory);
/// <summary>
/// Sets the ENTRYPOINT and CMD for the image.
/// </summary>
internal void SetEntrypointAndCmd(string[] entrypoint, string[] cmd) => _baseImageConfig.SetEntrypointAndCmd(entrypoint, cmd);
/// <summary>
/// Sets the USER for the image.
/// </summary>
internal void SetUser(string user, bool isExplicitUserInteraction = true) => _baseImageConfig.SetUser(user, isExplicitUserInteraction);
internal static (string[] entrypoint, string[] cmd) DetermineEntrypointAndCmd(
string[] entrypoint,
string[] entrypointArgs,
string[] cmd,
string[] appCommand,
string[] appCommandArgs,
string appCommandInstruction,
string[]? baseImageEntrypoint,
Action<string> logWarning,
Action<string, string?> logError)
{
bool setsEntrypoint = entrypoint.Length > 0 || entrypointArgs.Length > 0;
bool setsCmd = cmd.Length > 0;
baseImageEntrypoint ??= Array.Empty<string>();
// Some (Microsoft) base images set 'dotnet' as the ENTRYPOINT. We mustn't use it.
if (baseImageEntrypoint.Length == 1 && (baseImageEntrypoint[0] == "dotnet" || baseImageEntrypoint[0] == "/usr/bin/dotnet"))
{
baseImageEntrypoint = Array.Empty<string>();
}
if (string.IsNullOrEmpty(appCommandInstruction))
{
if (setsEntrypoint)
{
// Backwards-compatibility: before 'AppCommand'/'Cmd' was added, only 'Entrypoint' was available.
if (!setsCmd && appCommandArgs.Length == 0 && entrypoint.Length == 0)
{
// Copy over the values for starting the application from AppCommand.
entrypoint = appCommand;
appCommand = Array.Empty<string>();
// Use EntrypointArgs as cmd.
cmd = entrypointArgs;
entrypointArgs = Array.Empty<string>();
if (entrypointArgs.Length > 0)
{
// Log warning: Instead of ContainerEntrypointArgs, use ContainerAppCommandArgs for arguments that must always be set, or ContainerDefaultArgs for default arguments that the user override when creating the container.
logWarning(nameof(Strings.EntrypointArgsSetPreferAppCommandArgs));
}
appCommandInstruction = KnownAppCommandInstructions.None;
}
else
{
// There's an Entrypoint. Use DefaultArgs for the AppCommand.
appCommandInstruction = KnownAppCommandInstructions.DefaultArgs;
}
}
else
{
// Default to use an Entrypoint.
// If the base image defines an ENTRYPOINT, print a warning.
if (baseImageEntrypoint.Length > 0)
{
logWarning(nameof(Strings.BaseEntrypointOverwritten));
}
appCommandInstruction = KnownAppCommandInstructions.Entrypoint;
}
}
if (entrypointArgs.Length > 0 && entrypoint.Length == 0)
{
logError(nameof(Strings.EntrypointArgsSetNoEntrypoint), null);
return (Array.Empty<string>(), Array.Empty<string>());
}
if (appCommandArgs.Length > 0 && appCommand.Length == 0)
{
logError(nameof(Strings.AppCommandArgsSetNoAppCommand), null);
return (Array.Empty<string>(), Array.Empty<string>());
}
switch (appCommandInstruction)
{
case KnownAppCommandInstructions.None:
if (appCommand.Length > 0 || appCommandArgs.Length > 0)
{
logError(nameof(Strings.AppCommandSetNotUsed), appCommandInstruction);
return (Array.Empty<string>(), Array.Empty<string>());
}
break;
case KnownAppCommandInstructions.DefaultArgs:
cmd = appCommand.Concat(appCommandArgs).Concat(cmd).ToArray();
break;
case KnownAppCommandInstructions.Entrypoint:
if (setsEntrypoint)
{
logError(nameof(Strings.EntrypointConflictAppCommand), appCommandInstruction);
return (Array.Empty<string>(), Array.Empty<string>());
}
entrypoint = appCommand;
entrypointArgs = appCommandArgs;
break;
default:
throw new NotSupportedException(
Resource.FormatString(
nameof(Strings.UnknownAppCommandInstruction),
appCommandInstruction,
string.Join(",", KnownAppCommandInstructions.SupportedAppCommandInstructions)));
}
return (entrypoint.Length > 0 ? entrypoint.Concat(entrypointArgs).ToArray() : baseImageEntrypoint, cmd);
}
/// <summary>
/// The APP_UID environment variable is a convention used to set the user in a data-driven manner. we should respect it if it's present.
/// </summary>
internal void AssignUserFromEnvironment()
{
// it's a common convention to apply custom users with the APP_UID convention - we check and apply that here
if (_baseImageConfig.EnvironmentVariables.TryGetValue(EnvironmentVariables.APP_UID, out string? appUid))
{
_logger.LogTrace("Setting user from APP_UID environment variable");
SetUser(appUid, isExplicitUserInteraction: false);
}
}
/// <summary>
/// ASP.NET can have urls/ports set via three environment variables - if we see any of them we should create ExposedPorts for them
/// to ensure tooling can automatically create port mappings.
/// </summary>
internal void AssignPortsFromEnvironment()
{
// asp.net images control port bindings via three environment variables. we should check for those variables and ensure that ports are created for them.
// precendence is captured at https://github.com/dotnet/aspnetcore/blob/f49c1c7f7467c184ffb630086afac447772096c6/src/Hosting/Hosting/src/GenericHost/GenericWebHostService.cs#L68-L119
// ASPNETCORE_URLS is the most specific and is the only one used if present, followed by ASPNETCORE_HTTPS_PORT and ASPNETCORE_HTTP_PORT together
// https://learn.microsoft.com//aspnet/core/fundamentals/host/web-host?view=aspnetcore-8.0#server-urls - the format of ASPNETCORE_URLS has been stable for many years now
if (_baseImageConfig.EnvironmentVariables.TryGetValue(EnvironmentVariables.ASPNETCORE_URLS, out string? urls))
{
foreach (var url in Split(urls))
{
_logger.LogTrace("Setting ports from ASPNETCORE_URLS environment variable");
var match = aspnetPortRegex.Match(url);
if (match.Success && int.TryParse(match.Groups["port"].Value, out int port))
{
_logger.LogTrace("Added port {port}", port);
ExposePort(port, PortType.tcp);
}
}
return; // we're done here - ASPNETCORE_URLS is the most specific and overrides the other two
}
// port-specific
// https://learn.microsoft.com/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-8.0#specify-ports-only - new for .NET 8 - allows just changing port(s) easily
if (_baseImageConfig.EnvironmentVariables.TryGetValue(EnvironmentVariables.ASPNETCORE_HTTP_PORTS, out string? httpPorts))
{
_logger.LogTrace("Setting ports from ASPNETCORE_HTTP_PORTS environment variable");
foreach (var port in Split(httpPorts))
{
if (int.TryParse(port, out int parsedPort))
{
_logger.LogTrace("Added port {port}", parsedPort);
ExposePort(parsedPort, PortType.tcp);
}
else
{
_logger.LogTrace("Skipped port {port} because it could not be parsed as an integer", port);
}
}
}
if (_baseImageConfig.EnvironmentVariables.TryGetValue(EnvironmentVariables.ASPNETCORE_HTTPS_PORTS, out string? httpsPorts))
{
_logger.LogTrace("Setting ports from ASPNETCORE_HTTPS_PORTS environment variable");
foreach (var port in Split(httpsPorts))
{
if (int.TryParse(port, out int parsedPort))
{
_logger.LogTrace("Added port {port}", parsedPort);
ExposePort(parsedPort, PortType.tcp);
}
else
{
_logger.LogTrace("Skipped port {port} because it could not be parsed as an integer", port);
}
}
}
static string[] Split(string input)
{
return input.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
}
}
internal static class EnvironmentVariables
{
public static readonly string APP_UID = nameof(APP_UID);
public static readonly string ASPNETCORE_URLS = nameof(ASPNETCORE_URLS);
public static readonly string ASPNETCORE_HTTP_PORTS = nameof(ASPNETCORE_HTTP_PORTS);
public static readonly string ASPNETCORE_HTTPS_PORTS = nameof(ASPNETCORE_HTTPS_PORTS);
}
}