Repository navigation
Description
Background and Motivation
Further to the discussion at dotnet/diagnostics, EventCounter and EventSource both implement IDisposable after which the associated resources are released. This allows for 'instanced' event counters with a lifetime that does not match the associated EventSource; and event sources that have a shorter lifetime than the associated process.
However, the EventListener only detects one of these four life-time markers. Specifically, it only reports the creation of an EventSource. Ideally, it would be notified for all four, that is the creation and disposal of EventSources and, similarly, of EventCounters, to allow the listener, inheritors, and consumers, to clean-up any resources associated with short-lived counters and/or sources. Without such functionality, a long-running event listener could eventually run out of memory as the monitored process creates and destroys counters/sources dynamically.
Proposed API
The current API is at:
runtime/src/libraries/System.Diagnostics.Tracing/ref/System.Diagnostics.Tracing.cs
Lines 111 to 124 in 6072e4d
| public abstract partial class EventListener : System.IDisposable | |
| { | |
| protected EventListener() { } | |
| public event System.EventHandler<System.Diagnostics.Tracing.EventSourceCreatedEventArgs>? EventSourceCreated { add { } remove { } } | |
| public event System.EventHandler<System.Diagnostics.Tracing.EventWrittenEventArgs>? EventWritten { add { } remove { } } | |
| public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { } | |
| public virtual void Dispose() { } | |
| public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { } | |
| public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { } | |
| public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string?>? arguments) { } | |
| protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; } | |
| protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { } | |
| protected internal virtual void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { } | |
| } |
Here is the proposed diff.
System.Diagnostics.Tracing.cs | 30 ++++++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/System.Diagnostics.Tracing.cs b/System.Diagnostics.Tracing.cs
index 5af41cf..82a73be 100644
--- a/System.Diagnostics.Tracing.cs
+++ b/System.Diagnostics.Tracing.cs
@@ -112,6 +112,10 @@ namespace System.Diagnostics.Tracing
{
protected EventListener() { }
public event System.EventHandler<System.Diagnostics.Tracing.EventSourceCreatedEventArgs>? EventSourceCreated { add { } remove { } }
+ public event System.EventHandler<System.Diagnostics.Tracing.EventSourceDisposedEventArgs>? EventSourceDisposed { add { } remove { } }
+ public event System.EventHandler<System.Diagnostics.Tracing.EventCounterCreatedEventArgs>? EventCounterCreated { add { } remove { } }
+ public event System.EventHandler<System.Diagnostics.Tracing.EventCounterDisposedEventArgs>? EventCounterDisposed { add { } remove { } }
+ public event System.EventHandler<System.Diagnostics.Tracing.EventCounterUpdatedEventArgs>? EventCounterUpdated { add { } remove { } }
public event System.EventHandler<System.Diagnostics.Tracing.EventWrittenEventArgs>? EventWritten { add { } remove { } }
public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { }
public virtual void Dispose() { }
@@ -120,6 +124,10 @@ namespace System.Diagnostics.Tracing
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string?>? arguments) { }
protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; }
protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
+ protected internal virtual void OnEventSourceDisposed(System.Diagnostics.Tracing.EventSource eventSource) { }
+ protected internal virtual void OnEventCounterCreated(System.Diagnostics.Tracing.EventCounter eventCounter) { }
+ protected internal virtual void OnEventCounterDisposed(System.Diagnostics.Tracing.EventCounter eventCounter) { }
+ protected internal virtual void OnEventCounterUpdate(System.Diagnostics.Tracing.EventCounterUpdatedEventArgs eventData) { }
protected internal virtual void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { }
}
[System.FlagsAttribute]
@@ -227,6 +235,21 @@ namespace System.Diagnostics.Tracing
public EventSourceCreatedEventArgs() { }
public System.Diagnostics.Tracing.EventSource? EventSource { get { throw null; } }
}
+ public partial class EventSourceDisposedEventArgs : System.EventArgs
+ {
+ public EventSourceDisposedEventArgs() { }
+ public System.Diagnostics.Tracing.EventSource? EventSource { get { throw null; } }
+ }
+ public partial class EventCounterCreatedEventArgs : System.EventArgs
+ {
+ public EventCounterCreatedEventArgs() { }
+ public System.Diagnostics.Tracing.EventCounter? EventSource { get { throw null; } }
+ }
+ public partial class EventCounterDisposedEventArgs : System.EventArgs
+ {
+ public EventCounterDisposedEventArgs() { }
+ public System.Diagnostics.Tracing.EventCounter? EventSource { get { throw null; } }
+ }
public partial class EventSourceException : System.Exception
{
public EventSourceException() { }
@@ -282,6 +305,13 @@ namespace System.Diagnostics.Tracing
public System.DateTime TimeStamp { get { throw null; } }
public byte Version { get { throw null; } }
}
+ public partial class EventCounterUpdatedEventArgs : System.EventArgs
+ {
+ internal EventCounterUpdatedEventArgs() { }
+ public System.Diagnostics.Tracing.EventWrittenEventArgs EventWrittenEventArgs { get { throw null; } }
+ public System.Diagnostics.Tracing.EventCounter EventCounter { get { throw null; } }
+ public double Metric { get { throw null; } }
+ }
[System.AttributeUsageAttribute(System.AttributeTargets.Method)]
public sealed partial class NonEventAttribute : System.Attribute
{Which adds 3 new events (and associated handlers) to inform the inheritor or consumer of the disposal of an EventSource, and the creation, or disposal, of an EventCounter. Further, it adds a new EventCounterUpdated event which is called whenever and EventWritten event is called, that is logically associated with an EventCounter, allowing for much easier consumption.
NOTE My proposal for EventCounterUpdatedEventArgs is a starting point for discussion, it could easily be expanded to provide more useful functionality, or direct access through to the underlying EventWrittenEventArgs; it is also an addition to correspond more readily to the life-time events for counters. As discussed below, it is not technically a requirement to add the EventCounterUpdated event and this class, but it seems like the opportune time to add such an event to reduce the boilerplate implementations currently required for handling counters and to reflect more accurately the EventSource API.
Usage Examples
Instead of the example found in https://docs.microsoft.com/en-us/dotnet/core/diagnostics/event-counters, the following would be possible, which exposes a simple dictionary of the currently active counters and their latest metric (NOTE This is for demonstration purposes, it hasn't been compiled obviously, and is not concerned regarding thread-safety):
public class SimpleEventListener : EventListener
{
private readonly int _intervalSec;
private readonly Dictionary<EventCounter, double> _counters = new Dictionary<EventCounter, double>();
public IReadonlyDictionary<EventCounter, double> Counters => _counters;
public SimpleEventListener(int intervalSec = 1) =>
_intervalSec = intervalSec <= 0
? throw new ArgumentException("Interval must be at least 1 second.", nameof(intervalSec))
: intervalSec;
protected override void OnEventSourceCreated(EventSource source)
{
if (!source.Name.Equals("System.Runtime"))
{
return;
}
EnableEvents(source, EventLevel.Verbose, EventKeywords.All, new Dictionary<string, string>()
{
["EventCounterIntervalSec"] = _intervalSec.ToString()
});
}
protected override void OnEventCounterCreated(EventCounter counter)
{
_counters[counter] = 0D;
}
protected override void OnEventCounterUpdated(EventCounterUpdatedEventArgs eventArgs)
{
_counters[eventArgs.EventCounter] = eventArgs.Metric;
}
protected override void OnEventCounterDisposed(EventCounter counter)
{
_counters.Remove(counter);
}
}Alternative Designs
-
Listeners could record the last time an event was received from a specific counter and infer that it was disposed after a suitable timeout. It would be a significantly inferior solution and would not allow accurate tracking of the lifetime of sources and counters.
-
The current API doesn't actually expose
EventCounters, but, instead, provides a breakdown of information viaEventWrittenEventArgs, the proposed API addresses this by having a newEventCounterUpdatedevent, which is a subset of theEventWrittenevent. However, an alternative might be to provide similar data as found inEventWrittenEventArgsto theEventCounterlifetime events and not add the newEventCounterUpdatedevent.
Risks
I am not currently aware of the information currently passed through the inter-process pipes, as such implementing these new events is likely to increase the bandwidth consumed. However, that is likely insignificant compared to the bandwidth used by the regular event updates themselves. Further, there will be an increase in the number of events raised, though this too would be likely insignificant in comparison to the frequency of the EventWritten event.
Care needs to be taken that monitored producers may not yet send notification of the 3 new lifetime events for the listener to consume. This matters most for anyone expecting the EventCounterCreated event and anticipating being able to perform setup actions prior to receiving events from the specific counter. To mitigate this the event should be fired immediately prior to an EventWritten (and EventCounterUpdated - see above) event.
Simiarly, the two disposal events may not be triggered. This can happen because the monitored app has not yet been updated to a version supporting the proposed API; but can also happen because the process is terminated prematurely, or the objects are not correctly disposed. This is likely to be less problematic to code, however, it too could be mitigated by optionally supporting a timeout mechanism that will signal the relevant xxxDisposed event(s) when a counter or source has not been updated in a particular period. The above suggestion about triggering the relevant xxxCreated event(s), automatically, for an unexpected EventWritten would mitigate premature disposal.
Tagging @sywhang and @josalem as requested.
Activity
thargy commentedon Nov 26, 2020
A more compelling example usage would probably use
SourceCachefrom DynamicData (effectively an observable dictionary), or anObservableCollection.thargy commentedon Aug 17, 2021
Not going to lie, sad to see this bumped 😞.
josalem commentedon Aug 18, 2021
I saw your comment @thargy and took a look through the history on this.
As you pointed out, this didn't make it in to .net6.
That being said, I think there a few things worth pointing out.
EventSourceisn't intended to be used in an instanced manner. As you mentioned in the other issue, it does implementIDisposableand you certainly can create instanced sources. Doing so, however, is rather expensive as there are substantial resources created depending on the use case and a lot of duplicate work is performed.We're, however, looking into some changes to lifetimes of
EventSourcein .net7 on since there are some considerations aroundAssemblyLoadContexts that we probably need to address. If we choose to investigate this specific API suggestion it would most likely happen as part of that work.All that aside, I think there is already a way to do what you want without having to keep track of the lifetimes or even expect that
EventSources have lifetimes shorter than the process.The following should roughly map to what it sounds like you're trying to do (caveat emptor -- I didn't actually run this code):
Alternatively, you could have regular events on an
EventSourceand you have the events contain the instance name, the counter name on that instance, and the counter values. Though, that is effectively re-implementingEventCounters.Hopefully, that helps! Again, we'll revisit this type of change in the 7.0 timeframe 😃
thargy commentedon Aug 18, 2021
It's been a while since I looked at this, so forgive me if I'm being dumb or missing something, but the scenario that led to this was when looking at functionality and bugs in
dotnet-counters. I was writing code for monitoring a process from another process. In that scenario, which I believe is actually a common use case, theEventCounters andEventSources were in an external process to theEventListener, with data being passed inter-process.Because sources and counters are disposable and are not guaranteed to have a lifetime that matches their containing process, then external processes need a mechanism (based on the current model) of detecting that lifetime to prevent growth on long-running monitor processes, particularly when monitoring a process that create and destroys counters/sources.
My own use case was using
dotnet-counters monitorto monitor a program that had statistics on incoming streams. Streams were generally long-lasting, and there would only be a relatively small number simultaneously, but multiple streams could be created/destroyed within a process lifetime (when long-running on a server for example). The costs of the creation/deletion per stream instance of counters were acceptable compared to the average stream duration. Importantly, the current API has no restrictions in doing that. Indeed, it's a very useful feature to allow monitoring per instance. If disposal was deprecated (i.e. sources/counters become permanent for a process - effectively statics) that would be a regression IMHO.As such, this issue is more about a need to ensure that lifetime events are propagated out to the listeners across the process, so I don't think your code example helps at all in the scenario where you have no ability to modify the event source (e.g. as an author of a common monitoring utility tool)?
josalem commentedon Aug 18, 2021
Ah, I think there's a miscommunication happening.
EventListenercan only be used for in-process listening. It has no mechanism for listening to other processes.I'm not sure I track why creating and disposing counters in a process would cause growth in an external process. If you're referring to the UI aspect (list of received counters and their values) of
dotnet counters monitorthen that is an artifact of howdotnet counters monitorworks and isn't tied to the lifetime of the source in the target process.It sounds like what you want is what was described in your feature request in dotnet/diagnostics. That can happen out of band since
dotnet-counters's release cycle isn't closely tied to the .net release cycle. In other words, we can still make that change in the .net6 timeline indotnet-countersand ship an update fordotnet-counterswhenever it is merged.thargy commentedon Aug 18, 2021
Sorry, my fault, I really should be clearer. In my defence, as I mentioned above, it's been quite some time since I looked at this. 😨
In the original post I said:
This was because I wasn't intimately familiar with how the Windows ETW system interacted with
EventSources in .NET, I was assuming (probably incorrectly) that it involvedEventListeners on some level and that adding these extra events might be a step to exposing such events for the process and detecting them usingMicrosoft.Diagnostics.Tracing.This happens today, tools such as
dotnet-countersand other consumers ofMicrosoft.Diagnostics.Tracingfrequently assume that processes do not continue to add new counters during their lifetime, so do not clean up. This comes from the reality that it is normally true (at least within Microsoft?), but the current API neither enforces it nor actively discourages it (in documentation, etc.). Indeed, the disposable nature of the classes strongly implies that their lifetimes do not need to be bound to that of theAppDomain, and, as mentioned above, there are reasonable use cases for keeping it that way. It is true that these are therefore technically 'bugs' in the monitoring tools, but that they occur is at least due to this undocumented standard practice, and the cause of this issue (i.e. to provide a clearer/more discoverable approach by explicitly supporting transient lifetimes).IMHO There seem are to be several uses for this proposal (i.e. for this to be implemented in .NET):
EventListeners in-process, by making more visible the transient lifetimes of counters\sources. Though, I appreciate this is potentially being reviewed for 7, if the disposal pattern remains then exposing these events will prompt consumers to consider lifetimes.Microsoft.Diagnostics.Tracingto similarly expose them to out-of-process monitors, improving the robustness of such tools (includingdotnet-counterswhich could make use of them as an improvement over a timeout approach).It might help to go back to my use case. I was writing a UX WPF component that could run either in process or as a standalone application for monitoring performance counters, and ETW events (to use with my streams app). One of the results of that work was I looked at the APIs and tried to consider what potential problems I might face, and I saw the disposal pattern and realised the potential issues of not tracking disposal. I spent some time looking for a way to avoid a 'timeout approach' (which is always ultimately arbitrary, as it has to make assumptions as to how long a timeout is which it can't do without knowing how short source lifetimes are in a process) and came across
dotnet-counterswhich didn't handle it all.I hope that clarifies things a bit more? Thanks for your feedback.
josalem commentedon Aug 23, 2021
It does! Thanks 😃. Sorry for the delay, I was out of the office at the end of last week.
It's worth taking a step back and looking at a few of the constraints for the eventing system that are going to influence my response here:
EventSourceAPI is markedIDisposable. This is an artifact of there being native resources that need to be cleaned up when anEventSourceis no longer rooted. This API doesn't prohibit users from having short-livedEventSources.I would posit that constraints 2, 3, and 4 heavily disincentivize users from having short-lived or instanced
EventSources. There is nothing in the API that prevents this, but from an end-to-end perspective, it undesirable to have a short-livedEventSource. You are right, though, our documentation does not currently prescribe the desired use case or explicitly suggest to not do otherwise.Nothing prevents a library developer from implementing lifetime information in their own
EventSourceand documenting this for their users. As an example, if someone were to implement theEventSourcesystem I put in a previous comment, they could add aMyComponentDisposedevent that gets sent on disposal of every component. A listening application could then dispose any resources related to a counter from that component when it receives that event. A listener would then just listen to that source to receive counters for anyMyComponentthat gets created and events from whenMyComponents get disposed. The responsibility of implementing this is on the library developer, though and not necessarily something thatEventSourceitself needs to be aware of.My point here is that
EventSourceis already capable of lifetime management, but it is the responsibility of the library developer to implement it and the listener to be aware of how it was implemented. A single, staticEventSourceshould be used with "instanced" events and counters, rather than having multiple "instanced"EventSources.I think the documentation on
EventSourceis lacking these nuances. It doesn't prescribe thestatic public MySource Log = new();pattern and even mentions that users should be usingusingblocks or explicitly callingDispose. This can give the impression that anEventSourceis intended to live a short-ish lifespan which isn't necessarily correct. The documentation should explain this better.In my mind, that leaves the following TODOs from this conversation:
EventSourcedocumentation to include a lot of these nuances.static public MySource Log = new();pattern.To give a slightly more concrete example to make sure we're on the same page, let's pick apart the multi-cam scenario a little. Let's say we want the following information:
You could do this with "instanced"
EventSources per camera in the system, but that would require a listener to know about creation and disposal of these sources otherwise the listener can't know these "instanced" source names (hence your proposal I believe). Rather than do that, a library writer should make oneEventSourcethat fires aCameraConnected/CameraDisconnectedevent pair and spawns a counter with camera name for each of the desired metrics per camera. A listener would only need to subscribe to the one source and then bucket the metrics based on the camera name. Once a listener sees aCameraDisconnectedevent, it could clean up any resources related that camera.Another thing to note, is that
EventCounters should arrive a regular cadence. If a counter value doesn't arrive in the timespan expected (plus or minus some epsilon), this could also be used to signal when to clean up resources without knowing about the end of a counter.I hope that helps!
CC @brianrob since I think he'll find this conversation interesting
thargy commentedon Aug 23, 2021
Thanks so much for taking the time to respond in such detail. I'm confident we're on the same page now; and your suggestions regarding documentation are eminently sensible.
Primarily, prominently prescribing the static pattern would be a big step forward. Alongside that, reminding consumers that a bad actor may create, and stop using (dispose) counters over time, so they should clean up resources if a counter (that they didn't implement) stops producing events, is a wise precaution.
The tutorials you suggested would also be a big win.
Again thank you.
josalem commentedon Aug 23, 2021
My pleasure! In the interest of bookkeeping (and making sure this work happens), would you be okay with closing this issue and taking the TODOs from above and creating a new issue to track this documentation improvement? Alternatively, we could update dotnet/diagnostics#515 to include this work (and reference this issue). I'd be happy to do either 😄
thargy commentedon Aug 23, 2021
I'd be happy for it to go into the #515 issue, as it seems pretty related?
josalem commentedon Aug 23, 2021
Perfect. I'll go ahead and do that 😃
josalem commentedon Aug 23, 2021
Closing this as the work is now tracked in dotnet/diagnostics#515
mikelle-rogers commentedon Apr 21, 2022
Opening the issue because we are no longer using 515 to track this issue.
mikelle-rogers commentedon Apr 25, 2022
Confirmed that this has been completed.