Skip to content

Commit

Permalink
Create PinnedThreadValidation
Browse files Browse the repository at this point in the history
Signed-off-by: Jorge Bescos Gascon <jorge.bescos.gascon@oracle.com>
  • Loading branch information
jbescos authored and danielkec committed Dec 19, 2024
1 parent 660d541 commit 2513001
Show file tree
Hide file tree
Showing 12 changed files with 474 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.microprofile.testing.junit5;

import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingStream;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

/**
* JUnit5 extension to support pinned threads validation.
*/
class HelidonPinnedThreadValidationJunitExtension implements BeforeAllCallback, AfterAllCallback {

private RecordingStream recordingStream;
private boolean pinnedThreadValidation;
private PinningException pinningException;

@Override
public void beforeAll(ExtensionContext context) throws Exception {
Class<?> testClass = context.getRequiredTestClass();
pinnedThreadValidation = testClass.getAnnotation(PinnedThreadValidation.class) != null;
if (pinnedThreadValidation) {
recordingStream = new RecordingStream();
recordingStream.enable("jdk.VirtualThreadPinned").withStackTrace();
recordingStream.onEvent("jdk.VirtualThreadPinned", this::record);
recordingStream.startAsync();
}
}

void record(RecordedEvent event) {
PinningException e = new PinningException(event);
if (pinningException == null) {
pinningException = e;
} else {
pinningException.addSuppressed(e);
}
}

@Override
public void afterAll(ExtensionContext context) {
if (pinnedThreadValidation) {
try {
// Flush ending events
recordingStream.stop();
if (pinningException != null) {
throw pinningException;
}
} finally {
recordingStream.close();
}
}
}

private static class PinningException extends AssertionError {
private final RecordedEvent recordedEvent;

PinningException(RecordedEvent recordedEvent) {
this.recordedEvent = recordedEvent;
if (recordedEvent.getStackTrace() != null) {
StackTraceElement[] stackTraceElements = recordedEvent.getStackTrace().getFrames().stream()
.map(f -> new StackTraceElement(f.getMethod().getType().getName(),
f.getMethod().getName(),
f.getMethod().getType().getName() + ".java",
f.getLineNumber()))
.toArray(StackTraceElement[]::new);
super.setStackTrace(stackTraceElements);
}
}

@Override
public String getMessage() {
return "Pinned virtual threads were detected:\n"
+ recordedEvent.toString();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.microprofile.testing.junit5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.extension.ExtendWith;

/**
* An annotation making this test class to fail at the end if a pinned virtual thread was detected.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ExtendWith(HelidonPinnedThreadValidationJunitExtension.class)
@Inherited
public @interface PinnedThreadValidation {
}
1 change: 1 addition & 0 deletions microprofile/testing/junit5/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
requires io.helidon.microprofile.cdi;
requires jakarta.inject;
requires org.junit.jupiter.api;
requires jdk.jfr;

requires transitive jakarta.cdi;
requires transitive jakarta.ws.rs;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import jakarta.ws.rs.client.ClientBuilder;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingStream;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
Expand Down Expand Up @@ -88,23 +90,29 @@ public class HelidonTestNgListener implements IClassListener, ITestListener {
private List<AddExtension> classLevelExtensions = new ArrayList<>();
private List<AddBean> classLevelBeans = new ArrayList<>();
private ConfigMeta classLevelConfigMeta = new ConfigMeta();
private RecordingStream recordingStream;
private boolean classLevelDisableDiscovery = false;
private boolean resetPerTest;
private boolean pinnedThreadValidation;

private Class<?> testClass;
private Object testInstance;
private ConfigProviderResolver configProviderResolver;
private Config config;
private SeContainer container;
private PinningException pinningException;

@Override
public void onBeforeClass(ITestClass iTestClass) {

testClass = iTestClass.getRealClass();

List<Annotation> metaAnnotations = extractMetaAnnotations(testClass);

AddConfig[] configs = getAnnotations(testClass, AddConfig.class, metaAnnotations);
pinnedThreadValidation = testClass.getAnnotation(PinnedThreadValidation.class) != null;
startRecordingStream();

AddConfig[] configs = getAnnotations(testClass, AddConfig.class);
classLevelConfigMeta.addConfig(configs);
classLevelConfigMeta.configuration(getAnnotation(testClass, Configuration.class, metaAnnotations));
classLevelConfigMeta.addConfigBlock(getAnnotation(testClass, AddConfigBlock.class, metaAnnotations));
Expand Down Expand Up @@ -161,6 +169,7 @@ public void onAfterClass(ITestClass testClass) {
releaseConfig();
stopContainer();
}
closeRecordingStream();
}

@Override
Expand Down Expand Up @@ -358,6 +367,30 @@ private <T extends Annotation> T getAnnotation(Class<?> testClass, Class<T> anno
return annotation;
}

private void startRecordingStream() {
if (pinnedThreadValidation) {
pinningException = null;
recordingStream = new RecordingStream();
recordingStream.enable("jdk.VirtualThreadPinned").withStackTrace();
recordingStream.onEvent("jdk.VirtualThreadPinned", this::record);
recordingStream.startAsync();
}
}

private void closeRecordingStream() {
if (pinnedThreadValidation) {
try {
// Flush ending events
recordingStream.stop();
if (pinningException != null) {
throw pinningException;
}
} finally {
recordingStream.close();
}
}
}

@SuppressWarnings("unchecked")
private <T extends Annotation> T[] getAnnotations(Class<?> testClass, Class<T> annotClass,
List<Annotation> metaAnnotations) {
Expand Down Expand Up @@ -431,6 +464,15 @@ private static boolean hasAnnotation(AnnotatedElement element, Set<Class<? exten
return false;
}

void record(RecordedEvent event) {
PinningException e = new PinningException(event);
if (pinningException == null) {
pinningException = e;
} else {
pinningException.addSuppressed(e);
}
}

@SuppressWarnings("CdiManagedBeanInconsistencyInspection")
private record TestInstanceExtension(Object testInstance, Class<?> testClass) implements Extension {

Expand Down Expand Up @@ -645,4 +687,28 @@ public Class<? extends Extension> value() {
private static final class SingletonLiteral extends AnnotationLiteral<Singleton> implements Singleton {
static final SingletonLiteral INSTANCE = new SingletonLiteral();
}

private static class PinningException extends AssertionError {
private final RecordedEvent recordedEvent;

PinningException(RecordedEvent recordedEvent) {
this.recordedEvent = recordedEvent;
if (recordedEvent.getStackTrace() != null) {
StackTraceElement[] stackTraceElements = recordedEvent.getStackTrace().getFrames().stream()
.map(f -> new StackTraceElement(f.getMethod().getType().getName(),
f.getMethod().getName(),
f.getMethod().getType().getName() + ".java",
f.getLineNumber()))
.toArray(StackTraceElement[]::new);
super.setStackTrace(stackTraceElements);
}
}

@Override
public String getMessage() {
return "Pinned virtual threads were detected:\n"
+ recordedEvent.toString();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.microprofile.testing.testng;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* An annotation making this test class to fail at the end if a pinned virtual thread was detected.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface PinnedThreadValidation {
}
1 change: 1 addition & 0 deletions microprofile/testing/testng/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
requires jakarta.cdi;
requires jakarta.inject;
requires jakarta.ws.rs;
requires jdk.jfr;
requires microprofile.config.api;
requires org.testng;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.microprofile.tests.testing.junit5;

import io.helidon.microprofile.testing.junit5.PinnedThreadValidation;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

@PinnedThreadValidation
class TestPinnedThread {

@Test
@Disabled("Enable to verify pinned threads fails")
void test() throws InterruptedException {
Thread.ofVirtual().start(() -> {
synchronized (this) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
}).join();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.microprofile.tests.testing.testng;

import io.helidon.microprofile.testing.testng.PinnedThreadValidation;

import org.testng.annotations.Ignore;
import org.testng.annotations.Test;

@PinnedThreadValidation
class TestPinnedThread {

@Test
@Ignore("Enable to verify pinned threads fails")
void test() throws InterruptedException {
Thread.ofVirtual().start(() -> {
synchronized (this) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
}).join();
}
}
Loading

0 comments on commit 2513001

Please sign in to comment.