| 
 | 1 | +// Licensed to the .NET Foundation under one or more agreements.  | 
 | 2 | +// The .NET Foundation licenses this file to you under the MIT license.  | 
 | 3 | + | 
 | 4 | +using System;  | 
 | 5 | +using System.Collections.Generic;  | 
 | 6 | +using System.Diagnostics;  | 
 | 7 | +using System.Diagnostics.Tracing;  | 
 | 8 | +using System.Linq;  | 
 | 9 | +using System.Threading;  | 
 | 10 | +using System.Threading.Tasks;  | 
 | 11 | +using Microsoft.Diagnostics.NETCore.Client;  | 
 | 12 | +using Microsoft.Diagnostics.Tracing;  | 
 | 13 | +using Xunit;  | 
 | 14 | + | 
 | 15 | +namespace BasicEventSourceTests  | 
 | 16 | +{  | 
 | 17 | +    /// <summary>  | 
 | 18 | +    /// Implementation of Listener for EventPipe (in-process collection using DiagnosticsClient + EventPipeEventSource).  | 
 | 19 | +    /// </summary>  | 
 | 20 | +    internal sealed class EventPipeListener : Listener  | 
 | 21 | +    {  | 
 | 22 | +        private readonly List<(string eventSourceName, EventCommand command, FilteringOptions options)> _pendingCommands = new();  | 
 | 23 | +        private readonly Dictionary<string, FilteringOptions> _enabled = new(StringComparer.Ordinal);  | 
 | 24 | +        private EventPipeSession _session;  | 
 | 25 | +        private Task _processingTask;  | 
 | 26 | +        private bool _disposed;  | 
 | 27 | + | 
 | 28 | +        public override bool IsDynamicConfigChangeSupported => false;  | 
 | 29 | + | 
 | 30 | +        /// <summary>  | 
 | 31 | +        /// EventPipe NetTrace V5 format can't emit the metadata for a Boolean8 HasValue field that self-describing events use.  | 
 | 32 | +        /// </summary>  | 
 | 33 | +        public override bool IsSelfDescribingNullableSupported => false;  | 
 | 34 | + | 
 | 35 | +        public override bool IsEventPipe => true;  | 
 | 36 | + | 
 | 37 | +        public EventPipeListener() { }  | 
 | 38 | + | 
 | 39 | +        public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)  | 
 | 40 | +        {  | 
 | 41 | +            if (eventSourceName is null)  | 
 | 42 | +            {  | 
 | 43 | +                throw new ArgumentNullException(nameof(eventSourceName));  | 
 | 44 | +            }  | 
 | 45 | + | 
 | 46 | +            if (_session != null)  | 
 | 47 | +            {  | 
 | 48 | +                throw new InvalidOperationException("EventPipeEventListener does not support dynamic configuration changes after Start().");  | 
 | 49 | +            }  | 
 | 50 | +            _pendingCommands.Add((eventSourceName, command, options));  | 
 | 51 | +        }  | 
 | 52 | + | 
 | 53 | +        public override void Start()  | 
 | 54 | +        {  | 
 | 55 | +            if (_session != null)  | 
 | 56 | +            {  | 
 | 57 | +                return; // already started  | 
 | 58 | +            }  | 
 | 59 | + | 
 | 60 | +            // Build provider enable list from pending commands  | 
 | 61 | +            foreach (var (eventSourceName, command, options) in _pendingCommands)  | 
 | 62 | +            {  | 
 | 63 | +                if (command == EventCommand.Enable)  | 
 | 64 | +                {  | 
 | 65 | +                    var effective = options ?? new FilteringOptions();  | 
 | 66 | +                    _enabled[eventSourceName] = effective;  | 
 | 67 | +                }  | 
 | 68 | +                else if (command == EventCommand.Disable)  | 
 | 69 | +                {  | 
 | 70 | +                    _enabled.Remove(eventSourceName);  | 
 | 71 | +                }  | 
 | 72 | +                else  | 
 | 73 | +                {  | 
 | 74 | +                    throw new NotImplementedException();  | 
 | 75 | +                }  | 
 | 76 | +            }  | 
 | 77 | + | 
 | 78 | +            var providers = new List<EventPipeProvider>();  | 
 | 79 | +            foreach (var kvp in _enabled)  | 
 | 80 | +            {  | 
 | 81 | +                var opt = kvp.Value;  | 
 | 82 | +                providers.Add(new EventPipeProvider(kvp.Key, (EventLevel)opt.Level, (long)opt.Keywords, opt.Args));  | 
 | 83 | +            }  | 
 | 84 | + | 
 | 85 | +            var client = new DiagnosticsClient(Environment.ProcessId);  | 
 | 86 | +            _session = client.StartEventPipeSession(providers, false);  | 
 | 87 | + | 
 | 88 | +            _processingTask = Task.Factory.StartNew(() => ProcessEvents(_session), TaskCreationOptions.LongRunning);  | 
 | 89 | +        }  | 
 | 90 | + | 
 | 91 | +        private void ProcessEvents(EventPipeSession session)  | 
 | 92 | +        {  | 
 | 93 | +            using var source = new EventPipeEventSource(session.EventStream);  | 
 | 94 | +            source.Dynamic.All += traceEvent =>  | 
 | 95 | +            {  | 
 | 96 | +                // EventPipe adds extra events we didn't ask for, ignore them.  | 
 | 97 | +                if (traceEvent.ProviderName == "Microsoft-DotNETCore-EventPipe")  | 
 | 98 | +                {  | 
 | 99 | +                    return;  | 
 | 100 | +                }  | 
 | 101 | + | 
 | 102 | +                OnEvent?.Invoke(new EventPipeEvent(traceEvent));  | 
 | 103 | +            };  | 
 | 104 | +            source.Process();  | 
 | 105 | +        }  | 
 | 106 | + | 
 | 107 | +        public override void Dispose()  | 
 | 108 | +        {  | 
 | 109 | +            if (_disposed)  | 
 | 110 | +            {  | 
 | 111 | +                return;  | 
 | 112 | +            }  | 
 | 113 | + | 
 | 114 | +            try  | 
 | 115 | +            {  | 
 | 116 | +                _disposed = true;  | 
 | 117 | +                _session?.Stop();  | 
 | 118 | + | 
 | 119 | +                if (_processingTask != null && !_processingTask.Wait(TimeSpan.FromSeconds(5)))  | 
 | 120 | +                {  | 
 | 121 | +                    // If the session is still streaming data then session.Dispose() below will disconnect the stream   | 
 | 122 | +                    // and likely cause the thread running source.Process() to throw.  | 
 | 123 | +                    Assert.Fail("EventPipeEventListener processing task failed to complete in 5 seconds.");  | 
 | 124 | +                }  | 
 | 125 | +            }  | 
 | 126 | +            finally  | 
 | 127 | +            {  | 
 | 128 | +                _session?.Dispose();  | 
 | 129 | +            }  | 
 | 130 | +        }  | 
 | 131 | + | 
 | 132 | +        public override string ToString() => "EventPipeListener";  | 
 | 133 | + | 
 | 134 | +        /// <summary>  | 
 | 135 | +        /// Wrapper mapping TraceEvent (EventPipe) to harness Event abstraction.  | 
 | 136 | +        /// </summary>  | 
 | 137 | +        private sealed class EventPipeEvent : Event  | 
 | 138 | +        {  | 
 | 139 | +            private readonly TraceEvent _data;  | 
 | 140 | +            private readonly IList<string> _payloadNames;  | 
 | 141 | +            private readonly IList<object> _payloadValues;  | 
 | 142 | + | 
 | 143 | +            public EventPipeEvent(TraceEvent data)  | 
 | 144 | +            {  | 
 | 145 | +                _data = data;  | 
 | 146 | +                // EventPipe has a discrepancy with ETW for self-describing events - it exposes a single top-level object whereas ETW considers each of the fields within  | 
 | 147 | +                // that object as top-level named fields. To workaround that we unwrap any top-level object at payload index 0.  | 
 | 148 | +                if(data.PayloadNames.Length > 0 && data.PayloadValue(0) is IDictionary<string,object> d)  | 
 | 149 | +                {  | 
 | 150 | +                    _payloadNames = d.Select(kv => kv.Key).ToList();  | 
 | 151 | +                    _payloadValues = d.Select(kv => kv.Value).ToList();  | 
 | 152 | +                }  | 
 | 153 | +                else  | 
 | 154 | +                {  | 
 | 155 | +                    _payloadNames = data.PayloadNames;  | 
 | 156 | +                    _payloadValues = new List<object>();  | 
 | 157 | +                    for(int i = 0; i < _payloadNames.Count; i++)  | 
 | 158 | +                    {  | 
 | 159 | +                        _payloadValues.Add(data.PayloadValue(i));  | 
 | 160 | +                    }  | 
 | 161 | +                }  | 
 | 162 | +            }  | 
 | 163 | + | 
 | 164 | +            public override string ProviderName => _data.ProviderName;  | 
 | 165 | +            public override string EventName => _data.EventName;  | 
 | 166 | +            public override int PayloadCount => _payloadNames.Count;  | 
 | 167 | +            public override IList<string> PayloadNames => _payloadNames;  | 
 | 168 | + | 
 | 169 | +            public override object PayloadValue(int propertyIndex, string propertyName)  | 
 | 170 | +            {  | 
 | 171 | +                if (propertyName != null)  | 
 | 172 | +                {  | 
 | 173 | +                    Assert.Equal(propertyName, _payloadNames[propertyIndex]);  | 
 | 174 | +                }  | 
 | 175 | +                return _payloadValues[propertyIndex];  | 
 | 176 | +            }  | 
 | 177 | +        }  | 
 | 178 | +    }  | 
 | 179 | +}  | 
0 commit comments