Exemplo n.º 1
0
        private async Task <Stream> GetLogsAsync(Action <EventLogsPipelineSettings> settingsCallback = null)
        {
            var outputStream = new MemoryStream();

            await using (var testExecution = StartTraceeProcess(LoggerRemoteTestName))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                using var loggerFactory = new LoggerFactory(new[] { new TestStreamingLoggerProvider(outputStream) });
                var client = new DiagnosticsClient(testExecution.TestRunner.Pid);

                var logSettings = new EventLogsPipelineSettings {
                    Duration = Timeout.InfiniteTimeSpan
                };
                if (null != settingsCallback)
                {
                    settingsCallback(logSettings);
                }
                await using var pipeline = new EventLogsPipeline(client, logSettings, loggerFactory);

                await PipelineTestUtilities.ExecutePipelineWithDebugee(_output, pipeline, testExecution);
            }

            outputStream.Position = 0L;

            return(outputStream);
        }
        public async Task TestLogs()
        {
            var outputStream = new MemoryStream();

            await using (var testExecution = StartTraceeProcess("LoggerRemoteTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                using var loggerFactory = new LoggerFactory(new[] { new TestStreamingLoggerProvider(outputStream) });
                var client = new DiagnosticsClient(testExecution.TestRunner.Pid);

                var logSettings = new EventLogsPipelineSettings {
                    Duration = Timeout.InfiniteTimeSpan
                };
                await using var pipeline = new EventLogsPipeline(client, logSettings, loggerFactory);

                await PipelineTestUtilities.ExecutePipelineWithDebugee(pipeline, testExecution);
            }

            outputStream.Position = 0L;

            Assert.True(outputStream.Length > 0, "No data written by logging process.");

            using var reader = new StreamReader(outputStream);

            string firstMessage = reader.ReadLine();

            Assert.NotNull(firstMessage);

            LoggerTestResult result = JsonSerializer.Deserialize <LoggerTestResult>(firstMessage);

            Assert.Equal("Some warning message with 6", result.Message);
            Assert.Equal("LoggerRemoteTest", result.Category);
            Assert.Equal("Warning", result.LogLevel);
            Assert.Equal("0", result.EventId);
            Validate(result.Scopes, ("BoolValue", "true"), ("StringValue", "test"), ("IntValue", "5"));
            Validate(result.Arguments, ("arg", "6"));

            string secondMessage = reader.ReadLine();

            Assert.NotNull(secondMessage);

            result = JsonSerializer.Deserialize <LoggerTestResult>(secondMessage);
            Assert.Equal("Another message", result.Message);
            Assert.Equal("LoggerRemoteTest", result.Category);
            Assert.Equal("Warning", result.LogLevel);
            Assert.Equal("0", result.EventId);
            Assert.Equal(0, result.Scopes.Count);
            //We are expecting only the original format
            Assert.Equal(1, result.Arguments.Count);
        }
        public async Task TestTraceStopAsync()
        {
            Stream eventStream = null;

            await using (var testExecution = StartTraceeProcess("TraceStopTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client   = new DiagnosticsClient(testExecution.TestRunner.Pid);
                var settings = new EventTracePipelineSettings()
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    Configuration = new CpuProfileConfiguration()
                };

                var foundProviderSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

                await using var pipeline = new EventTracePipeline(client, settings, async(s, token) =>
                {
                    eventStream = s;

                    using var eventSource = new EventPipeEventSource(s);

                    // Dispose event source when cancelled.
                    using var _ = token.Register(() => eventSource.Dispose());

                    eventSource.Dynamic.All += (TraceEvent obj) =>
                    {
                        if (string.Equals(obj.ProviderName, MonitoringSourceConfiguration.SampleProfilerProviderName, StringComparison.OrdinalIgnoreCase))
                        {
                            foundProviderSource.TrySetResult(null);
                        }
                    };

                    await Task.Run(() => Assert.True(eventSource.Process()), token);
                });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(
                    _output,
                    pipeline,
                    testExecution,
                    foundProviderSource);
            }

            //Validate that the stream is only valid for the lifetime of the callback in the trace pipeline.
            Assert.Throws <ObjectDisposedException>(() => eventStream.Read(new byte[4], 0, 4));
        }
        public async Task TestCounterEventPipeline()
        {
            var    expectedCounters = new[] { "cpu-usage", "working-set" };
            string expectedProvider = "System.Runtime";

            IDictionary <string, IEnumerable <string> > expectedMap = new Dictionary <string, IEnumerable <string> >();

            expectedMap.Add(expectedProvider, expectedCounters);

            var foundExpectedCountersSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            var logger = new TestMetricsLogger(expectedMap, foundExpectedCountersSource);

            await using (var testExecution = StartTraceeProcess("CounterRemoteTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client = new DiagnosticsClient(testExecution.TestRunner.Pid);

                await using EventCounterPipeline pipeline = new EventCounterPipeline(client, new EventPipeCounterPipelineSettings
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    CounterGroups = new[]
                    {
                        new EventPipeCounterGroup
                        {
                            ProviderName = expectedProvider,
                            CounterNames = expectedCounters
                        }
                    },
                    CounterIntervalSeconds = 1
                }, new[] { logger });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(
                    _output,
                    pipeline,
                    testExecution,
                    foundExpectedCountersSource);
            }

            Assert.True(logger.Metrics.Any());

            var actualMetrics = logger.Metrics.Select(m => m.Name).OrderBy(m => m);

            Assert.Equal(expectedCounters, actualMetrics);
            Assert.True(logger.Metrics.All(m => string.Equals(m.Provider, expectedProvider)));
        }
        public async Task EventCounterTriggerWithEventPipePipelineTest()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                throw new SkipTestException("https://github.com/dotnet/diagnostics/issues/2568");
            }
            EventCounterTriggerSettings settings = new()
            {
                ProviderName           = EventCounterConstants.RuntimeProviderName,
                CounterName            = EventCounterConstants.CpuUsageCounterName,
                GreaterThan            = 5,
                SlidingWindowDuration  = TimeSpan.FromSeconds(3),
                CounterIntervalSeconds = 1
            };

            await using (var testExecution = StartTraceeProcess("TriggerRemoteTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                DiagnosticsClient client = new(testExecution.TestRunner.Pid);

                TaskCompletionSource <object> waitSource = new(TaskCreationOptions.RunContinuationsAsynchronously);

                await using EventPipeTriggerPipeline <EventCounterTriggerSettings> pipeline = new(
                                client,
                                new EventPipeTriggerPipelineSettings <EventCounterTriggerSettings>
                {
                    Configuration = EventCounterTrigger.CreateConfiguration(settings),
                    TriggerFactory = new EventCounterTriggerFactory(),
                    TriggerSettings = settings,
                    Duration = Timeout.InfiniteTimeSpan
                },
                                traceEvent =>
                {
                    waitSource.TrySetResult(null);
                });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(
                    _output,
                    pipeline,
                    testExecution,
                    waitSource);

                Assert.True(waitSource.Task.IsCompletedSuccessfully);
            }
Exemplo n.º 6
0
        public async Task TestTraceStopAsync()
        {
            using var buffer = new MemoryStream();
            Stream eventStream = null;

            await using (var testExecution = StartTraceeProcess("TraceStopTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client   = new DiagnosticsClient(testExecution.TestRunner.Pid);
                var settings = new EventTracePipelineSettings()
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    Configuration = new CpuProfileConfiguration()
                };

                await using var pipeline = new EventTracePipeline(client, settings, async(s, token) =>
                {
                    await s.CopyToAsync(buffer);
                    eventStream = s;
                });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(pipeline, testExecution);
            }

            //Validate that the stream is only valid for the lifetime of the callback in the trace pipeline.
            Assert.Throws <ObjectDisposedException>(() => eventStream.Read(new byte[4], 0, 4));

            Assert.True(buffer.Length > 0);

            var  eventSource      = new EventPipeEventSource(buffer);
            bool foundCpuProvider = false;

            eventSource.Dynamic.All += (TraceEvent obj) =>
            {
                if (string.Equals(obj.ProviderName, MonitoringSourceConfiguration.SampleProfilerProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    foundCpuProvider = true;
                }
            };
            Assert.True(eventSource.Process());
            Assert.True(foundCpuProvider);
        }
        public async Task TestEventStreamCleanup()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                throw new SkipTestException("Test debugee sigfaults for OSX/Linux");
            }

            Stream eventStream = null;

            using var cancellationTokenSource = new CancellationTokenSource();
            await using (var testExecution = StartTraceeProcess("TestEventStreamCleanup"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client   = new DiagnosticsClient(testExecution.TestRunner.Pid);
                var settings = new EventTracePipelineSettings()
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    Configuration = new CpuProfileConfiguration()
                };

                await using var pipeline = new EventTracePipeline(client, settings, (s, token) =>
                {
                    eventStream = s; //Clients should not do this.
                    cancellationTokenSource.Cancel();
                    token.ThrowIfCancellationRequested();
                    return(Task.CompletedTask);
                });

                await Assert.ThrowsAsync <OperationCanceledException>(
                    async() => await PipelineTestUtilities.ExecutePipelineWithDebugee(
                        _output,
                        pipeline,
                        testExecution,
                        cancellationTokenSource.Token));
            }

            //Validate that the stream is only valid for the lifetime of the callback in the trace pipeline.
            Assert.Throws <ObjectDisposedException>(() => eventStream.Read(new byte[4], 0, 4));
        }
