Skip to content

Enhance lifetime monitoring in EventListener #45247

Closed

Description

@thargy

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:

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 via EventWrittenEventArgs, the proposed API addresses this by having a new EventCounterUpdated event, which is a subset of the EventWritten event. However, an alternative might be to provide similar data as found in EventWrittenEventArgs to the EventCounter lifetime events and not add the new EventCounterUpdated event.

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

  1. added
    api-suggestion
    on Nov 26, 2020
  2. added
    untriaged
    on Nov 26, 2020
  3. thargy commented on Nov 26, 2020

    @thargy
    Author

    A more compelling example usage would probably use SourceCache from DynamicData (effectively an observable dictionary), or an ObservableCollection.

  4. removed
    untriaged
    on Nov 28, 2020
  5. added this to the 6.0.0 milestone on Nov 28, 2020
  6. added
    User Story
    and removed
    User Story
    on Jan 12, 2021
  7. modified the milestones: 6.0.0, 7.0.0 on Jun 16, 2021
  8. thargy commented on Aug 17, 2021

    @thargy
    Author

    Not going to lie, sad to see this bumped 😞.

  9. josalem commented on Aug 18, 2021

    @josalem
    Contributor

    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. EventSource isn't intended to be used in an instanced manner. As you mentioned in the other issue, it does implement IDisposable and 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 EventSource in .net7 on since there are some considerations around AssemblyLoadContexts 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):

    public sealed class MyComponentCounterSource : EventSource
    {
    	// you could also return the counter directly and track it in the Component itself rather than storing it on the EventSource in this dict
    	private Dictionary<component, EventCounter> _counterDict = new();
    
    	public static MyCounterSource Log = new();
    
    	[NonEvent]
    	public void OnComponentConstruction(MyComponent component)
    	{
    		lock (_counterDict)
    		{
    			_counterDict.Add(component, new PollingCounter(...));
    		}
    	}
    
    	[NonEvent]
    	public void OnComponentDispose(MyComponent component)
    	{
    		lock (_counterDict)
    		{
    			_counterDict.Remove(component, out EventCounter counter);
    			counter.Dispose();
    		}
    	}
    }
    public class MyComponent : IDisposable
    {
    	public MyComponent()
    	{
    		// rest of init
    		MyComponentCounterSource.Log.OnComponentConstruction(this);
    	}
    
    	public void Dispose()
    	{
    		MyComponentCounterSource.Log.OnComponentDispose(this);
    		// other disposal
    	}
    }

    Alternatively, you could have regular events on an EventSource and you have the events contain the instance name, the counter name on that instance, and the counter values. Though, that is effectively re-implementing EventCounters.

    Hopefully, that helps! Again, we'll revisit this type of change in the 7.0 timeframe 😃

  10. thargy commented on Aug 18, 2021

    @thargy
    Author

    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, the EventCounters and EventSources were in an external process to the EventListener, 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 monitor to 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)?

  11. josalem commented on Aug 18, 2021

    @josalem
    Contributor

    Ah, I think there's a miscommunication happening. EventListener can only be used for in-process listening. It has no mechanism for listening to other processes.

    of detecting that lifetime to prevent growth on long-running monitor 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 monitor then that is an artifact of how dotnet counters monitor works 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 in dotnet-counters and ship an update for dotnet-counters whenever it is merged.

  12. thargy commented on Aug 18, 2021

    @thargy
    Author

    Ah, I think there's a miscommunication happening. EventListener can only be used for in-process listening. It has no mechanism for listening to other processes.

    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:

    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.

    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 involved EventListeners on some level and that adding these extra events might be a step to exposing such events for the process and detecting them using Microsoft.Diagnostics.Tracing.

    I'm not sure I track why creating and disposing counters in a process would cause growth in an external process...

    This happens today, tools such as dotnet-counters and other consumers of Microsoft.Diagnostics.Tracing frequently 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 the AppDomain, 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):

    1. To improve the experience of using 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.
    2. To ease the development of 3rd party libraries. Note you're proposed workaround would not work when creating a 3rd party library to monitor in-process event counters. Instead a 'timeout' workaround would be needed, which is subpar, and less robust (consider the admittedly bad use case of rapid lifetime cycling).
    3. To potentially expose new lifetime related events to ETW, to allow Microsoft.Diagnostics.Tracing to similarly expose them to out-of-process monitors, improving the robustness of such tools (including dotnet-counters which could make use of them as an improvement over a timeout approach).
    4. If transient lifetimes are to be scrapped in .NET 7, to remind the working group that it may not be an insignificant breaking change; and may be considered a regression.

    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-counters which didn't handle it all.

    I hope that clarifies things a bit more? Thanks for your feedback.

  13. josalem commented on Aug 23, 2021

    @josalem
    Contributor

    I hope that clarifies things a bit more?

    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:

    1. The modern eventing infrastructure in .net is influenced by the inner workings of ETW, but is not designed exclusively for ETW.
    2. Out-of-process eventing clients, e.g., dotnet-trace, etc., can only listen to the list of providers that they specify at the start of a tracing session. Changing this list of providers involves stopping one session and starting another.
    3. ETW doesn't provide a concept of provider lifetime to listeners. EventPipe, .net's modern, cross-platform equivalent of ETW, follows this same pattern and does not provide listeners with a concept of provider lifetime.
    4. There is currently no mechanism for informing out-of-process listeners of the creation of a new source. In other words, a user of an out-of-process listener must know a priori what providers exist in a target process before it runs. Typically, this is achieved with documentation.
    5. The EventSource API is marked IDisposable. This is an artifact of there being native resources that need to be cleaned up when an EventSource is no longer rooted. This API doesn't prohibit users from having short-lived EventSources.

    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-lived EventSource. 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 EventSource and documenting this for their users. As an example, if someone were to implement the EventSource system I put in a previous comment, they could add a MyComponentDisposed event 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 any MyComponent that gets created and events from when MyComponents get disposed. The responsibility of implementing this is on the library developer, though and not necessarily something that EventSource itself needs to be aware of.

    My point here is that EventSource is 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, static EventSource should be used with "instanced" events and counters, rather than having multiple "instanced" EventSources.

    I think the documentation on EventSource is lacking these nuances. It doesn't prescribe the static public MySource Log = new(); pattern and even mentions that users should be using using blocks or explicitly calling Dispose. This can give the impression that an EventSource is 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:

    • Vastly improve the EventSource documentation to include a lot of these nuances.
      • Specifically prescribe the static public MySource Log = new(); pattern.
    • Update or create eventing tutorials for some of these desired use cases.
      • As an example, I think your scenario of a multi-camera streaming program producing counters per-camera would be a good tutorial.

    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:

    • the frame rate, bitrate, and temperature of every camera in the system every 10 seconds
    • camera connect and camera disconnect notification

    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 one EventSource that fires a CameraConnected/CameraDisconnected event 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 a CameraDisconnected event, 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

  14. thargy commented on Aug 23, 2021

    @thargy
    Author

    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.

  15. josalem commented on Aug 23, 2021

    @josalem
    Contributor

    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 😄

  16. thargy commented on Aug 23, 2021

    @thargy
    Author

    I'd be happy for it to go into the #515 issue, as it seems pretty related?

  17. josalem commented on Aug 23, 2021

    @josalem
    Contributor

    Perfect. I'll go ahead and do that 😃

  18. josalem commented on Aug 23, 2021

    @josalem
    Contributor

    Closing this as the work is now tracked in dotnet/diagnostics#515

  19. ghost locked as resolved and limited conversation to collaborators on Sep 23, 2021
  20. mikelle-rogers commented on Apr 21, 2022

    @mikelle-rogers
    Member

    Opening the issue because we are no longer using 515 to track this issue.

  21. mikelle-rogers commented on Apr 25, 2022

    @mikelle-rogers
    Member

    Confirmed that this has been completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Diagnostics.Tracingfeature-request

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions