|
| 1 | +// -------------------------------------------------------------------------------------------- |
| 2 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +// Licensed under the MIT license. |
| 4 | +// -------------------------------------------------------------------------------------------- |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Formats.Tar; |
| 8 | +using System.IO; |
| 9 | +using System.IO.Compression; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.Extensions.Logging; |
| 12 | +using Microsoft.Extensions.Options; |
| 13 | +using Microsoft.Oryx.BuildScriptGenerator.Common; |
| 14 | + |
| 15 | +namespace Microsoft.Oryx.BuildScriptGenerator |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// Fetches SDK tarballs directly from an OCI container registry. |
| 19 | + /// SDK images are single-layer <c>FROM scratch</c> images containing a single |
| 20 | + /// <c>.tar.gz</c> SDK file. The OCI layer blob is a tar archive of the image |
| 21 | + /// filesystem, so this provider downloads the layer, extracts the inner SDK |
| 22 | + /// tarball from it, and caches it locally. |
| 23 | + /// </summary> |
| 24 | + /// <remarks> |
| 25 | + /// Makes direct HTTP calls to the registry (no Unix socket). |
| 26 | + /// See <see cref="ExternalAcrSdkProvider"/> for the socket-based variant. |
| 27 | + /// </remarks> |
| 28 | + public class AcrSdkProvider : IAcrSdkProvider |
| 29 | + { |
| 30 | + private readonly ILogger<AcrSdkProvider> logger; |
| 31 | + private readonly IStandardOutputWriter outputWriter; |
| 32 | + private readonly BuildScriptGeneratorOptions options; |
| 33 | + private readonly OciRegistryClient ociClient; |
| 34 | + |
| 35 | + public AcrSdkProvider( |
| 36 | + IStandardOutputWriter outputWriter, |
| 37 | + ILogger<AcrSdkProvider> logger, |
| 38 | + IOptions<BuildScriptGeneratorOptions> options, |
| 39 | + OciRegistryClient ociClient) |
| 40 | + { |
| 41 | + this.logger = logger; |
| 42 | + this.outputWriter = outputWriter; |
| 43 | + this.options = options.Value; |
| 44 | + this.ociClient = ociClient; |
| 45 | + } |
| 46 | + |
| 47 | + /// <inheritdoc/> |
| 48 | + public async Task<bool> RequestSdkFromAcrAsync(string platformName, string version, string debianFlavor, string runtimeVersion = null) |
| 49 | + { |
| 50 | + if (string.IsNullOrEmpty(platformName)) |
| 51 | + { |
| 52 | + throw new ArgumentException("Platform name cannot be null or empty.", nameof(platformName)); |
| 53 | + } |
| 54 | + |
| 55 | + if (string.IsNullOrEmpty(version)) |
| 56 | + { |
| 57 | + throw new ArgumentException("Version cannot be null or empty.", nameof(version)); |
| 58 | + } |
| 59 | + |
| 60 | + if (string.IsNullOrEmpty(debianFlavor)) |
| 61 | + { |
| 62 | + debianFlavor = this.options.DebianFlavor ?? "bookworm"; |
| 63 | + } |
| 64 | + |
| 65 | + var repository = SdkImageRepositoryHelper.GetSdkImageRepository(platformName, this.options.OryxAcrSdkRepositoryPrefix); |
| 66 | + var tag = string.IsNullOrEmpty(runtimeVersion) |
| 67 | + ? $"{debianFlavor}-{version}" |
| 68 | + : $"{debianFlavor}-{version}_{runtimeVersion}"; |
| 69 | + var blobName = $"{platformName}-{debianFlavor}-{version}.tar.gz"; |
| 70 | + |
| 71 | + this.logger.LogInformation( |
| 72 | + "Requesting SDK from ACR: {Repository}:{Tag}", |
| 73 | + repository, |
| 74 | + tag); |
| 75 | + this.outputWriter.WriteLine( |
| 76 | + $"Requesting SDK from ACR: {repository}:{tag}"); |
| 77 | + |
| 78 | + // Download to the writable dynamic install directory, NOT /var/OryxSdks (read-only external mount). |
| 79 | + var downloadDir = Path.Combine(this.options.DynamicInstallRootDir, platformName); |
| 80 | + var tarballPath = Path.Combine(downloadDir, blobName); |
| 81 | + var digestPath = Path.Combine(downloadDir, $".{blobName}.digest"); |
| 82 | + |
| 83 | + try |
| 84 | + { |
| 85 | + // Get image manifest |
| 86 | + var remoteDigest = await this.ociClient.GetManifestDigestAsync(repository, tag); |
| 87 | + |
| 88 | + // Check if cached tarball is still fresh |
| 89 | + if (File.Exists(tarballPath) && File.Exists(digestPath) && remoteDigest != null) |
| 90 | + { |
| 91 | + var localDigest = File.ReadAllText(digestPath).Trim(); |
| 92 | + if (string.Equals(localDigest, remoteDigest, StringComparison.OrdinalIgnoreCase)) |
| 93 | + { |
| 94 | + this.logger.LogInformation( |
| 95 | + "SDK cache is fresh (digest match): {FilePath}", |
| 96 | + tarballPath); |
| 97 | + this.outputWriter.WriteLine( |
| 98 | + $"SDK tarball already cached and fresh at {tarballPath}"); |
| 99 | + return true; |
| 100 | + } |
| 101 | + |
| 102 | + this.logger.LogInformation( |
| 103 | + "SDK cache is stale (digest mismatch). Re-downloading."); |
| 104 | + } |
| 105 | + |
| 106 | + // Get manifest → extract single layer digest |
| 107 | + var manifest = await this.ociClient.GetManifestAsync(repository, tag); |
| 108 | + var layerDigest = OciRegistryClient.GetFirstLayerDigest(manifest); |
| 109 | + |
| 110 | + if (string.IsNullOrEmpty(layerDigest)) |
| 111 | + { |
| 112 | + this.logger.LogWarning( |
| 113 | + "No layer found in manifest for {Repository}:{Tag}", |
| 114 | + repository, |
| 115 | + tag); |
| 116 | + this.outputWriter.WriteLine($"No layer found in ACR manifest for {platformName} {version}."); |
| 117 | + return false; |
| 118 | + } |
| 119 | + |
| 120 | + Directory.CreateDirectory(downloadDir); |
| 121 | + |
| 122 | + // 2. Download the OCI layer blob to a temp file. |
| 123 | + // The layer is a tar archive of the image filesystem (not the SDK tarball itself). |
| 124 | + var layerTempPath = Path.Combine(downloadDir, $".layer-{Guid.NewGuid():N}.tmp"); |
| 125 | + try |
| 126 | + { |
| 127 | + var downloadSuccess = await this.ociClient.DownloadLayerBlobAsync( |
| 128 | + repository, |
| 129 | + layerDigest, |
| 130 | + layerTempPath); |
| 131 | + |
| 132 | + if (!downloadSuccess) |
| 133 | + { |
| 134 | + this.logger.LogWarning( |
| 135 | + "ACR SDK pull failed digest verification: {Repository}:{Tag}", |
| 136 | + repository, |
| 137 | + tag); |
| 138 | + this.outputWriter.WriteLine( |
| 139 | + $"Failed to pull SDK from ACR (digest mismatch): {platformName} {version}"); |
| 140 | + return false; |
| 141 | + } |
| 142 | + |
| 143 | + // 3. Extract the inner SDK .tar.gz from the layer tar. |
| 144 | + // The image is FROM scratch with a single COPY of the SDK tarball, |
| 145 | + // so the layer contains the .tar.gz as a top-level entry. |
| 146 | + this.ExtractFileFromTar(layerTempPath, tarballPath, blobName); |
| 147 | + } |
| 148 | + finally |
| 149 | + { |
| 150 | + // Always clean up the temporary layer file |
| 151 | + if (File.Exists(layerTempPath)) |
| 152 | + { |
| 153 | + File.Delete(layerTempPath); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + this.logger.LogInformation( |
| 158 | + "Successfully pulled SDK from ACR: {Repository}:{Tag} → {FilePath}", |
| 159 | + repository, |
| 160 | + tag, |
| 161 | + tarballPath); |
| 162 | + this.outputWriter.WriteLine( |
| 163 | + $"Successfully pulled SDK from ACR: {platformName} {version}"); |
| 164 | + |
| 165 | + // Write manifest digest sidecar for future freshness checks |
| 166 | + if (!string.IsNullOrEmpty(remoteDigest)) |
| 167 | + { |
| 168 | + File.WriteAllText(digestPath, remoteDigest); |
| 169 | + } |
| 170 | + |
| 171 | + return true; |
| 172 | + } |
| 173 | + catch (Exception ex) |
| 174 | + { |
| 175 | + this.logger.LogError( |
| 176 | + ex, |
| 177 | + "Error pulling SDK from ACR: {Repository}:{Tag}", |
| 178 | + repository, |
| 179 | + tag); |
| 180 | + this.outputWriter.WriteLine( |
| 181 | + $"Error pulling SDK from ACR: {platformName} {version}: {ex.Message}"); |
| 182 | + return false; |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + /// <summary> |
| 187 | + /// Extracts the expected SDK .tar.gz file from an OCI layer tar archive. |
| 188 | + /// OCI layers use media type "application/vnd.docker.image.rootfs.diff.tar.gzip", |
| 189 | + /// so the blob must be decompressed before reading tar entries. |
| 190 | + /// </summary> |
| 191 | + private void ExtractFileFromTar(string layerPath, string outputPath, string expectedFileName) |
| 192 | + { |
| 193 | + using (var stream = File.OpenRead(layerPath)) |
| 194 | + using (var gzipStream = new GZipStream(stream, CompressionMode.Decompress)) |
| 195 | + using (var tarReader = new TarReader(gzipStream)) |
| 196 | + { |
| 197 | + TarEntry entry; |
| 198 | + while ((entry = tarReader.GetNextEntry()) != null) |
| 199 | + { |
| 200 | + var name = entry.Name.TrimStart('.', '/'); |
| 201 | + if (entry.DataStream != null && name.Equals(expectedFileName, StringComparison.OrdinalIgnoreCase)) |
| 202 | + { |
| 203 | + entry.ExtractToFile(outputPath, overwrite: true); |
| 204 | + return; |
| 205 | + } |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + throw new InvalidOperationException($"Expected entry '{expectedFileName}' not found in OCI layer: {layerPath}"); |
| 210 | + } |
| 211 | + } |
| 212 | +} |
0 commit comments