-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Improve logging from agent #43672
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
Merged
Merged
Improve logging from agent #43672
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.Extensions.HotReload; | ||
|
||
internal sealed class AgentReporter | ||
{ | ||
private readonly List<(string message, AgentMessageSeverity severity)> _log = []; | ||
|
||
public void Report(string message, AgentMessageSeverity severity) | ||
{ | ||
_log.Add((message, severity)); | ||
} | ||
|
||
public IReadOnlyCollection<(string message, AgentMessageSeverity severity)> GetAndClearLogEntries(ResponseLoggingLevel level) | ||
{ | ||
lock (_log) | ||
{ | ||
var filteredLog = (level != ResponseLoggingLevel.Verbose) | ||
? _log.Where(static entry => entry.severity != AgentMessageSeverity.Verbose) | ||
: _log; | ||
|
||
var log = filteredLog.ToArray(); | ||
_log.Clear(); | ||
return log; | ||
} | ||
} | ||
} |
Large diffs are not rendered by default.
Oops, something went wrong.
239 changes: 239 additions & 0 deletions
239
src/BuiltInTools/DotNetDeltaApplier/MetadataUpdateHandlerInvoker.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,239 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Reflection; | ||
|
||
namespace Microsoft.Extensions.HotReload; | ||
|
||
/// <summary> | ||
/// Finds and invokes metadata update handlers. | ||
/// </summary> | ||
internal sealed class MetadataUpdateHandlerInvoker(AgentReporter reporter) | ||
{ | ||
internal sealed class RegisteredActions(IReadOnlyList<Action<Type[]?>> clearCache, IReadOnlyList<Action<Type[]?>> updateApplication) | ||
{ | ||
public void Invoke(Type[] updatedTypes) | ||
{ | ||
foreach (var action in clearCache) | ||
{ | ||
action(updatedTypes); | ||
} | ||
|
||
foreach (var action in updateApplication) | ||
{ | ||
action(updatedTypes); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// For testing. | ||
/// </summary> | ||
internal IEnumerable<Action<Type[]?>> ClearCache => clearCache; | ||
|
||
/// <summary> | ||
/// For testing. | ||
/// </summary> | ||
internal IEnumerable<Action<Type[]?>> UpdateApplication => updateApplication; | ||
} | ||
|
||
private const string ClearCacheHandlerName = "ClearCache"; | ||
private const string UpdateApplicationHandlerName = "UpdateApplication"; | ||
|
||
private RegisteredActions? _actions; | ||
|
||
/// <summary> | ||
/// Call when a new assembly is loaded. | ||
/// </summary> | ||
internal void Clear() | ||
=> Interlocked.Exchange(ref _actions, null); | ||
|
||
/// <summary> | ||
/// Invokes all registerd handlers. | ||
/// </summary> | ||
internal void Invoke(Type[] updatedTypes) | ||
{ | ||
try | ||
{ | ||
// Defer discovering metadata updata handlers until after hot reload deltas have been applied. | ||
// This should give enough opportunity for AppDomain.GetAssemblies() to be sufficiently populated. | ||
var actions = _actions; | ||
if (actions == null) | ||
{ | ||
Interlocked.CompareExchange(ref _actions, GetMetadataUpdateHandlerActions(), null); | ||
actions = _actions; | ||
} | ||
|
||
reporter.Report("Invoking metadata update handlers.", AgentMessageSeverity.Verbose); | ||
|
||
actions.Invoke(updatedTypes); | ||
|
||
reporter.Report("Deltas applied.", AgentMessageSeverity.Verbose); | ||
} | ||
catch (Exception e) | ||
{ | ||
reporter.Report(e.ToString(), AgentMessageSeverity.Warning); | ||
} | ||
} | ||
|
||
private IEnumerable<Type> GetHandlerTypes() | ||
{ | ||
// We need to execute MetadataUpdateHandlers in a well-defined order. For v1, the strategy that is used is to topologically | ||
// sort assemblies so that handlers in a dependency are executed before the dependent (e.g. the reflection cache action | ||
// in System.Private.CoreLib is executed before System.Text.Json clears its own cache.) | ||
// This would ensure that caches and updates more lower in the application stack are up to date | ||
// before ones higher in the stack are recomputed. | ||
var sortedAssemblies = TopologicalSort(AppDomain.CurrentDomain.GetAssemblies()); | ||
|
||
foreach (var assembly in sortedAssemblies) | ||
{ | ||
foreach (var attr in TryGetCustomAttributesData(assembly)) | ||
{ | ||
// Look up the attribute by name rather than by type. This would allow netstandard targeting libraries to | ||
// define their own copy without having to cross-compile. | ||
if (attr.AttributeType.FullName != "System.Reflection.Metadata.MetadataUpdateHandlerAttribute") | ||
{ | ||
continue; | ||
} | ||
|
||
IList<CustomAttributeTypedArgument> ctorArgs = attr.ConstructorArguments; | ||
if (ctorArgs.Count != 1 || | ||
ctorArgs[0].Value is not Type handlerType) | ||
{ | ||
reporter.Report($"'{attr}' found with invalid arguments.", AgentMessageSeverity.Warning); | ||
continue; | ||
} | ||
|
||
yield return handlerType; | ||
} | ||
} | ||
} | ||
|
||
public RegisteredActions GetMetadataUpdateHandlerActions() | ||
=> GetMetadataUpdateHandlerActions(GetHandlerTypes()); | ||
|
||
/// <summary> | ||
/// Internal for testing. | ||
/// </summary> | ||
internal RegisteredActions GetMetadataUpdateHandlerActions(IEnumerable<Type> handlerTypes) | ||
{ | ||
var clearCacheActions = new List<Action<Type[]?>>(); | ||
var updateApplicationActions = new List<Action<Type[]?>>(); | ||
|
||
foreach (var handlerType in handlerTypes) | ||
{ | ||
bool methodFound = false; | ||
|
||
if (GetUpdateMethod(handlerType, ClearCacheHandlerName) is MethodInfo clearCache) | ||
{ | ||
clearCacheActions.Add(CreateAction(clearCache)); | ||
methodFound = true; | ||
} | ||
|
||
if (GetUpdateMethod(handlerType, UpdateApplicationHandlerName) is MethodInfo updateApplication) | ||
{ | ||
updateApplicationActions.Add(CreateAction(updateApplication)); | ||
methodFound = true; | ||
} | ||
|
||
if (!methodFound) | ||
{ | ||
reporter.Report( | ||
$"Expected to find a static method '{ClearCacheHandlerName}' or '{UpdateApplicationHandlerName}' on type '{handlerType.AssemblyQualifiedName}' but neither exists.", | ||
AgentMessageSeverity.Warning); | ||
} | ||
} | ||
|
||
return new RegisteredActions(clearCacheActions, updateApplicationActions); | ||
|
||
Action<Type[]?> CreateAction(MethodInfo update) | ||
{ | ||
var action = (Action<Type[]?>)update.CreateDelegate(typeof(Action<Type[]?>)); | ||
return types => | ||
{ | ||
try | ||
{ | ||
action(types); | ||
} | ||
catch (Exception ex) | ||
{ | ||
reporter.Report($"Exception from '{action}': {ex}", AgentMessageSeverity.Warning); | ||
} | ||
}; | ||
} | ||
|
||
MethodInfo? GetUpdateMethod(Type handlerType, string name) | ||
{ | ||
if (handlerType.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, binder: null, new[] { typeof(Type[]) }, modifiers: null) is MethodInfo updateMethod && | ||
updateMethod.ReturnType == typeof(void)) | ||
{ | ||
return updateMethod; | ||
} | ||
|
||
foreach (MethodInfo method in handlerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) | ||
{ | ||
if (method.Name == name) | ||
{ | ||
reporter.Report($"Type '{handlerType}' has method '{method}' that does not match the required signature.", AgentMessageSeverity.Warning); | ||
break; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
} | ||
|
||
private IList<CustomAttributeData> TryGetCustomAttributesData(Assembly assembly) | ||
{ | ||
try | ||
{ | ||
return assembly.GetCustomAttributesData(); | ||
} | ||
catch (Exception e) | ||
{ | ||
// In cross-platform scenarios, such as debugging in VS through WSL, Roslyn | ||
// runs on Windows, and the agent runs on Linux. Assemblies accessible to Windows | ||
// may not be available or loaded on linux (such as WPF's assemblies). | ||
// In such case, we can ignore the assemblies and continue enumerating handlers for | ||
// the rest of the assemblies of current domain. | ||
reporter.Report($"'{assembly.FullName}' is not loaded ({e.Message})", AgentMessageSeverity.Verbose); | ||
return []; | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Internal for testing. | ||
/// </summary> | ||
internal static List<Assembly> TopologicalSort(Assembly[] assemblies) | ||
{ | ||
var sortedAssemblies = new List<Assembly>(assemblies.Length); | ||
|
||
var visited = new HashSet<string>(StringComparer.Ordinal); | ||
|
||
foreach (var assembly in assemblies) | ||
{ | ||
Visit(assemblies, assembly, sortedAssemblies, visited); | ||
} | ||
|
||
static void Visit(Assembly[] assemblies, Assembly assembly, List<Assembly> sortedAssemblies, HashSet<string> visited) | ||
{ | ||
var assemblyIdentifier = assembly.GetName().Name!; | ||
if (!visited.Add(assemblyIdentifier)) | ||
{ | ||
return; | ||
} | ||
|
||
foreach (var dependencyName in assembly.GetReferencedAssemblies()) | ||
{ | ||
var dependency = Array.Find(assemblies, a => a.GetName().Name == dependencyName.Name); | ||
if (dependency is not null) | ||
{ | ||
Visit(assemblies, dependency, sortedAssemblies, visited); | ||
} | ||
} | ||
|
||
sortedAssemblies.Add(assembly); | ||
} | ||
|
||
return sortedAssemblies; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just moved and refactored.