|
2 | 2 | // SPDX-License-Identifier: Apache-2.0 |
3 | 3 |
|
4 | 4 | #if NETFRAMEWORK |
| 5 | +using System.Text; |
| 6 | +using System.Xml; |
| 7 | +using System.Xml.Linq; |
| 8 | +using OpenTelemetry.AutoInstrumentation.Logging; |
| 9 | + |
5 | 10 | namespace OpenTelemetry.AutoInstrumentation.Loader; |
6 | 11 |
|
7 | 12 | /// <summary> |
8 | 13 | /// Handles update of config files for non-default AppDomain |
9 | 14 | /// </summary> |
10 | 15 | internal static class AppConfigUpdater |
11 | 16 | { |
| 17 | + private static readonly IOtelLogger Logger = EnvironmentHelper.Logger; |
| 18 | + |
| 19 | + private enum PatchMode |
| 20 | + { |
| 21 | + LoaderOptimizationSingleDomain, |
| 22 | + AssemblyRedirect, |
| 23 | + None |
| 24 | + } |
| 25 | + |
12 | 26 | /// <summary> |
13 | | - /// Modify assembly bindings in appDomainSetup. |
14 | | - /// Will be called through reflection when new <see cref="System.AppDomain"/> created. |
15 | | - /// Call done using bytecode modifications for <see cref="AppDomain.CreateDomain(string,System.Security.Policy.Evidence,System.AppDomainSetup)"/> |
16 | | - /// and <see cref="AppDomainManager.CreateDomainHelper(string,System.Security.Policy.Evidence,System.AppDomainSetup)"/>. |
| 27 | + /// Modify assembly bindings in appDomainSetup |
17 | 28 | /// </summary> |
18 | 29 | /// <param name="appDomainSetup">appDomainSetup to be updated</param> |
19 | 30 | public static void ModifyConfig(AppDomainSetup appDomainSetup) |
20 | 31 | { |
21 | | - appDomainSetup.LoaderOptimization = LoaderOptimization.SingleDomain; |
| 32 | + var patchMode = Environment.GetEnvironmentVariable("OTEL_APP_DOMAIN_STRATEGY") ?? string.Empty; |
| 33 | + if (!Enum.TryParse<PatchMode>(patchMode, ignoreCase: true, out var mode)) |
| 34 | + { |
| 35 | + mode = PatchMode.LoaderOptimizationSingleDomain; |
| 36 | + } |
| 37 | + |
| 38 | + Logger.Debug($"Use {mode} strategy for multiple app domains"); |
| 39 | + |
| 40 | + switch (mode) |
| 41 | + { |
| 42 | + case PatchMode.LoaderOptimizationSingleDomain: |
| 43 | + appDomainSetup.LoaderOptimization = LoaderOptimization.SingleDomain; |
| 44 | + break; |
| 45 | + case PatchMode.AssemblyRedirect: |
| 46 | + ModifyAssemblyRedirectConfig(appDomainSetup); |
| 47 | + break; |
| 48 | + case PatchMode.None: |
| 49 | + break; |
| 50 | + default: |
| 51 | + throw new InvalidOperationException(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// Modify assembly bindings in appDomainSetup |
| 57 | + /// </summary> |
| 58 | + /// <param name="appDomainSetup">appDomainSetup to be updated</param> |
| 59 | + private static void ModifyAssemblyRedirectConfig(AppDomainSetup appDomainSetup) |
| 60 | + { |
| 61 | + var configPath = appDomainSetup.ConfigurationFile; |
| 62 | + try |
| 63 | + { |
| 64 | + Logger.Debug($"Try to modify {configPath}"); |
| 65 | + var config = XDocument.Load(configPath); |
| 66 | + ModifyConfig(config); |
| 67 | + |
| 68 | + var settings = new XmlWriterSettings { OmitXmlDeclaration = false, Encoding = Encoding.UTF8 }; |
| 69 | + using var memoryStream = new MemoryStream(); |
| 70 | + using var xmlWriter = XmlWriter.Create(memoryStream, settings); |
| 71 | + config.WriteTo(xmlWriter); |
| 72 | + xmlWriter.Flush(); |
| 73 | + appDomainSetup.SetConfigurationBytes(memoryStream.ToArray()); |
| 74 | + Logger.Information($"Config modified: {config}"); |
| 75 | + } |
| 76 | + catch (Exception e) |
| 77 | + { |
| 78 | + Logger.Error(e, "Failed to modify app domain config "); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private static void ModifyConfig(XDocument config) |
| 83 | + { |
| 84 | + var configuration = config.Element(Names.Configuration); |
| 85 | + if (configuration == null) |
| 86 | + { |
| 87 | + throw new InvalidOperationException(); |
| 88 | + } |
| 89 | + |
| 90 | + var runtime = configuration.Element(Names.Runtime); |
| 91 | + if (runtime == null) |
| 92 | + { |
| 93 | + runtime = new XElement(Names.Runtime); |
| 94 | + configuration.Add(runtime); |
| 95 | + } |
| 96 | + |
| 97 | + var assemblyBinding = runtime.Element(Names.AssemblyBinding); |
| 98 | + if (assemblyBinding == null) |
| 99 | + { |
| 100 | + assemblyBinding = new XElement(Names.AssemblyBinding); |
| 101 | + runtime.Add(assemblyBinding); |
| 102 | + } |
| 103 | + |
| 104 | + foreach (var assemblyInfo in AssemblyCatalog.GetAssemblies()) |
| 105 | + { |
| 106 | + var existingRedirects = assemblyBinding |
| 107 | + .Descendants(Names.AssemblyIdentity) |
| 108 | + .Where(identity => |
| 109 | + string.Equals(identity.Attribute(Names.Name)?.Value, assemblyInfo.FullName.Name, StringComparison.OrdinalIgnoreCase) |
| 110 | + && string.Equals(identity.Attribute(Names.PublicKeyToken)?.Value, assemblyInfo.Token, StringComparison.OrdinalIgnoreCase)) |
| 111 | + .Select(identity => identity.Parent) |
| 112 | + .Elements(Names.BindingRedirect).ToList(); |
| 113 | + if (existingRedirects.Count > 1) |
| 114 | + { |
| 115 | + Logger.Warning($"Multiple redirections for {assemblyInfo.FullName.Name} found. Skipping it."); |
| 116 | + continue; |
| 117 | + } |
| 118 | + |
| 119 | + if (existingRedirects.Count == 1) |
| 120 | + { |
| 121 | + var versionString = existingRedirects.First().Attribute(Names.NewVersion)?.Value ?? string.Empty; |
| 122 | + Version existingNewVersion; |
| 123 | + try |
| 124 | + { |
| 125 | + existingNewVersion = new Version(versionString); |
| 126 | + } |
| 127 | + catch (Exception ex) |
| 128 | + { |
| 129 | + Logger.Error(ex, $"Version {versionString} not parsed for {assemblyInfo.FullName.Name}. Treat it as 0.0."); |
| 130 | + existingNewVersion = new Version(0, 0); |
| 131 | + } |
| 132 | + |
| 133 | + if (existingNewVersion >= assemblyInfo.Version) |
| 134 | + { |
| 135 | + // App uses higher version, use it |
| 136 | + if (existingRedirects.First().Attribute(Names.OldVersion) is { } oldVersion) |
| 137 | + { |
| 138 | + oldVersion.Value = $"0.0.0.0-{existingNewVersion}"; |
| 139 | + } |
| 140 | + |
| 141 | + Logger.Debug($"Use existing version. Override version range for {assemblyInfo.FullName.Name}"); |
| 142 | + existingRedirects[0].Parent!.Add(new XElement( |
| 143 | + Names.CodeBase, |
| 144 | + new XAttribute(Names.Version, assemblyInfo.Version), |
| 145 | + new XAttribute(Names.Href, new Uri(assemblyInfo.Path).AbsoluteUri))); |
| 146 | + continue; |
| 147 | + } |
| 148 | + else |
| 149 | + { |
| 150 | + // Remove existing redirect, we will add a new one to use higher version |
| 151 | + existingRedirects[0].Parent!.Remove(); |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + var dependentAssembly = new XElement( |
| 156 | + Names.DependentAssembly, |
| 157 | + new XElement( |
| 158 | + Names.AssemblyIdentity, |
| 159 | + new XAttribute(Names.Name, assemblyInfo.FullName.Name), |
| 160 | + new XAttribute(Names.PublicKeyToken, assemblyInfo.Token), |
| 161 | + new XAttribute(Names.Culture, Names.NeutralCulture)), |
| 162 | + new XElement( |
| 163 | + Names.BindingRedirect, |
| 164 | + new XAttribute(Names.OldVersion, $"0.0.0.0-{assemblyInfo.Version}"), |
| 165 | + new XAttribute(Names.NewVersion, assemblyInfo.Version)), |
| 166 | + new XElement( |
| 167 | + Names.CodeBase, |
| 168 | + new XAttribute(Names.Version, assemblyInfo.Version), |
| 169 | + new XAttribute(Names.Href, new Uri(assemblyInfo.Path).AbsoluteUri))); |
| 170 | + assemblyBinding.Add(dependentAssembly); |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + private static class Names |
| 175 | + { |
| 176 | + public const string NeutralCulture = "neutral"; |
| 177 | + public static readonly XName Configuration = XName.Get("configuration"); |
| 178 | + public static readonly XName Runtime = XName.Get("runtime"); |
| 179 | + public static readonly XName AssemblyBinding = XName.Get("assemblyBinding", AsmNs); |
| 180 | + public static readonly XName AssemblyIdentity = XName.Get("assemblyIdentity", AsmNs); |
| 181 | + public static readonly XName BindingRedirect = XName.Get("bindingRedirect", AsmNs); |
| 182 | + public static readonly XName DependentAssembly = XName.Get("dependentAssembly", AsmNs); |
| 183 | + public static readonly XName CodeBase = XName.Get("codeBase", AsmNs); |
| 184 | + public static readonly XName Name = XName.Get("name"); |
| 185 | + public static readonly XName PublicKeyToken = XName.Get("publicKeyToken"); |
| 186 | + public static readonly XName NewVersion = XName.Get("newVersion"); |
| 187 | + public static readonly XName OldVersion = XName.Get("oldVersion"); |
| 188 | + public static readonly XName Culture = XName.Get("culture"); |
| 189 | + public static readonly XName Version = XName.Get("version"); |
| 190 | + public static readonly XName Href = XName.Get("href"); |
| 191 | + private const string AsmNs = "urn:schemas-microsoft-com:asm.v1"; |
22 | 192 | } |
23 | 193 | } |
24 | 194 | #endif |
0 commit comments