Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First "MVP" support for Spring @Scheduled / EJB @Schedule annotation #569

Merged
merged 4 commits into from
Apr 11, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions apm-agent-plugins/apm-spring-scheduled-plugin/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apm-agent-plugins</artifactId>
<groupId>co.elastic.apm</groupId>
<version>1.5.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>apm-spring-scheduled-plugin</artifactId>
<name>${project.groupId}:${project.artifactId}</name>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.6</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*-
* #%L
* Elastic APM Java agent
* %%
* Copyright (C) 2018 - 2019 Elastic and contributors
* %%
* 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.
* #L%
*/
package co.elastic.apm.agent.spring.scheduled;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import javax.annotation.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import co.elastic.apm.agent.bci.ElasticApmInstrumentation;
import co.elastic.apm.agent.bci.VisibleForAdvice;
import co.elastic.apm.agent.bci.bytebuddy.SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature;
import co.elastic.apm.agent.impl.ElasticApmTracer;
import co.elastic.apm.agent.impl.stacktrace.StacktraceConfiguration;
import co.elastic.apm.agent.impl.transaction.TraceContext;
import co.elastic.apm.agent.impl.transaction.TraceContextHolder;
import co.elastic.apm.agent.impl.transaction.Transaction;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.NamedElement;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;

import static co.elastic.apm.agent.bci.bytebuddy.CustomElementMatchers.isInAnyPackage;
import static net.bytebuddy.matcher.ElementMatchers.declaresMethod;
import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith;
import static net.bytebuddy.matcher.ElementMatchers.named;

public class SpringScheduledTransactionNameInstrumentation extends ElasticApmInstrumentation {

@VisibleForAdvice
public static final Logger logger = LoggerFactory.getLogger(SpringScheduledTransactionNameInstrumentation.class);

private Collection<String> applicationPackages = Collections.emptyList();

@Advice.OnMethodEnter(suppress = Throwable.class)
private static void setTransactionName(@SimpleMethodSignature String signature, @Advice.Origin Class<?> clazz, @Advice.Local("transaction") Transaction transaction) {
if (tracer != null) {
TraceContextHolder<?> active = tracer.getActive();
if (active == null) {
transaction = tracer.startTransaction(TraceContext.asRoot(), null, clazz.getClassLoader())
.withName(signature)
.withType("scheduled")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a good choice for "type"? I did not find anything besided "request" in the current code base.

.activate();

} else {
logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active);
}
}
}

@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onMethodExit(@Nullable @Advice.Local("transaction") Transaction transaction,
@Advice.Thrown Throwable t) {
if (transaction != null) {
transaction.captureException(t)
.deactivate()
.end();
}
}

@Override
public void init(ElasticApmTracer tracer) {
applicationPackages = tracer.getConfig(StacktraceConfiguration.class).getApplicationPackages();
}

@Override
public ElementMatcher<? super TypeDescription> getTypeMatcher() {
return isInAnyPackage(applicationPackages, ElementMatchers.<NamedElement>none())
.and(declaresMethod(getMethodMatcher()));
}

