-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathEventCounterPipelineUnitTests.cs
213 lines (182 loc) · 9.13 KB
/
EventCounterPipelineUnitTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Diagnostics.NETCore.Client;
using Microsoft.Diagnostics.TestHelpers;
using Xunit;
using Xunit.Abstractions;
using Xunit.Extensions;
using TestRunner = Microsoft.Diagnostics.CommonTestRunner.TestRunner;
// Newer SDKs flag MemberData(nameof(Configurations)) with this error
// Avoid unnecessary zero-length array allocations. Use Array.Empty<object>() instead.
#pragma warning disable CA1825
namespace Microsoft.Diagnostics.Monitoring.EventPipe.UnitTests
{
public class EventCounterPipelineUnitTests
{
private readonly ITestOutputHelper _output;
public static IEnumerable<object[]> Configurations => TestRunner.Configurations;
public EventCounterPipelineUnitTests(ITestOutputHelper output)
{
_output = output;
}
class ExpectedCounter
{
public string ProviderName { get; }
public string CounterName { get; }
public string MeterTags { get; }
public string InstrumentTags { get; }
public ExpectedCounter(string providerName, string counterName, string meterTags = null, string instrumentTags = null)
{
ProviderName = providerName;
CounterName = counterName;
MeterTags = meterTags;
InstrumentTags = instrumentTags;
}
public bool MatchesCounterMetadata(CounterMetadata metadata)
{
if (metadata.ProviderName != ProviderName) return false;
if (metadata.CounterName != CounterName) return false;
if (MeterTags != null && metadata.MeterTags != MeterTags) return false;
if (InstrumentTags != null && metadata.InstrumentTags != InstrumentTags) return false;
return true;
}
}
private sealed class TestMetricsLogger : ICountersLogger
{
private readonly List<ExpectedCounter> _expectedCounters = new();
private Dictionary<ExpectedCounter, ICounterPayload> _metrics = new();
private readonly TaskCompletionSource<object> _foundExpectedCountersSource;
private readonly ITestOutputHelper _output;
public TestMetricsLogger(IEnumerable<ExpectedCounter> expectedCounters, TaskCompletionSource<object> foundExpectedCountersSource, ITestOutputHelper output)
{
_foundExpectedCountersSource = foundExpectedCountersSource;
_expectedCounters = new(expectedCounters);
if (_expectedCounters.Count == 0)
{
foundExpectedCountersSource.SetResult(null);
}
_output = output;
}
public IEnumerable<ICounterPayload> Metrics => _metrics.Values;
public void Log(ICounterPayload payload)
{
bool isValuePayload = payload.EventType switch
{
EventType.Gauge => true,
EventType.UpDownCounter => true,
EventType.Histogram => true,
EventType.Rate => true,
_ => false
};
if(!isValuePayload)
{
return;
}
ExpectedCounter expectedCounter = _expectedCounters.Find(c => c.MatchesCounterMetadata(payload.CounterMetadata));
if(expectedCounter != null)
{
_expectedCounters.Remove(expectedCounter);
_metrics.Add(expectedCounter, payload);
_output.WriteLine($"Found expected counter: {expectedCounter.ProviderName}/{expectedCounter.CounterName}. Counters remaining={_expectedCounters.Count}");
// Complete the task source if the last expected key was removed.
if (_expectedCounters.Count == 0)
{
_output.WriteLine($"All expected counters have been received. Signaling pipeline can exit.");
_foundExpectedCountersSource.TrySetResult(null);
}
}
else
{
_output.WriteLine($"Received additional counter event: {payload.CounterMetadata.ProviderName}/{payload.CounterMetadata.CounterName}");
}
}
public Task PipelineStarted(CancellationToken token)
{
_output.WriteLine("Counters pipeline is running. Waiting to receive expected counters from tracee.");
return Task.CompletedTask;
}
public Task PipelineStopped(CancellationToken token) => Task.CompletedTask;
}
[SkippableTheory, MemberData(nameof(Configurations))]
public async Task TestCounterEventPipeline(TestConfiguration config)
{
string[] expectedCounters = new[] { "cpu-usage", "working-set" };
string expectedProvider = "System.Runtime";
TaskCompletionSource<object> foundExpectedCountersSource = new(TaskCreationOptions.RunContinuationsAsynchronously);
TestMetricsLogger logger = new(expectedCounters.Select(name => new ExpectedCounter(expectedProvider, name)), foundExpectedCountersSource, _output);
await using (TestRunner testRunner = await PipelineTestUtilities.StartProcess(config, "CounterRemoteTest", _output))
{
DiagnosticsClient client = new(testRunner.Pid);
await using MetricsPipeline pipeline = new(client, new MetricsPipelineSettings
{
Duration = Timeout.InfiniteTimeSpan,
CounterGroups = new[]
{
new EventPipeCounterGroup
{
ProviderName = expectedProvider,
CounterNames = expectedCounters,
Type = CounterGroupType.EventCounter
}
},
CounterIntervalSeconds = 1
}, new[] { logger });
await PipelineTestUtilities.ExecutePipelineWithTracee(
pipeline,
testRunner,
foundExpectedCountersSource);
}
Assert.True(logger.Metrics.Any());
IOrderedEnumerable<string> actualMetrics = logger.Metrics.Select(m => m.CounterMetadata.CounterName).OrderBy(m => m);
Assert.Equal(expectedCounters, actualMetrics);
Assert.True(logger.Metrics.All(m => string.Equals(m.CounterMetadata.ProviderName, expectedProvider)));
}
[SkippableTheory, MemberData(nameof(Configurations))]
public async Task TestDuplicateNameMetrics(TestConfiguration config)
{
if(config.RuntimeFrameworkVersionMajor < 9)
{
throw new SkipTestException("MetricsEventSource only supports instrument IDs starting in .NET 9.0.");
}
string providerName = "AmbiguousNameMeter";
string counterName = "AmbiguousNameCounter";
ExpectedCounter[] expectedCounters =
[
new ExpectedCounter(providerName, counterName, "MeterTag=one","InstrumentTag=A"),
new ExpectedCounter(providerName, counterName, "MeterTag=one","InstrumentTag=B"),
new ExpectedCounter(providerName, counterName, "MeterTag=two","InstrumentTag=A"),
new ExpectedCounter(providerName, counterName, "MeterTag=two","InstrumentTag=B"),
];
TaskCompletionSource<object> foundExpectedCountersSource = new(TaskCreationOptions.RunContinuationsAsynchronously);
TestMetricsLogger logger = new(expectedCounters, foundExpectedCountersSource, _output);
await using (TestRunner testRunner = await PipelineTestUtilities.StartProcess(config, "DuplicateNameMetrics", _output))
{
DiagnosticsClient client = new(testRunner.Pid);
await using MetricsPipeline pipeline = new(client, new MetricsPipelineSettings
{
Duration = Timeout.InfiniteTimeSpan,
CounterGroups = new[]
{
new EventPipeCounterGroup
{
ProviderName = providerName,
CounterNames = [counterName]
}
},
CounterIntervalSeconds = 1,
MaxTimeSeries = 1000
}, new[] { logger });
await PipelineTestUtilities.ExecutePipelineWithTracee(
pipeline,
testRunner,
foundExpectedCountersSource);
}
// confirm that all four tag combinations published a value
Assert.Equal(4, logger.Metrics.Count());
}
}
}