|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the MIT License. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.IO; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Azure; |
| 8 | +using Azure.Storage.Blobs; |
| 9 | +using Microsoft.Azure.WebJobs.Script.Properties; |
| 10 | +using Microsoft.Extensions.Logging; |
| 11 | +using Newtonsoft.Json; |
| 12 | +using IApplicationLifetime = Microsoft.AspNetCore.Hosting.IApplicationLifetime; |
| 13 | + |
| 14 | +namespace Microsoft.Azure.WebJobs.Script |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// Used to perform Host ID validation checks, ensuring that when hosts are sharing |
| 18 | + /// a storage account, their computed IDs don't collide. |
| 19 | + /// </summary> |
| 20 | + /// <remarks> |
| 21 | + /// <see cref="ScriptHostIdProvider"/> computes a Host ID and truncates it if needed to |
| 22 | + /// ensure it's under length limits. For two different Function Apps, this can result in |
| 23 | + /// both apps resolving to the same Host ID. This can cause problems if those apps share |
| 24 | + /// a storage account. This class helps detect/prevent such cases. |
| 25 | + /// </remarks> |
| 26 | + public class HostIdValidator |
| 27 | + { |
| 28 | + public const string BlobPathFormat = "ids/usage/{0}"; |
| 29 | + private const LogLevel DefaultLevel = LogLevel.Warning; |
| 30 | + |
| 31 | + private readonly IEnvironment _environment; |
| 32 | + private readonly IAzureStorageProvider _storageProvider; |
| 33 | + private readonly IApplicationLifetime _applicationLifetime; |
| 34 | + private readonly HostNameProvider _hostNameProvider; |
| 35 | + private readonly ILogger _logger; |
| 36 | + |
| 37 | + private readonly object _syncLock = new object(); |
| 38 | + private bool _validationScheduled; |
| 39 | + |
| 40 | + public HostIdValidator(IEnvironment environment, IAzureStorageProvider storageProvider, IApplicationLifetime applicationLifetime, |
| 41 | + HostNameProvider hostNameProvider, ILogger<HostIdValidator> logger) |
| 42 | + { |
| 43 | + _environment = environment; |
| 44 | + _storageProvider = storageProvider; |
| 45 | + _applicationLifetime = applicationLifetime; |
| 46 | + _hostNameProvider = hostNameProvider; |
| 47 | + _logger = logger; |
| 48 | + } |
| 49 | + |
| 50 | + internal bool ValidationScheduled => _validationScheduled; |
| 51 | + |
| 52 | + public virtual void ScheduleValidation(string hostId) |
| 53 | + { |
| 54 | + lock (_syncLock) |
| 55 | + { |
| 56 | + if (!_validationScheduled) |
| 57 | + { |
| 58 | + // Schedule the validation to run asynchronously after a delay. This delay ensures |
| 59 | + // we're not impacting coldstart. |
| 60 | + Utility.ExecuteAfterColdStartDelay(_environment, () => Task.Run(() => ValidateHostIdUsageAsync(hostId))); |
| 61 | + _validationScheduled = true; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + internal async Task ValidateHostIdUsageAsync(string hostId) |
| 67 | + { |
| 68 | + try |
| 69 | + { |
| 70 | + if (!_storageProvider.ConnectionExists(ConnectionStringNames.Storage)) |
| 71 | + { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + HostIdInfo hostIdInfo = await ReadHostIdInfoAsync(hostId); |
| 76 | + |
| 77 | + if (hostIdInfo != null) |
| 78 | + { |
| 79 | + // an existing record exists for this host ID |
| 80 | + CheckForCollision(hostId, hostIdInfo); |
| 81 | + } |
| 82 | + else |
| 83 | + { |
| 84 | + // no existing record, so write one, claiming this host ID for this host name |
| 85 | + // in this storage account |
| 86 | + hostIdInfo = new HostIdInfo |
| 87 | + { |
| 88 | + Hostname = _hostNameProvider.Value |
| 89 | + }; |
| 90 | + await WriteHostIdAsync(hostId, hostIdInfo); |
| 91 | + } |
| 92 | + } |
| 93 | + catch (Exception ex) |
| 94 | + { |
| 95 | + // best effort - log error and continue |
| 96 | + _logger.LogError(ex, "Error validating host ID usage."); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + private void CheckForCollision(string hostId, HostIdInfo hostIdInfo) |
| 101 | + { |
| 102 | + // verify the host name is the same as our host name |
| 103 | + if (!string.Equals(_hostNameProvider.Value, hostIdInfo.Hostname, StringComparison.OrdinalIgnoreCase)) |
| 104 | + { |
| 105 | + HandleCollision(hostId); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + private void HandleCollision(string hostId) |
| 110 | + { |
| 111 | + // see if the user has specified a level, otherwise default |
| 112 | + string value = _environment.GetEnvironmentVariable(EnvironmentSettingNames.FunctionsHostIdCheckLevel); |
| 113 | + if (!Enum.TryParse<LogLevel>(value, out LogLevel level)) |
| 114 | + { |
| 115 | + level = DefaultLevel; |
| 116 | + } |
| 117 | + |
| 118 | + string message = string.Format(Resources.HostIdCollisionFormat, hostId); |
| 119 | + if (level == LogLevel.Error) |
| 120 | + { |
| 121 | + _logger.LogError(message); |
| 122 | + _applicationLifetime.StopApplication(); |
| 123 | + } |
| 124 | + else |
| 125 | + { |
| 126 | + // we only allow Warning/Error levels to be specified, so anything other than |
| 127 | + // Error is treated as warning |
| 128 | + _logger.LogWarning(message); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + internal async Task WriteHostIdAsync(string hostId, HostIdInfo hostIdInfo) |
| 133 | + { |
| 134 | + try |
| 135 | + { |
| 136 | + var containerClient = _storageProvider.GetBlobContainerClient(); |
| 137 | + string blobPath = string.Format(BlobPathFormat, hostId); |
| 138 | + BlobClient blobClient = containerClient.GetBlobClient(blobPath); |
| 139 | + BinaryData data = BinaryData.FromObjectAsJson(hostIdInfo); |
| 140 | + await blobClient.UploadAsync(data); |
| 141 | + |
| 142 | + _logger.LogDebug($"Host ID record written (ID:{hostId}, HostName:{hostIdInfo.Hostname})"); |
| 143 | + } |
| 144 | + catch (RequestFailedException rfex) when (rfex.Status == 409) |
| 145 | + { |
| 146 | + // Another instance wrote the blob between the time when we initially |
| 147 | + // checked and when we attempted to write. Read the blob and validate it. |
| 148 | + hostIdInfo = await ReadHostIdInfoAsync(hostId); |
| 149 | + if (hostIdInfo != null) |
| 150 | + { |
| 151 | + CheckForCollision(hostId, hostIdInfo); |
| 152 | + } |
| 153 | + } |
| 154 | + catch (Exception ex) |
| 155 | + { |
| 156 | + // best effort |
| 157 | + _logger.LogError(ex, "Error writing host ID info"); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + internal async Task<HostIdInfo> ReadHostIdInfoAsync(string hostId) |
| 162 | + { |
| 163 | + HostIdInfo hostIdInfo = null; |
| 164 | + |
| 165 | + try |
| 166 | + { |
| 167 | + // check storage to see if a record already exists for this host ID |
| 168 | + var containerClient = _storageProvider.GetBlobContainerClient(); |
| 169 | + string blobPath = string.Format(BlobPathFormat, hostId); |
| 170 | + BlobClient blobClient = containerClient.GetBlobClient(blobPath); |
| 171 | + var downloadResponse = await blobClient.DownloadAsync(); |
| 172 | + string content; |
| 173 | + using (StreamReader reader = new StreamReader(downloadResponse.Value.Content)) |
| 174 | + { |
| 175 | + content = reader.ReadToEnd(); |
| 176 | + } |
| 177 | + |
| 178 | + if (!string.IsNullOrEmpty(content)) |
| 179 | + { |
| 180 | + hostIdInfo = JsonConvert.DeserializeObject<HostIdInfo>(content); |
| 181 | + } |
| 182 | + } |
| 183 | + catch (RequestFailedException exception) when (exception.Status == 404) |
| 184 | + { |
| 185 | + // no record stored for this host ID |
| 186 | + } |
| 187 | + catch (Exception ex) |
| 188 | + { |
| 189 | + // best effort |
| 190 | + _logger.LogError(ex, "Error reading host ID info"); |
| 191 | + } |
| 192 | + |
| 193 | + return hostIdInfo; |
| 194 | + } |
| 195 | + |
| 196 | + internal class HostIdInfo |
| 197 | + { |
| 198 | + public string Hostname { get; set; } |
| 199 | + } |
| 200 | + } |
| 201 | +} |
0 commit comments