forked from open-telemetry/opentelemetry-java-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSamplingProfilerTest.java
More file actions
352 lines (297 loc) · 11.9 KB
/
SamplingProfilerTest.java
File metadata and controls
352 lines (297 loc) · 11.9 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.contrib.inferredspans.internal;
import static io.opentelemetry.contrib.inferredspans.internal.semconv.Attributes.LINK_IS_CHILD;
import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat;
import static org.awaitility.Awaitility.await;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.contrib.inferredspans.InferredSpansProcessor;
import io.opentelemetry.contrib.inferredspans.InferredSpansProcessorBuilder;
import io.opentelemetry.contrib.inferredspans.ProfilerTestSetup;
import io.opentelemetry.contrib.inferredspans.internal.util.DisabledOnOpenJ9;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.data.SpanData;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.condition.OS;
// async-profiler doesn't work on Windows
@DisabledOnOs(OS.WINDOWS)
@DisabledOnOpenJ9
class SamplingProfilerTest {
private ProfilerTestSetup setup;
@BeforeEach
void setup() {
// avoids any test failure to make other tests to fail
getProfilerTempFiles().forEach(SamplingProfilerTest::silentDeleteFile);
}
@AfterEach
void tearDown() {
if (setup != null) {
setup.close();
setup = null;
}
getProfilerTempFiles().forEach(SamplingProfilerTest::silentDeleteFile);
}
@Test
void shouldLazilyCreateTempFilesAndCleanThem() throws Exception {
List<Path> tempFiles = getProfilerTempFiles();
assertThat(tempFiles).isEmpty();
// temporary files should be created on-demand, and properly deleted afterwards
setupProfiler(false);
assertThat(setup.profiler.getProfilingSessions())
.describedAs("profiler should not have any session when disabled")
.isEqualTo(0);
assertThat(getProfilerTempFiles())
.describedAs("should not create a temp file when disabled")
.isEmpty();
setup.close();
setup = null;
setupProfiler(true);
awaitProfilerStarted(setup.profiler);
assertThat(getProfilerTempFiles()).describedAs("should have created two temp files").hasSize(2);
setup.close();
setup = null;
assertThat(getProfilerTempFiles())
.describedAs("should delete temp files when profiler is stopped")
.isEmpty();
}
private static List<Path> getProfilerTempFiles() {
Path tempFolder = Paths.get(System.getProperty("java.io.tmpdir"));
try (Stream<Path> files = Files.list(tempFolder)) {
return files
.filter(f -> f.getFileName().toString().startsWith("otel-inferred-"))
.sorted()
.collect(Collectors.toList());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Test
void shouldNotDeleteProvidedFiles() throws Exception {
// when an existing file is provided to the profiler, we should not delete it
// unlike the temporary files that are created by profiler itself
InferredSpansConfiguration defaultConfig;
try (InferredSpansProcessor profiler1 =
InferredSpansProcessor.builder().startScheduledProfiling(false).build()) {
defaultConfig = ProfilerTestSetup.extractProfilerImpl(profiler1).getConfig();
}
Path tempFile1 = Files.createTempFile("otel-inferred-provided", "test.bin");
Path tempFile2 = Files.createTempFile("otel-inferred-provided", "test.jfr");
try (OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().build()) {
SamplingProfiler otherProfiler =
new SamplingProfiler(
defaultConfig,
new FixedClock(),
() -> sdk.getTracer("my-tracer"),
tempFile1.toFile(),
tempFile2.toFile());
otherProfiler.start();
awaitProfilerStarted(otherProfiler);
otherProfiler.stop();
}
assertThat(tempFile1).exists();
assertThat(tempFile2).exists();
}
@Test
void testStartCommand() {
setupProfiler(false);
assertThat(setup.profiler.createStartCommand())
.isEqualTo(
"start,jfr,clock=m,event=wall,nobatch,cstack=n,interval=5ms,filter,file=null,safemode=0");
setup.close();
setupProfiler(config -> config.startScheduledProfiling(false).profilerLoggingEnabled(false));
assertThat(setup.profiler.createStartCommand())
.isEqualTo(
"start,jfr,clock=m,event=wall,nobatch,cstack=n,interval=5ms,filter,file=null,safemode=0,loglevel=none");
setup.close();
setupProfiler(
config ->
config
.startScheduledProfiling(false)
.profilerLoggingEnabled(false)
.samplingInterval(Duration.ofMillis(10))
.asyncProfilerSafeMode(14));
assertThat(setup.profiler.createStartCommand())
.isEqualTo(
"start,jfr,clock=m,event=wall,nobatch,cstack=n,interval=10ms,filter,file=null,safemode=14,loglevel=none");
}
@Test
void testProfileTransaction() throws Exception {
setupProfiler(
config -> config.startScheduledProfiling(true)
// uncomment the following line to enable the backup of the JFR file
// The JFR file can be used as input for the JfrParserTest
// .backupDiagnosticFiles(true)
);
awaitProfilerStarted(setup.profiler);
Tracer tracer = setup.sdk.getTracer("manual-spans");
boolean profilingActiveOnThread;
Span tx = tracer.spanBuilder("transaction").startSpan();
try (Scope scope = tx.makeCurrent()) {
// makes sure that the rest will be captured by another profiling session
// this tests that restoring which threads to profile works
Thread.sleep(600);
profilingActiveOnThread = setup.profiler.isProfilingActiveOnThread(Thread.currentThread());
aInferred(tracer);
} finally {
tx.end();
}
await()
.pollDelay(Duration.ofMillis(10))
.timeout(Duration.ofSeconds(5))
.untilAsserted(() -> assertThat(setup.getSpans()).hasSizeGreaterThanOrEqualTo(6));
assertThat(profilingActiveOnThread).isTrue();
Optional<SpanData> txData =
setup.getSpans().stream().filter(s -> s.getName().equals("transaction")).findAny();
assertThat(txData).isPresent();
assertThat(txData.get()).hasNoParent();
Optional<SpanData> testProfileTransaction =
setup.getSpans().stream()
.filter(s -> s.getName().equals("SamplingProfilerTest#testProfileTransaction"))
.findAny();
assertThat(testProfileTransaction).isPresent();
assertThat(testProfileTransaction.get()).hasParent(txData.get());
Optional<SpanData> inferredSpanA =
setup.getSpans().stream()
.filter(s -> s.getName().equals("SamplingProfilerTest#aInferred"))
.findAny();
assertThat(inferredSpanA).isPresent();
assertThat(inferredSpanA.get()).hasParent(testProfileTransaction.get());
Optional<SpanData> explicitSpanB =
setup.getSpans().stream().filter(s -> s.getName().equals("bExplicit")).findAny();
assertThat(explicitSpanB).isPresent();
assertThat(explicitSpanB.get()).hasParent(txData.get());
assertThat(inferredSpanA.get().getLinks())
.hasSize(1)
.anySatisfy(
link -> {
assertThat(link.getAttributes()).containsEntry(LINK_IS_CHILD, true);
SpanData expectedSpan = explicitSpanB.get();
Assertions.assertThat(link.getSpanContext().getTraceId())
.isEqualTo(expectedSpan.getTraceId());
Assertions.assertThat(link.getSpanContext().getSpanId())
.isEqualTo(expectedSpan.getSpanId());
});
Optional<SpanData> inferredSpanC =
setup.getSpans().stream()
.filter(s -> s.getName().equals("SamplingProfilerTest#cInferred"))
.findAny();
assertThat(inferredSpanC).isPresent();
assertThat(inferredSpanC.get()).hasParent(explicitSpanB.get());
Optional<SpanData> inferredSpanD =
setup.getSpans().stream()
.filter(s -> s.getName().equals("SamplingProfilerTest#dInferred"))
.findAny();
assertThat(inferredSpanD).isPresent();
assertThat(inferredSpanD.get()).hasParent(inferredSpanC.get());
}
@Test
@DisabledForJreRange(max = JRE.JAVA_20)
void testVirtualThreadsExcluded() throws Exception {
setupProfiler(true);
awaitProfilerStarted(setup.profiler);
Tracer tracer = setup.sdk.getTracer("manual-spans");
AtomicReference<Boolean> profilingActive = new AtomicReference<>();
Runnable task =
() -> {
Span tx = tracer.spanBuilder("transaction").startSpan();
try (Scope scope = tx.makeCurrent()) {
profilingActive.set(setup.profiler.isProfilingActiveOnThread(Thread.currentThread()));
} finally {
tx.end();
}
};
Method startVirtualThread = Thread.class.getMethod("startVirtualThread", Runnable.class);
Thread virtual = (Thread) startVirtualThread.invoke(null, task);
virtual.join();
assertThat(profilingActive.get()).isFalse();
}
@Test
void testPostProcessingDisabled() throws Exception {
setupProfiler(config -> config.postProcessingEnabled(false));
awaitProfilerStarted(setup.profiler);
Tracer tracer = setup.sdk.getTracer("manual-spans");
Span tx = tracer.spanBuilder("transaction").startSpan();
try (Scope scope = tx.makeCurrent()) {
// makes sure that the rest will be captured by another profiling session
// this tests that restoring which threads to profile works
Thread.sleep(600);
aInferred(tracer);
} finally {
tx.end();
}
await()
.pollDelay(Duration.ofMillis(10))
.timeout(Duration.ofSeconds(5))
.untilAsserted(() -> assertThat(setup.getSpans()).hasSize(2));
Optional<SpanData> explicitSpanB =
setup.getSpans().stream().filter(s -> s.getName().equals("bExplicit")).findAny();
assertThat(explicitSpanB).isPresent();
assertThat(explicitSpanB.get()).hasParentSpanId(tx.getSpanContext().getSpanId());
}
private static void aInferred(Tracer tracer) throws Exception {
Span span = tracer.spanBuilder("bExplicit").startSpan();
try (Scope spanScope = span.makeCurrent()) {
cInferred();
} finally {
span.end();
}
Thread.sleep(50);
}
private static void cInferred() throws Exception {
dInferred();
Thread.sleep(50);
}
private static void dInferred() throws Exception {
Thread.sleep(50);
}
private void setupProfiler(boolean enabled) {
setupProfiler(config -> config.startScheduledProfiling(enabled));
}
private void setupProfiler(Consumer<InferredSpansProcessorBuilder> configCustomizer) {
setup =
ProfilerTestSetup.create(
config -> {
config
.profilingDuration(Duration.ofMillis(500))
.profilerInterval(Duration.ofMillis(500))
.samplingInterval(Duration.ofMillis(5));
configCustomizer.accept(config);
});
}
private static void awaitProfilerStarted(SamplingProfiler profiler) {
// ensure profiler is initialized
await()
.pollDelay(Duration.ofMillis(10))
.timeout(Duration.ofSeconds(6))
.until(() -> profiler.getProfilingSessions() > 1);
}
private static void silentDeleteFile(Path f) {
try {
Files.delete(f);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}