@Override
public ElementMatcher<? super MethodDescription> getMethodMatcher() {
return isAnnotatedWith(named("org.springframework.scheduling.annotation.Scheduled"));
timmhirsens marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
public Collection<String> getInstrumentationGroupNames() {
return Arrays.asList("concurrent", "spring-scheduled");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*-
* #%L
* Elastic APM Java agent
* %%
* Copyright (C) 2018 - 2019 Elastic and contributors
* %%
* 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.
* #L%
*/
@NonnullApi
package co.elastic.apm.agent.spring.scheduled;

import co.elastic.apm.agent.annotation.NonnullApi;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
co.elastic.apm.agent.spring.scheduled.SpringScheduledTransactionNameInstrumentation
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*-
* #%L
* Elastic APM Java agent
* %%
* Copyright (C) 2018 - 2019 Elastic and contributors
* %%
* 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.
* #L%
*/
package co.elastic.apm.agent.spring.scheduled;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Counter {
private AtomicInteger count = new AtomicInteger(0);

@Scheduled(fixedDelay = 5)
public void scheduled() {
this.count.incrementAndGet();
}

public int getInvocationCount() {
return this.count.get();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*-
* #%L
* Elastic APM Java agent
* %%
* Copyright (C) 2018 - 2019 Elastic and contributors
* %%
* 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.
* #L%
*/
package co.elastic.apm.agent.spring.scheduled;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
@ComponentScan("co.elastic.apm.agent.spring.scheduled")
public class ScheduledConfig {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*-
* #%L
* Elastic APM Java agent
* %%
* Copyright (C) 2018 - 2019 Elastic and contributors
* %%
* 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.
* #L%
*/
package co.elastic.apm.agent.spring.scheduled;

import java.util.Collections;

import org.awaitility.Duration;
import org.junit.BeforeClass;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import co.elastic.apm.agent.MockReporter;
import co.elastic.apm.agent.bci.ElasticApmAgent;
import co.elastic.apm.agent.configuration.SpyConfiguration;
import co.elastic.apm.agent.impl.ElasticApmTracer;
import co.elastic.apm.agent.impl.ElasticApmTracerBuilder;
import net.bytebuddy.agent.ByteBuddyAgent;

import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.verify;

/**
* TODO <<Zweck und Verantwortung des Moduls, ggf. mehrere Zeilen>>
timmhirsens marked this conversation as resolved.
Show resolved Hide resolved
*/
@SpringJUnitConfig(ScheduledConfig.class)
timmhirsens marked this conversation as resolved.
Show resolved Hide resolved
class SpringScheduledTransactionNameInstrumentationTest {

private static MockReporter reporter;
private static ElasticApmTracer tracer;

@BeforeClass
@BeforeAll
static void setUpAll() {
reporter = new MockReporter();
tracer = new ElasticApmTracerBuilder()
.configurationRegistry(SpyConfiguration.createSpyConfig())
.reporter(reporter)
.build();
ElasticApmAgent.initInstrumentation(tracer, ByteBuddyAgent.install(),
Collections.singletonList(new SpringScheduledTransactionNameInstrumentation()));
}

@SpyBean
private Counter counter;

@Test
void testScheduledAnnotatedMethodsAreTraced() {
reporter.reset();
await()
timmhirsens marked this conversation as resolved.
Show resolved Hide resolved
.atMost(Duration.FIVE_HUNDRED_MILLISECONDS)
.untilAsserted(() -> verify(counter, atLeast(5)).scheduled());
timmhirsens marked this conversation as resolved.
Show resolved Hide resolved
assertThat(reporter.getTransactions().size(), greaterThanOrEqualTo(counter.getInvocationCount()));
assertThat(reporter.getTransactions().get(0).getName().toString(), containsString("#scheduled"));
}

}
1 change: 1 addition & 0 deletions apm-agent-plugins/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<module>apm-java-concurrent-plugin</module>
<module>apm-urlconnection-plugin</module>
<module>apm-jaxws-plugin</module>
<module>apm-spring-scheduled-plugin</module>
</modules>

<properties>
Expand Down
4 changes: 2 additions & 2 deletions docs/configuration.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ you should add an additional entry to this list (make sure to also include the d
==== `disable_instrumentations`

A list of instrumentations which should be disabled.
Valid options are `annotations`, `apache-httpclient`, `concurrent`, `dispatcher-servlet`, `elasticsearch-restclient`, `executor`, `http-client`, `incubating`, `jax-rs`, `jax-ws`, `jdbc`, `jsf`, `okhttp`, `opentracing`, `public-api`, `render`, `servlet-api`, `servlet-api-async`, `servlet-input-stream`, `servlet-service-name`, `spring-mvc`, `spring-resttemplate`, `spring-service-name`, `urlconnection`.
Valid options are `annotations`, `apache-httpclient`, `concurrent`, `dispatcher-servlet`, `elasticsearch-restclient`, `executor`, `http-client`, `incubating`, `jax-rs`, `jax-ws`, `jdbc`, `jsf`, `okhttp`, `opentracing`, `public-api`, `render`, `servlet-api`, `servlet-api-async`, `servlet-input-stream`, `servlet-service-name`, `spring-mvc`, `spring-resttemplate`, `spring-scheduled`, `spring-service-name`, `urlconnection`.
If you want to try out incubating features,
set the value to an empty string.

Expand Down Expand Up @@ -1204,7 +1204,7 @@ If the service name is set explicitly, it overrides all of the above.
# sanitize_field_names=password,passwd,pwd,secret,*key,*token*,*session*,*credit*,*card*,authorization,set-cookie

# A list of instrumentations which should be disabled.
# Valid options are `annotations`, `apache-httpclient`, `concurrent`, `dispatcher-servlet`, `elasticsearch-restclient`, `executor`, `http-client`, `incubating`, `jax-rs`, `jax-ws`, `jdbc`, `jsf`, `okhttp`, `opentracing`, `public-api`, `render`, `servlet-api`, `servlet-api-async`, `servlet-input-stream`, `servlet-service-name`, `spring-mvc`, `spring-resttemplate`, `spring-service-name`, `urlconnection`.
# Valid options are `annotations`, `apache-httpclient`, `concurrent`, `dispatcher-servlet`, `elasticsearch-restclient`, `executor`, `http-client`, `incubating`, `jax-rs`, `jax-ws`, `jdbc`, `jsf`, `okhttp`, `opentracing`, `public-api`, `render`, `servlet-api`, `servlet-api-async`, `servlet-input-stream`, `servlet-service-name`, `spring-mvc`, `spring-resttemplate`, `spring-scheduled`, `spring-service-name`, `urlconnection`.
# If you want to try out incubating features,
# set the value to an empty string.
#
Expand Down
5 changes: 5 additions & 0 deletions elastic-apm-agent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,11 @@
<artifactId>apm-web-plugin</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>apm-spring-scheduled-plugin</artifactId>
<version>${project.version}</version>
</dependency>

<!-- For auto-generating configuration docs -->
<dependency>
Expand Down