Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Labels to the Image config #120

Merged
merged 4 commits into from
Aug 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Microsoft.NET.Build.Containers/CreateNewImage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ public class CreateNewImage : Microsoft.Build.Utilities.Task
/// </summary>
public ITaskItem[] EntrypointArgs { get; set; }

/// <summary>
/// Labels that the image configuration will include in metadata
/// </summary>
public ITaskItem[] Labels { get; set; }

public CreateNewImage()
{
BaseRegistry = "";
Expand All @@ -78,6 +83,7 @@ public CreateNewImage()
WorkingDirectory = "";
Entrypoint = Array.Empty<ITaskItem>();
EntrypointArgs = Array.Empty<ITaskItem>();
Labels = Array.Empty<ITaskItem>();
}


Expand Down Expand Up @@ -112,6 +118,11 @@ public override bool Execute()
image.WorkingDirectory = WorkingDirectory;
image.SetEntrypoint(Entrypoint.Select(i => i.ItemSpec).ToArray(), EntrypointArgs.Select(i => i.ItemSpec).ToArray());

foreach (var label in Labels)
{
image.Label(label.ItemSpec, label.GetMetadata("Value"));
}

if (OutputRegistry.StartsWith("docker://"))
{
try
Expand Down
55 changes: 51 additions & 4 deletions Microsoft.NET.Build.Containers/Image.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

namespace Microsoft.NET.Build.Containers;

record Label(string name, string value);

public class Image
{
public JsonNode manifest;
Expand All @@ -15,12 +17,16 @@ public class Image

internal List<Layer> newLayers = new();

private HashSet<Label> labels;

public Image(JsonNode manifest, JsonNode config, string name, Registry? registry)
{
this.manifest = manifest;
this.config = config;
this.OriginatingName = name;
this.originatingRegistry = registry;
// labels are inherited from the parent image, so we need to seed our new image with them.
this.labels = ReadLabelsFromConfig(config);
}

public IEnumerable<Descriptor> LayerDescriptors
Expand Down Expand Up @@ -61,7 +67,39 @@ private void RecalculateDigest()
manifest["config"]!["digest"] = GetDigest(config);
}

static JsonArray ToJsonArray(string[] items) => new JsonArray(items.Where(s => !string.IsNullOrEmpty(s)).Select(s =>(JsonValue) s).ToArray());
private static HashSet<Label> ReadLabelsFromConfig(JsonNode inputConfig)
{
if (inputConfig is JsonObject config && config["Labels"] is JsonObject labelsJson)
{
// read label mappings from object
var labels = new HashSet<Label>();
foreach (var property in labelsJson)
{
if (property.Key is { } propertyName && property.Value is JsonValue propertyValue)
{
labels.Add(new(propertyName, propertyValue.ToString()));
}
}
return labels;
}
else
{
// initialize and empty labels map
return new HashSet<Label>();
}
}

private JsonObject CreateLabelMap()
{
var container = new JsonObject();
foreach (var label in labels)
{
container.Add(label.name, label.value);
}
return container;
}

static JsonArray ToJsonArray(string[] items) => new JsonArray(items.Where(s => !string.IsNullOrEmpty(s)).Select(s => (JsonValue)s).ToArray());

public void SetEntrypoint(string[] executableArgs, string[]? args = null)
{
Expand All @@ -86,14 +124,23 @@ public void SetEntrypoint(string[] executableArgs, string[]? args = null)
RecalculateDigest();
}

public string WorkingDirectory {
get => (string?)manifest["config"]!["WorkingDir"] ?? "";
set {
public string WorkingDirectory
{
get => (string?)config["config"]!["WorkingDir"] ?? "";
set
{
config["config"]!["WorkingDir"] = value;
RecalculateDigest();
}
}

public void Label(string name, string value)
{
labels.Add(new(name, value));
config["config"]!["Labels"] = CreateLabelMap();
RecalculateDigest();
}

public string GetDigest(JsonNode json)
{
string hashString;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,20 @@
<ContainerWorkingDirectory Condition="'$(ContainerWorkingDirectory)' == ''">/app</ContainerWorkingDirectory>
<!-- Could be semicolon-delimited -->
</PropertyGroup>

<ItemGroup>
<ContainerLabel Condition="@(ContainerLabel) == ''"></ContainerLabel>

<ItemGroup Label="Entrypoint Assignment">
<!-- For non-apphosts, we need to invoke `dotnet` `workingdir/app` as separate args -->
<ContainerEntrypoint Condition="'$(ContainerEntrypoint)' == '' and '$(UseAppHost)' != 'true'" Include="dotnet;$(ContainerWorkingDirectory)/$(TargetFileName)" />
<!-- For apphosts, we need to invoke `workingdir/app` as a single arg -->
<ContainerEntrypoint Condition="'$(ContainerEntrypoint)' == '' and '$(UseAppHost)' == 'true'" Include="$(ContainerWorkingDirectory)/$(AssemblyName)$(_NativeExecutableExtension)" />
</ItemGroup>

<ItemGroup Label="Conventional Label assignment">
<ContainerLabel Include="org.opencontainers.image.created" Value="$([System.DateTime]::UtcNow.ToString('o'))" />
</ItemGroup>

<!-- Asp.NET defaults -->
<ItemGroup Condition="'$(_IsAspNet)' == 'true'">
<ItemGroup Label="ASP.NET port forwarding" Condition="'$(_IsAspNet)' == 'true'">
<ContainerPort Include="80" Type="tcp" Condition="@(ContainerPort->WithMetadataValue('Identity', '80')->AnyHaveMetadataValue('Type', 'tcp')) == ''" />

<ContainerEnvironmentVariable Include="ASPNETCORE_URLS" Value="http://localhost:5000;https://localhost:5001"
Expand Down Expand Up @@ -72,6 +75,7 @@
PublishDirectory="$(PublishDir)"
WorkingDirectory="$(ContainerWorkingDirectory)"
Entrypoint="@(ContainerEntrypoint)"
EntrypointArgs="@(ContainerEntrypointArgs)"/>
EntrypointArgs="@(ContainerEntrypointArgs)"
Labels="@(ContainerLabel)"/>
</Target>
</Project>