public void then_session_is_started()
            {
                bool sessionCreated = TraceEventSession.GetActiveSessionNames().
                                      Any(s => s.StartsWith(this.traceEventServiceSettings.SessionNamePrefix, StringComparison.OrdinalIgnoreCase));

                Assert.IsTrue(sessionCreated);
            }
Beispiel #2
0
        /// <summary>
        /// Stops the current ETW session.
        /// </summary>
        public void Stop()
        {
            if (this.eventSource != null)
            {
                this.eventSource.StopProcessing();
                this.eventSource.Dispose();
                this.eventSource = null;
            }

            if (this.eventSession != null)
            {
                this.eventSession.Stop(true);
                this.eventSession.Dispose();
                this.eventSession = null;
            }

            if (TraceEventSession.GetActiveSessionNames().Contains(this.name, StringComparer.OrdinalIgnoreCase))
            {
                using (TraceEventSession session = new TraceEventSession(this.name))
                {
                    session.Stop(true);
                }
            }

            this.isStarted = false;
        }
Beispiel #3
0
        private string CleanupMatchingSessions(string sessionNamePrefix, bool keepOne)
        {
            string result = null;

            foreach (var sesName in TraceEventSession.GetActiveSessionNames())
            {
                if (!sesName.StartsWith(sessionNamePrefix, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                var session = TraceEventSession.GetActiveSession(sesName);
                if (session == null || !session.IsRealTime)
                {
                    continue;
                }

                if (keepOne && result == null)
                {
                    result = session.SessionName;
                }
                else
                {
                    session.Dispose();
                }
            }

            return(result);
        }
 protected void RemoveAnyExistingSession(string sessionName = Constants.DefaultSessionNamePrefix)
 {
     TraceEventSession.GetActiveSessionNames().
     Where(s => s.StartsWith(sessionName, StringComparison.OrdinalIgnoreCase)).ToList().
     ForEach(n => new TraceEventSession(n)
     {
         StopOnDispose = true
     }.Dispose());
 }
Beispiel #5
0
        static void Main(string[] args)
        {
            // list ETW sessions
            Console.WriteLine("Current ETW sessions:");
            foreach (var session in TraceEventSession.GetActiveSessionNames())
            {
                Console.WriteLine(session);
            }
            Console.WriteLine("--------------------------------------------");


            string sessionName = "EtwSessionForCLR_" + Guid.NewGuid().ToString();

            Console.WriteLine($"Starting {sessionName}...\r\n");
            using (TraceEventSession userSession = new TraceEventSession(sessionName, TraceEventSessionOptions.Create))
            {
                Task.Run(() =>
                {
                    // register handlers for events on the session source
                    // --> listen to all CLR events
                    userSession.Source.Clr.All += delegate(TraceEvent data)
                    {
                        // skip verbose and unneeded events
                        if (SkipEvent(data))
                        {
                            return;
                        }

                        // raw dump of the events
                        Console.WriteLine($"{data.ProcessID,7}___[{data.ID} | {data.OpcodeName}] {data.EventName} <| {data.GetType().Name}");
                    };

                    // decide which provider to listen to with filters if needed
                    userSession.EnableProvider(
                        ClrTraceEventParser.ProviderGuid,  // CLR provider
                        TraceEventLevel.Verbose,
                        (ulong)(
                            ClrTraceEventParser.Keywords.Contention |           // thread contention timing
                            ClrTraceEventParser.Keywords.Threading |            // threadpool events
                            ClrTraceEventParser.Keywords.Exception |            // get the first chance exceptions
                            ClrTraceEventParser.Keywords.GCHeapAndTypeNames |   // for finalizer and exceptions type names
                            ClrTraceEventParser.Keywords.Type |                 // for finalizer and exceptions type names
                            ClrTraceEventParser.Keywords.GC                     // garbage collector details
                            )
                        );

                    // this is a blocking call until the session is disposed
                    userSession.Source.Process();
                    Console.WriteLine("End of session");
                });

                // wait for the user to dismiss the session
                Console.WriteLine("Presse ENTER to exit...");
                Console.ReadLine();
            }
        }
        private static void CloseExistingSession(string name)
        {
            HashSet <string> sessionNames = new HashSet <string>(TraceEventSession.GetActiveSessionNames());

            if (sessionNames.Contains(name))
            {
                using (TraceEventSession existingSession = new TraceEventSession(name))
                {
                    existingSession.StopOnDispose = true;
                }
            }
        }
 public void TestInit()
 {
     foreach (var sessionName in TraceEventSession.GetActiveSessionNames())
     {
         if (sessionName.ToString().StartsWith("ServiceReconfig"))
         {
             new TraceEventSession(sessionName)
             {
                 StopOnDispose = true
             }.Dispose();
         }
     }
 }
Beispiel #8
0
        public static void ClearAllActiveObservableEventListenerSession()
        {
            var activeSessions = TraceEventSession.GetActiveSessionNames()
                                 .Where(x => x.StartsWith("ObservableEventListener"))
                                 .Select(x => TraceEventSession.GetActiveSession(x));
            var activeCount = 0;

            foreach (var item in activeSessions)
            {
                item.Dispose();
                activeCount++;
            }
            Console.WriteLine("Cleared ActiveSession's Count:" + activeCount);
        }
Beispiel #9
0
 public void Cleanup()
 {
     try
     {
         // This clean up is there to clean up possible left over trace event sessions during the Debug of the unit tests.
         foreach (var name in TraceEventSession.GetActiveSessionNames().Where(n => n.StartsWith("ApplicationInsights-", StringComparison.Ordinal)))
         {
             TraceEventSession.GetActiveSession(name).Stop();
         }
     }
     catch
     {
         // This should normally not happen. But if this happens, there's, unfortunately, nothing too much we can do here.
     }
 }
Beispiel #10
0
        private static bool PollUntil(Func <IEnumerable <string>, bool> pollUntilCondition)
        {
            var timeoutToWaitUntilEventIsReceived = DateTime.UtcNow.AddSeconds(10);

            while (DateTime.UtcNow < timeoutToWaitUntilEventIsReceived)
            {
                var activeSessionNames = TraceEventSession.GetActiveSessionNames();
                if (pollUntilCondition(activeSessionNames))
                {
                    return(true);
                }

                Task.Delay(200).Wait();
            }

            return(false);
        }
        public static int ClearAllActiveObservableEventListenerSessions()
        {
            var activeSessions = TraceEventSession
                                 .GetActiveSessionNames()
                                 .Where(x => x.StartsWith("ObservableEventListener"))
                                 .Select(TraceEventSession.GetActiveSession);

            var activeCount = 0;

            foreach (var item in activeSessions)
            {
                item.Dispose();

                activeCount++;
            }

            return(activeCount);
        }
        public static int ClearActiveObservableEventListenerSession(string sessionName)
        {
            var activeSessions = TraceEventSession
                                 .GetActiveSessionNames()
                                 .Where(x => x.Equals(sessionName))
                                 .Select(TraceEventSession.GetActiveSession);

            var activeCount = 0;

            foreach (var item in activeSessions)
            {
                item.Dispose();

                activeCount++;
            }

            return(activeCount);
        }
Beispiel #13
0
        internal static TraceEventSession CreateSession(string sessionName)
        {
            if (TraceEventSession.GetActiveSessionNames().Contains(sessionName, StringComparer.OrdinalIgnoreCase))
            {
                // Notify of session removal
                SemanticLoggingEventSource.Log.TraceEventServiceSessionRemoved(sessionName);

                // Remove existing session
                new TraceEventSession(sessionName)
                {
                    StopOnDispose = true
                }.Dispose();
            }

            return(new TraceEventSession(sessionName, null)
            {
                StopOnDispose = true
            });
        }
Beispiel #14
0
        public CollectTraceEventsHelper(CommandLineOptions options)
        {
            if (TraceEventSession.IsElevated() != true)
            {
                throw new InvalidOperationException("Collecting perf events requires administrative privileges.");
            }

            if (options.ClrEvents.Events == ClrTraceEventParser.Keywords.None && options.KernelEvents == KernelTraceEventParser.Keywords.None)
            {
                throw new PowerArgs.ArgException("Must specify at least one CLR or kernel event.");
            }

            // verify session name
            var existingSessions = TraceEventSession.GetActiveSessionNames();

            if (options.Mode == ExecutionMode.Start && existingSessions.Contains(options.TestName))
            {
                throw new InvalidOperationException(string.Format("The session name '{0}' is already in use.", options.TestName));
            }
            else if (options.Mode == ExecutionMode.Stop && !existingSessions.Contains(options.TestName))
            {
                throw new InvalidOperationException(string.Format("The session name '{0}' does not exist.", options.TestName));
            }

            m_traceSession = new TraceEventSession(options.TestName, options.DataFile);

            if (options.Mode == ExecutionMode.Start)
            {
                m_traceSession.BufferSizeMB = 512;

                // starting a new session, enable providers
                m_traceSession.EnableKernelProvider(options.KernelEvents);
                m_traceSession.EnableProvider(ClrTraceEventParser.ProviderGuid, TraceEventLevel.Informational, (ulong)options.ClrEvents.Events);

                // keep the session active after the process terminates
                m_traceSession.StopOnDispose = false;
            }
        }
Beispiel #15
0
        private static void WorkerTraceEvents(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (TraceEventSession.IsElevated() != true)
                {
                    throw new InvalidOperationException(
                              "Collecting ETW trace events requires administrative privileges.");
                }

                if (TraceEventSession.GetActiveSessionNames().Contains(SessionName))
                {
                    Debug.WriteLine(
                        $"The session name '{SessionName}' is already in use, stopping existing and restart a new one.");
                    TraceEventSession.GetActiveSession(SessionName).Stop(true);
                }

                // An End-To-End ETW Tracing Example: EventSource and TraceEvent
                // https://blogs.msdn.microsoft.com/vancem/2012/12/20/an-end-to-end-etw-tracing-example-eventsource-and-traceevent/
                using (var traceEventSession = new TraceEventSession(SessionName))
                {
                    traceEventSession.StopOnDispose = true;
                    using (var traceEventSource = new ETWTraceEventSource(SessionName, TraceEventSourceType.Session))
                    {
                        traceEventSession.EnableProvider(OmaDmClient);
                        traceEventSession.EnableProvider(OmaDmClientProvider);

                        new RegisteredTraceEventParser(traceEventSource).All += (data =>
                                                                                 (sender as BackgroundWorker)?.ReportProgress(0, data.Clone()));
                        traceEventSource.Process();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception: {ex}");
            }
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                int.TryParse(args[0], out s_pid);
            }
            if (s_pid == 0)
            {
                s_pid = 20688;
            }

            // list ETW sessions
            Console.WriteLine("Current ETW sessions:");
            foreach (var session in TraceEventSession.GetActiveSessionNames())
            {
                Console.WriteLine(session);
            }
            Console.WriteLine("--------------------------------------------");

            string sessionName = "EtwSessionForCLR_" + Guid.NewGuid().ToString();

            Console.WriteLine($"Starting {sessionName}...\r\n");
            using (TraceEventSession userSession = new TraceEventSession(sessionName, TraceEventSessionOptions.Create))
            {
                Task.Run(() =>
                {
                    // register handlers for events on the session source

                    // listen to all CLR events
                    userSession.Source.Clr.All += delegate(TraceEvent data)
                    {
                        // skip verbose and unneeded events
                        if (SkipEvent(data))
                        {
                            return;
                        }

                        // raw dump of the events
                        //Console.WriteLine($"{data.ProcessID,7} <{data.ProviderName}:{data.ID}>\r\n   ___[{(int)data.Opcode}|{data.OpcodeName}] {data.EventName} <| {data.GetType().Name}\r\n");
                        //Console.WriteLine($"\r\n   ___[{(int)data.Opcode}|{data.OpcodeName}] {data.EventName} <| {data.GetType().Name}");
                    };

                    userSession.Source.Clr.AppDomainResourceManagementThreadCreated += delegate(ThreadCreatedTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($"^ {process.Threads.Count}");
                    };

                    userSession.Source.Clr.AppDomainResourceManagementThreadTerminated += delegate(ThreadTerminatedOrTransitionTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($"v {process.Threads.Count}");
                    };

                    userSession.Source.Clr.ThreadPoolWorkerThreadAdjustmentAdjustment += delegate(ThreadPoolWorkerThreadAdjustmentTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($". {process.Threads.Count} | {data.NewWorkerThreadCount} threads due to {data.Reason.ToString()}");
                    };

                    userSession.Source.Clr.ThreadPoolWorkerThreadStart += delegate(ThreadPoolWorkerThreadTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($"+ {process.Threads.Count} | {data.ActiveWorkerThreadCount + data.RetiredWorkerThreadCount} = {data.ActiveWorkerThreadCount} + {data.RetiredWorkerThreadCount} threads");
                    };

                    userSession.Source.Clr.ThreadPoolWorkerThreadStop += delegate(ThreadPoolWorkerThreadTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($"- {process.Threads.Count} | {data.ActiveWorkerThreadCount + data.RetiredWorkerThreadCount}  = {data.ActiveWorkerThreadCount} + {data.RetiredWorkerThreadCount} threads");
                    };

                    //userSession.Source.Clr.ThreadPoolIOEnqueue += delegate (ThreadPoolIOWorkEnqueueTraceData data)
                    //{
                    //    Process process = Process.GetProcessById(s_pid);
                    //    Console.WriteLine($"e {process.Threads.Count}");
                    //};

                    //userSession.Source.Clr.ThreadPoolIODequeue += delegate (ThreadPoolIOWorkTraceData data)
                    //{
                    //    Process process = Process.GetProcessById(s_pid);
                    //    Console.WriteLine($"d {process.Threads.Count}");
                    //};

                    userSession.Source.Clr.IOThreadCreationStart += delegate(IOThreadTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($"$ {process.Threads.Count} | {data.IOThreadCount + data.RetiredIOThreads}  = {data.IOThreadCount} + {data.RetiredIOThreads} threads");
                    };

                    userSession.Source.Clr.IOThreadCreationStop += delegate(IOThreadTraceData data)
                    {
                        Process process = Process.GetProcessById(s_pid);
                        if (s_pid != data.ProcessID)
                        {
                            return;
                        }
                        Console.WriteLine($"# {process.Threads.Count} | {data.IOThreadCount + data.RetiredIOThreads}  = {data.IOThreadCount} + {data.RetiredIOThreads} threads");
                    };


                    //userSession.Source.Dynamic.All += delegate (TraceEvent data)
                    //{
                    //    // skip verbose and unneeded events
                    //    if (SkipEvent(data))
                    //        return;

                    //    // raw dump of the events
                    //    //Console.WriteLine($"{data.ProcessID,7} <{data.ProviderName}:{data.ID}>\r\n   ___[{(int)data.Opcode}|{data.OpcodeName}] {data.EventName} <| {data.GetType().Name}\r\n");
                    //    //Console.WriteLine($"\r\n   ...[{(int)data.Opcode}|{data.OpcodeName}] {data.EventName} <| {data.GetType().Name}");
                    //};

                    // decide which provider to listen to with filters if needed
                    userSession.EnableProvider(
                        ClrTraceEventParser.ProviderGuid,  // CLR provider
                        TraceEventLevel.Verbose,
                        (ulong)(
                            ClrTraceEventParser.Keywords.AppDomainResourceManagement | // thread termination event
                            ClrTraceEventParser.Keywords.Contention |                  // thread contention timing
                            ClrTraceEventParser.Keywords.Threading |                   // threadpool events
                            ClrTraceEventParser.Keywords.Exception |                   // get the first chance exceptions
                            ClrTraceEventParser.Keywords.GCHeapAndTypeNames |          // for finalizer and exceptions type names
                            ClrTraceEventParser.Keywords.Type |                        // for finalizer and exceptions type names
                            ClrTraceEventParser.Keywords.GC                            // garbage collector details
                            )
                        );

                    // this is a blocking call until the session is disposed
                    userSession.Source.Process();
                    Console.WriteLine("End of session");
                });

                // wait for the user to dismiss the session
                Console.WriteLine("Presse ENTER to exit...");
                Console.ReadLine();
            }
        }
 protected bool IsCreatedSessionAlive()
 {
     return(TraceEventSession.GetActiveSessionNames().Any(s =>
                                                          s.StartsWith(this.configuration.Settings.SessionNamePrefix, StringComparison.OrdinalIgnoreCase)));
 }
Beispiel #18
0
 /// <summary>
 /// Get all active ETW sessions
 /// </summary>
 /// <returns>string array of with the trace session names</returns>
 public string[] GetTraceSessions()
 {
     return(TraceEventSession.GetActiveSessionNames().ToArray());
 }
Beispiel #19
0
        public static bool WaitAndAssertCountOfSessions(string sessionNamePrefix, int countOfSessions)
        {
            var allSessionsHaveStarted = PollUntil(sessionNames => sessionNames.Count(name => name.StartsWith(sessionNamePrefix)) == countOfSessions);

            if (allSessionsHaveStarted)
            {
                return(true);
            }

            throw new TimeoutException(countOfSessions + " sessions with the prefix '" + sessionNamePrefix + "' have not started within time. These are the active sessions: " + string.Join(", ", TraceEventSession.GetActiveSessionNames()));
        }