Exemplo n.º 8
0
        public async Task TestTraceStopAsync()
        {
            using var buffer = new MemoryStream();

            await using (var testExecution = StartTraceeProcess("TraceStopTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client   = new DiagnosticsClient(testExecution.TestRunner.Pid);
                var settings = new EventTracePipelineSettings()
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    Configuration = new CpuProfileConfiguration()
                };

                await using var pipeline = new EventTracePipeline(client, settings, async(s, token) =>
                {
                    //The buffer must be read in order to not hang. The Stop message will not be processed otherwise.
                    await s.CopyToAsync(buffer);
                });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(pipeline, testExecution);
            }

            Assert.True(buffer.Length > 0);

            var  eventSource      = new EventPipeEventSource(buffer);
            bool foundCpuProvider = false;

            eventSource.Dynamic.All += (TraceEvent obj) =>
            {
                if (string.Equals(obj.ProviderName, MonitoringSourceConfiguration.SampleProfilerProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    foundCpuProvider = true;
                }
            };
            Assert.True(eventSource.Process());
            Assert.True(foundCpuProvider);
        }
Exemplo n.º 9
0
        public async Task TestCounterEventPipeline()
        {
            var    logger           = new TestMetricsLogger(_output);
            var    expectedCounters = new[] { "cpu-usage", "working-set" };
            string expectedProvider = "System.Runtime";

            await using (var testExecution = StartTraceeProcess("CounterRemoteTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client = new DiagnosticsClient(testExecution.TestRunner.Pid);

                await using EventCounterPipeline pipeline = new EventCounterPipeline(client, new EventPipeCounterPipelineSettings
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    CounterGroups = new[]
                    {
                        new EventPipeCounterGroup
                        {
                            ProviderName = expectedProvider,
                            CounterNames = expectedCounters
                        }
                    },
                    RefreshInterval = TimeSpan.FromSeconds(1)
                }, new[] { logger });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(pipeline, testExecution);
            }

            Assert.True(logger.Metrics.Any());

            var actualMetrics = logger.Metrics.Select(m => m.Name).OrderBy(m => m);

            Assert.Equal(expectedCounters, actualMetrics);
            Assert.True(logger.Metrics.All(m => string.Equals(m.Provider, expectedProvider)));
        }