Skip to content

Commit 4eb4f98

Browse files
HostObject Cleanup (#216)
* Don't disable nullable in shipping code * One exception per class * No need to override execute in the ToolTask * Add const for env var names * Capitalize consts * Modify containerhttpexception message * Remove warning when extracting host object * Don't recalculate the json contents * Remove extra HostObjectMagic function * Lower-pri 'host object not found' message
1 parent 2b6d21a commit 4eb4f98

File tree

7 files changed

+37
-47
lines changed

7 files changed

+37
-47
lines changed

Microsoft.NET.Build.Containers/AuthHandshakeMessageHandler.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ private record TokenResponse(string? token, string? access_token, int? expires_i
8888
private async Task<string> GetTokenAsync(Uri realm, string service, string scope, CancellationToken cancellationToken)
8989
{
9090
// Allow overrides for auth via environment variables
91-
string? credU = Environment.GetEnvironmentVariable("SDK_CONTAINER_REGISTRY_UNAME");
92-
string? credP = Environment.GetEnvironmentVariable("SDK_CONTAINER_REGISTRY_PWORD");
91+
string? credU = Environment.GetEnvironmentVariable(ContainerHelpers.HostObjectUser);
92+
string? credP = Environment.GetEnvironmentVariable(ContainerHelpers.HostObjectPass);
9393

9494
// fetch creds for the host
9595
DockerCredentials? privateRepoCreds;

Microsoft.NET.Build.Containers/ContainerHelpers.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ public record Port(int number, PortType type);
2020

2121
public static class ContainerHelpers
2222
{
23+
public const string HostObjectUser = "SDK_CONTAINER_REGISTRY_UNAME";
24+
25+
public const string HostObjectPass = "SDK_CONTAINER_REGISTRY_PWORD";
26+
2327
private static Regex envVarRegex = new Regex(@"^[a-zA-Z_]+$");
2428

2529
/// <summary>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
namespace Microsoft.NET.Build.Containers;
2+
public class ContainerHttpException : Exception
3+
{
4+
private const string ErrorPrefix = "Containerize: error CONTAINER004:";
5+
string? jsonResponse;
6+
string? uri;
7+
public ContainerHttpException(string message, string? targetUri, string? jsonResp)
8+
: base($"{ErrorPrefix} {message}\nURI: {targetUri ?? "Unknown"}\nJson Response: {jsonResp ?? "None."}")
9+
{
10+
jsonResponse = jsonResp;
11+
uri = targetUri;
12+
}
13+
}

Microsoft.NET.Build.Containers/CreateNewImageToolTask.cs

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -139,29 +139,8 @@ public CreateNewImage()
139139
GeneratedContainerManifest = "";
140140
}
141141

142-
private void HostObjectMagic()
143-
{
144-
VSHostObject hostObj = new VSHostObject(HostObject as System.Collections.Generic.IEnumerable<ITaskItem>);
145-
if (hostObj.ExtractCredentials(out string user, out string pass))
146-
{
147-
Log.LogWarning($"Host Object Retrieved.\nUser: {user}\nPass: {pass}");
148-
extractionInfo = (true, user, pass);
149-
}
150-
else
151-
{
152-
Log.LogWarning("Host object failed to extract");
153-
}
154-
155-
}
156-
157142
protected override string GenerateFullPathToTool() => Quote(Path.Combine(DotNetPath, ToolExe));
158143

159-
public override bool Execute()
160-
{
161-
HostObjectMagic();
162-
return base.Execute();
163-
}
164-
165144
/// <summary>
166145
/// Workaround to avoid storing user/pass into the EnvironmentVariables property, which gets logged by the task.
167146
/// </summary>
@@ -176,12 +155,22 @@ protected override ProcessStartInfo GetProcessStartInfo
176155
string responseFileSwitch
177156
)
178157
{
158+
VSHostObject hostObj = new VSHostObject(HostObject as System.Collections.Generic.IEnumerable<ITaskItem>);
159+
if (hostObj.ExtractCredentials(out string user, out string pass))
160+
{
161+
extractionInfo = (true, user, pass);
162+
}
163+
else
164+
{
165+
Log.LogMessage(MessageImportance.Low, "No host object detected.");
166+
}
167+
179168
ProcessStartInfo startInfo = base.GetProcessStartInfo(pathToTool, commandLineCommands, responseFileSwitch)!;
180169

181170
if (extractionInfo.success)
182171
{
183-
startInfo.Environment["SDK_CONTAINER_REGISTRY_UNAME"] = extractionInfo.user;
184-
startInfo.Environment["SDK_CONTAINER_REGISTRY_PWORD"] = extractionInfo.pass;
172+
startInfo.Environment[ContainerHelpers.HostObjectUser] = extractionInfo.user;
173+
startInfo.Environment[ContainerHelpers.HostObjectPass] = extractionInfo.pass;
185174
}
186175

187176
return startInfo;

Microsoft.NET.Build.Containers/Exceptions.cs renamed to Microsoft.NET.Build.Containers/DockerLoadException.cs

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,3 @@ protected DockerLoadException(SerializationInfo info, StreamingContext context)
2020
{
2121
}
2222
}
23-
24-
public class ContainerHttpException : Exception
25-
{
26-
private const string errorPrefix = "Containerize: error CONTAINER004:";
27-
string? jsonResponse;
28-
string? uri;
29-
public ContainerHttpException(string message, string? targetUri, string? jsonResp)
30-
: base($"{errorPrefix} {message}\nURI: {targetUri ?? "None."}\nJson Response: {jsonResp ?? "None."}" )
31-
{
32-
jsonResponse = jsonResp;
33-
uri = targetUri;
34-
}
35-
}

Microsoft.NET.Build.Containers/Registry.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -216,14 +216,14 @@ await Task.WhenAll(x.LayerDescriptors.Select(async descriptor => {
216216

217217
var manifestDigest = x.GetDigest(x.manifest);
218218
logProgressMessage($"Uploading manifest to registry at blob {manifestDigest}");
219-
HttpContent manifestUploadContent = new StringContent(x.manifest.ToJsonString());
219+
string jsonString = x.manifest.ToJsonString();
220+
HttpContent manifestUploadContent = new StringContent(jsonString);
220221
manifestUploadContent.Headers.ContentType = new MediaTypeHeaderValue(DockerManifestV2);
221222
var putResponse = await client.PutAsync(new Uri(BaseUri, $"/v2/{name}/manifests/{manifestDigest}"), manifestUploadContent);
222223

223224
if (!putResponse.IsSuccessStatusCode)
224225
{
225-
string jsonResponse = await putResponse.Content.ReadAsStringAsync();
226-
throw new ContainerHttpException("Registry push failed.", putResponse.RequestMessage?.RequestUri?.ToString(), jsonResponse);
226+
throw new ContainerHttpException("Registry push failed.", putResponse.RequestMessage?.RequestUri?.ToString(), jsonString);
227227
}
228228
logProgressMessage($"Uploaded manifest to registry");
229229

@@ -232,8 +232,7 @@ await Task.WhenAll(x.LayerDescriptors.Select(async descriptor => {
232232

233233
if (!putResponse2.IsSuccessStatusCode)
234234
{
235-
string jsonResponse = await putResponse2.Content.ReadAsStringAsync();
236-
throw new ContainerHttpException("Registry push failed.", putResponse2.RequestMessage?.RequestUri?.ToString(), jsonResponse);
235+
throw new ContainerHttpException("Registry push failed.", putResponse2.RequestMessage?.RequestUri?.ToString(), jsonString);
237236
}
238237

239238
logProgressMessage($"Uploaded tag to registry");

Microsoft.NET.Build.Containers/VSHostObject.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,16 @@
22
using System.Linq;
33
using Microsoft.Build.Framework;
44

5-
#nullable disable
6-
75
namespace Microsoft.NET.Build.Containers.Tasks;
86

97
internal class VSHostObject
108
{
119
private const string CredentialItemSpecName = "MsDeployCredential";
1210
private const string UserMetaDataName = "UserName";
1311
private const string PasswordMetaDataName = "Password";
14-
IEnumerable<ITaskItem> _hostObject;
12+
IEnumerable<ITaskItem>? _hostObject;
1513

16-
public VSHostObject(IEnumerable<ITaskItem> hostObject)
14+
public VSHostObject(IEnumerable<ITaskItem>? hostObject)
1715
{
1816
_hostObject = hostObject;
1917
}

0 commit comments

Comments
 (0)