diff options
Diffstat (limited to 'kamon-annotation/src')
21 files changed, 1726 insertions, 0 deletions
diff --git a/kamon-annotation/src/main/java/kamon/annotation/Count.java b/kamon-annotation/src/main/java/kamon/annotation/Count.java new file mode 100644 index 00000000..09bea4ec --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/Count.java @@ -0,0 +1,69 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +import java.lang.annotation.*; + +/** + * A marker annotation to define a method as a Counter. + * <p> + * <p> + * Given a method like this: + * <pre><code> + * {@literal @}Count(name = "coolName", tags="${'my-cool-tag':'my-cool-value'}") + * public String coolName(String name) { + * return "Hello " + name; + * } + * </code></pre> + * <p> + * <p> + * A {@link kamon.metric.instrument.Counter Counter} for the defining method with the name {@code coolName} will be created and each time the + * {@code #coolName(String)} method is invoked, the counter will be incremented. + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Count { + + /** + * @return The counter's name. + * <p> + * Also, the Metric name can be resolved with an EL expression that evaluates to a String: + * <p> + * <pre> + * {@code + * class Counted { + * private long id; + * + * public long getId() { return id; } + * + * {@literal @}Count (name = "${'counterID:' += this.id}") + * void countedMethod() {} // create a counter with name => counterID:[id] + * } + * } + * </pre> + */ + String name(); + + /** + * Tags are a way of adding dimensions to metrics, + * these are constructed using EL syntax e.g. "${'algorithm':'1','env':'production'}" + * + * @return the tags associated to the counter + */ + String tags() default ""; +} diff --git a/kamon-annotation/src/main/java/kamon/annotation/EnableKamon.java b/kamon-annotation/src/main/java/kamon/annotation/EnableKamon.java new file mode 100644 index 00000000..97ed9375 --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/EnableKamon.java @@ -0,0 +1,27 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +import java.lang.annotation.*; + +/** + * A marker annotation for enable the Kamon instrumentation. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface EnableKamon {} diff --git a/kamon-annotation/src/main/java/kamon/annotation/Histogram.java b/kamon-annotation/src/main/java/kamon/annotation/Histogram.java new file mode 100644 index 00000000..7c163104 --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/Histogram.java @@ -0,0 +1,89 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +import java.lang.annotation.*; + +/** + * A marker annotation to define a method as a Histogram. + * <p> + * <p> + * Given a method like this: + * <pre><code> + * {@literal @}0Histogram(name = "coolName", tags="${'my-cool-tag':'my-cool-value'}") + * public (Long|Double|Float|Integer) coolName() { + * return someComputation(); + * } + * </code></pre> + * <p> + * <p> + * A {@link kamon.metric.instrument.Histogram Histogram} for the defining method with the name {@code coolName} will be created which uses the + * annotated method's return as its value. + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Histogram { + + /** + * @return The histogram's name. + * <p> + * Also, the Metric name can be resolved with an EL expression that evaluates to a String: + * <p> + * <pre> + * {@code + * class ClassWithHistogram { + * private long id; + * + * public long getId() { return id; } + * + * {@literal @}Histogram (name = "${'histoID:' += this.id}") + * void countedMethod() {} // create a histogram with name => histoID:[id] + * } + * } + * </pre> + */ + String name(); + + /** + * The lowest value that can be discerned (distinguished from 0) by the histogram.Must be a positive integer that + * is >= 1. May be internally rounded down to nearest power of 2. + */ + long lowestDiscernibleValue() default 1; + + + /** + * The highest value to be tracked by the histogram. Must be a positive integer that is >= (2 * lowestDiscernibleValue). + * Must not be larger than (Long.MAX_VALUE/2). + */ + long highestTrackableValue() default 3600000000000L; + + /** + * The number of significant decimal digits to which the histogram will maintain value resolution and separation. + * Must be a non-negative integer between 1 and 3. + */ + int precision() default 2; + + + /** + * Tags are a way of adding dimensions to metrics, + * these are constructed using EL syntax e.g. "${'algorithm':'1','env':'production'}" + * + * @return the tags associated to the histogram + */ + String tags() default ""; +}
\ No newline at end of file diff --git a/kamon-annotation/src/main/java/kamon/annotation/MinMaxCount.java b/kamon-annotation/src/main/java/kamon/annotation/MinMaxCount.java new file mode 100644 index 00000000..ed2a6f6e --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/MinMaxCount.java @@ -0,0 +1,71 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +import java.lang.annotation.*; + +/** + * A marker annotation to define a method as a MinMaxCounter. + * <p> + * <p> + * Given a method like this: + * <pre><code> + * {@literal @}MinMaxCount(name = "coolName", tags="${'my-cool-tag':'my-cool-value'}") + * public String coolName(String name) { + * return "Hello " + name; + * } + * </code></pre> + * <p> + * <p> + * A {@link kamon.metric.instrument.MinMaxCounter MinMaxCounter} for the defining method with the name {@code coolName} will be created and each time the + * {@code #coolName(String)} method is invoked the counter is decremented when the method returns, + * counting current invocations of the annotated method. + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface MinMaxCount { + + /** + * @return The MinMaxCounter's name. + * <p> + * Also, the Metric name can be resolved with an EL expression that evaluates to a String: + * <p> + * <pre> + * {@code + * class MinMaxCounted { + * private long id; + * + * public long getId() { return id; } + * + * {@literal @}MinMaxCount (name = "${'counterID:' += this.id}") + * void countedMethod() {} // create a counter with name => counterID:[id] + * } + * } + * </pre> + */ + + String name(); + + /** + * Tags are a way of adding dimensions to metrics, + * these are constructed using EL syntax e.g. "${'algorithm':'1','env':'production'}" + * + * @return the tags associated to the counter + */ + String tags() default ""; +} diff --git a/kamon-annotation/src/main/java/kamon/annotation/Segment.java b/kamon-annotation/src/main/java/kamon/annotation/Segment.java new file mode 100644 index 00000000..8d69e84a --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/Segment.java @@ -0,0 +1,78 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +import java.lang.annotation.*; + +/** + * A marker annotation to start a new Segment. + * <p> + * <p> + * Given a method like this: + * <pre><code> + * {@literal @}Segment("coolSegmentName", tags="${'my-cool-tag':'my-cool-value'}") + * public String coolName(String name) { + * return "Hello " + name; + * } + * </code></pre> + * <p> + * <p> + * A new Segment will be created only if in the moment of the method execution exist a TraceContext. + */ +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Segment { + + /** + * @return The Segment's name. + * <p> + * Also, the Segment name can be resolved with an EL expression that evaluates to a String: + * <p> + * <pre> + * {@code + * class Segment { + * private long id; + * + * public long getId() { return id; } + * + * {@literal @}Segment (name = "${'segmentID:' += this.id}") + * void segment() {} // create a Segment with name => segmentID:[id] + * } + * } + * </pre> + */ + String name(); + + /** + * @return The Segment's category. + */ + String category(); + + /** + * @return The Segment's library. + */ + String library(); + + /** + * Tags are a way of adding dimensions to metrics, + * these are constructed using EL syntax e.g. "${'algorithm':'1','env':'production'}" + * + * @return the tags associated to the segment + */ + String tags() default ""; +} diff --git a/kamon-annotation/src/main/java/kamon/annotation/Time.java b/kamon-annotation/src/main/java/kamon/annotation/Time.java new file mode 100644 index 00000000..a8e3a62c --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/Time.java @@ -0,0 +1,57 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +/** + * A marker annotation to define a method as a timed. + * <p> + * <p> + * Given a method like this: + * <pre><code> + * {@literal @}Timed(name = "coolName", tags="""${{'my-cool-tag':'my-cool-value'}}""") + * public String coolName(String name) { + * return "Hello " + name; + * } + * </code></pre> + * <p> + * <p> + * A histogram for the defining method with the name {@code coolName} will be created and each time the + * {@code #coolName(String)} method is invoked, the latency of execution will be recorded. + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Time { + /** + * @return The histogram's name. + */ + String name(); + + /** + * Tags are a way of adding dimensions to metrics, + * these are constructed using EL syntax e.g. """${{'algorithm':'1','env':'production'}}""" + * + * @return the tags associated to the histogram + */ + String tags() default ""; +} diff --git a/kamon-annotation/src/main/java/kamon/annotation/Trace.java b/kamon-annotation/src/main/java/kamon/annotation/Trace.java new file mode 100644 index 00000000..1f373fa2 --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/Trace.java @@ -0,0 +1,69 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +import java.lang.annotation.*; + +/** + * A marker annotation to start a new Trace. + * <p> + * <p> + * Given a method like this: + * <pre><code> + * {@literal @}Trace("coolTraceName", tags="${'my-cool-tag':'my-cool-value'}") + * public String coolName(String name) { + * return "Hello " + name; + * } + * </code></pre> + * <p> + * <p> + * A new Trace will be created for the defining method with the name each time the + * {@code #coolName(String)} method is invoked. + */ + +@Documented +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Trace { + /** + * @return The Trace's name. + * <p> + * Also, the Trace name can be resolved with an EL expression that evaluates to a String: + * <p> + * <pre> + * {@code + * class Traced { + * private long id; + * + * public long getId() { return id; } + * + * {@literal @}Trace (name = "${'traceID:' += this.id}") + * void countedMethod() {} // create a Trace with name => traceID:[id] + * } + * } + * </pre> + */ + String value(); + + /** + * Tags are a way of adding dimensions to metrics, + * these are constructed using EL syntax e.g. "${'algorithm':'1','env':'production'}" + * + * @return the tags associated to the trace + */ + String tags() default ""; +} diff --git a/kamon-annotation/src/main/java/kamon/annotation/el/resolver/PrivateFieldELResolver.java b/kamon-annotation/src/main/java/kamon/annotation/el/resolver/PrivateFieldELResolver.java new file mode 100644 index 00000000..df646942 --- /dev/null +++ b/kamon-annotation/src/main/java/kamon/annotation/el/resolver/PrivateFieldELResolver.java @@ -0,0 +1,117 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation.el.resolver; + +import java.beans.FeatureDescriptor; +import java.lang.reflect.Field; +import java.util.Iterator; +import javax.el.ELContext; +import javax.el.ELException; +import javax.el.ELResolver; + +/** + * A custom {@link ELResolver} for mapping properties to public/private fields of the base object. + */ +public class PrivateFieldELResolver extends ELResolver { + + @Override + public Object getValue(ELContext context, Object base, Object property) { + if (base == null) { + return null; + } + try { + Field field = getField(base, (String) property); + context.setPropertyResolved(true); + field.setAccessible(true); + return field.get(base); + } catch (NoSuchFieldException exc) { + context.setPropertyResolved(false); + return null; + } catch (Exception exc) { + throw new ELException(exc); + } + } + + private Field getField(Object base, String property) throws NoSuchFieldException { + try { + return base.getClass().getDeclaredField(property); + } catch (SecurityException exc) { + throw new ELException(exc); + } + } + + @Override + public Class<?> getType(ELContext context, Object base, Object property) { + if (base == null) { + return null; + } + try { + Field field = getField(base, (String) property); + if (field != null) { + context.setPropertyResolved(true); + return field.getType(); + } else { + return null; + } + } catch (NoSuchFieldException exc) { + context.setPropertyResolved(false); + return null; + } + } + + @Override + public void setValue(ELContext context, Object base, Object property, Object value) { + if (base == null) { + return; + } + try { + context.setPropertyResolved(true); + getField(base, (String) property).set(base, value); + } catch (NoSuchFieldException exc) { + context.setPropertyResolved(false); + } catch (Exception exc) { + throw new ELException(exc); + } + } + + @Override + public boolean isReadOnly(ELContext context, Object base, Object property) { + if (base == null) { + return true; + } + try { + Field field = getField(base, (String) property); + if (field != null) { + context.setPropertyResolved(true); + return !field.isAccessible(); + } + } catch (NoSuchFieldException exc) { + context.setPropertyResolved(false); + } + return false; + } + + @Override + public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { + return null; + } + + @Override + public Class<?> getCommonPropertyType(ELContext context, Object base) { + return String.class; + } +}
\ No newline at end of file diff --git a/kamon-annotation/src/main/resources/META-INF/aop.xml b/kamon-annotation/src/main/resources/META-INF/aop.xml new file mode 100644 index 00000000..b017e60e --- /dev/null +++ b/kamon-annotation/src/main/resources/META-INF/aop.xml @@ -0,0 +1,18 @@ +<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> + +<aspectj> + <aspects> + <aspect name="kamon.annotation.instrumentation.ClassToAnnotationInstrumentsMixin"/> + <aspect name="kamon.annotation.instrumentation.AnnotationInstrumentation"/> + <aspect name="kamon.annotation.instrumentation.StaticAnnotationInstrumentation"/> + </aspects> + <weaver options="-warn:none"> + <!-- exclude some commons packages --> + <exclude within="org.apache.commons..*"/> + <exclude within="org.apache.log4j..*"/> + <exclude within="org.hibernate..*"/> + <exclude within="org.springframework..*"/> + <exclude within="com.google..*"/> + <exclude within="*..*CGLIB*" /> + </weaver> +</aspectj> diff --git a/kamon-annotation/src/main/resources/reference.conf b/kamon-annotation/src/main/resources/reference.conf new file mode 100644 index 00000000..b7680022 --- /dev/null +++ b/kamon-annotation/src/main/resources/reference.conf @@ -0,0 +1,19 @@ +# ========================================= # +# Kamon-Annotation Reference Configuration # +# ========================================= # + +kamon { + annotation { + # We use two arrays to store the kamon instruments in order to do fast array lookups. + # These lookups are done using the getId() method on the JoinPoint.StaticPart object. + # The ids for all affected join points within a target type are unique (and start from 0). + instruments-array-size = 32 + } + modules { + kamon-annotation { + auto-start = yes + requires-aspectj = yes + extension-id = "kamon.annotation.Annotation" + } + } +} diff --git a/kamon-annotation/src/main/scala/kamon/annotation/Annotation.scala b/kamon-annotation/src/main/scala/kamon/annotation/Annotation.scala new file mode 100644 index 00000000..6ddf57cf --- /dev/null +++ b/kamon-annotation/src/main/scala/kamon/annotation/Annotation.scala @@ -0,0 +1,34 @@ +/* ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation + +import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } +import akka.event.Logging +import kamon.Kamon + +object Annotation extends ExtensionId[AnnotationExtension] with ExtensionIdProvider { + override def lookup(): ExtensionId[_ <: Extension] = Annotation + override def createExtension(system: ExtendedActorSystem): AnnotationExtension = new AnnotationExtension(system) +} + +class AnnotationExtension(system: ExtendedActorSystem) extends Kamon.Extension { + val log = Logging(system, classOf[AnnotationExtension]) + log.info(s"Starting the Kamon(Annotation) extension") + + val config = system.settings.config.getConfig("kamon.annotation") + val arraySize = config.getInt("instruments-array-size") +} + diff --git a/kamon-annotation/src/main/scala/kamon/annotation/el/ELProcessorFactory.scala b/kamon-annotation/src/main/scala/kamon/annotation/el/ELProcessorFactory.scala new file mode 100644 index 00000000..e80c61d8 --- /dev/null +++ b/kamon-annotation/src/main/scala/kamon/annotation/el/ELProcessorFactory.scala @@ -0,0 +1,40 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation.el + +import javax.el.ELProcessor +import kamon.annotation.el.resolver.PrivateFieldELResolver + +object ELProcessorFactory { + def withClass(clazz: Class[_]): ELProcessor = { + val processor = create() + processor.getELManager.importClass(clazz.getName) + processor + } + + def withObject(obj: AnyRef): ELProcessor = { + val processor = withClass(obj.getClass) + processor.defineBean("this", obj) + processor + } + + private def create(): ELProcessor = { + val processor = new ELProcessor() + processor.getELManager.addELResolver(new PrivateFieldELResolver()) + processor + } +} diff --git a/kamon-annotation/src/main/scala/kamon/annotation/el/EnhancedELProcessor.scala b/kamon-annotation/src/main/scala/kamon/annotation/el/EnhancedELProcessor.scala new file mode 100644 index 00000000..f407930b --- /dev/null +++ b/kamon-annotation/src/main/scala/kamon/annotation/el/EnhancedELProcessor.scala @@ -0,0 +1,60 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation.el + +import javax.el.ELProcessor + +import kamon.Kamon +import kamon.annotation.Annotation + +import scala.util.{ Failure, Success, Try } + +/** + * Pimp ELProcessor injecting some useful methods. + */ +object EnhancedELProcessor { + private val Pattern = """[#|$]\{(.*)\}""".r + + implicit class Syntax(val processor: ELProcessor) extends AnyVal { + import scala.collection.JavaConverters._ + + def evalToString(expression: String): String = extract(expression).map { str ⇒ + eval[String](str) match { + case Success(value) ⇒ value + case Failure(cause) ⇒ + Kamon(Annotation).log.error(s"${cause.getMessage} -> we will complete the operation with 'unknown' string") + "unknown" + } + } getOrElse expression + + def evalToMap(expression: String): Map[String, String] = extract(expression).map { str ⇒ + eval[Map[String, String]](s"{$str}") match { + case Success(value) ⇒ value.asInstanceOf[java.util.HashMap[String, String]].asScala.toMap + case Failure(cause) ⇒ + Kamon(Annotation).log.error(s"${cause.getMessage} -> we will complete the operation with an empty map") + Map.empty[String, String] + } + } getOrElse Map.empty[String, String] + + private def eval[A](str: String): Try[A] = Try(processor.eval(str).asInstanceOf[A]) + + private def extract(expression: String): Option[String] = expression match { + case Pattern(ex) ⇒ Some(ex) + case _ ⇒ None + } + } +} diff --git a/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/AnnotationInstrumentation.scala b/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/AnnotationInstrumentation.scala new file mode 100644 index 00000000..381aeb72 --- /dev/null +++ b/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/AnnotationInstrumentation.scala @@ -0,0 +1,81 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation.instrumentation + +import kamon.Kamon +import kamon.annotation._ +import kamon.metric.instrument +import kamon.metric.instrument.{ MinMaxCounter, Counter } +import org.aspectj.lang.annotation._ +import org.aspectj.lang.{ JoinPoint, ProceedingJoinPoint } +import java.util.concurrent.atomic.AtomicReferenceArray + +@Aspect +class AnnotationInstrumentation extends BaseAnnotationInstrumentation { + + @After("execution((@kamon.annotation.EnableKamon AnnotationInstruments+).new(..)) && this(obj)") + def creation(jps: JoinPoint.StaticPart, obj: AnnotationInstruments): Unit = { + val size = Kamon(Annotation).arraySize + obj.traces = new AtomicReferenceArray[TraceContextInfo](size) + obj.segments = new AtomicReferenceArray[SegmentInfo](size) + obj.counters = new AtomicReferenceArray[Counter](size) + obj.minMaxCounters = new AtomicReferenceArray[MinMaxCounter](size) + obj.histograms = new AtomicReferenceArray[instrument.Histogram](size) + } + + @Around("execution(@kamon.annotation.Trace !static * (@kamon.annotation.EnableKamon AnnotationInstruments+).*(..)) && this(obj)") + def trace(pjp: ProceedingJoinPoint, obj: AnnotationInstruments): AnyRef = { + var traceInfo = obj.traces.get(pjp.getStaticPart.getId) + if (traceInfo == null) traceInfo = registerTrace(pjp.getStaticPart, obj.traces, StringEvaluator(obj), TagsEvaluator(obj)) + processTrace(traceInfo, pjp) + } + + @Around("execution(@kamon.annotation.Segment !static * (@kamon.annotation.EnableKamon AnnotationInstruments+).*(..)) && this(obj)") + def segment(pjp: ProceedingJoinPoint, obj: AnnotationInstruments): AnyRef = { + var segmentInfo = obj.segments.get(pjp.getStaticPart.getId) + if (segmentInfo == null) segmentInfo = registerSegment(pjp.getStaticPart, obj.segments, StringEvaluator(obj), TagsEvaluator(obj)) + processSegment(segmentInfo, pjp) + } + + @Around("execution(@kamon.annotation.Time !static * (@kamon.annotation.EnableKamon AnnotationInstruments+).*(..)) && this(obj)") + def time(pjp: ProceedingJoinPoint, obj: AnnotationInstruments): AnyRef = { + var histogram = obj.histograms.get(pjp.getStaticPart.getId) + if (histogram == null) histogram = registerTime(pjp.getStaticPart, obj.histograms, StringEvaluator(obj), TagsEvaluator(obj)) + processTime(histogram, pjp) + } + + @Around("execution(@kamon.annotation.Count !static * (@kamon.annotation.EnableKamon AnnotationInstruments+).*(..)) && this(obj)") + def count(pjp: ProceedingJoinPoint, obj: AnnotationInstruments): AnyRef = { + var counter = obj.counters.get(pjp.getStaticPart.getId) + if (counter == null) counter = registerCounter(pjp.getStaticPart, obj.counters, StringEvaluator(obj), TagsEvaluator(obj)) + processCount(counter, pjp) + } + + @Around("execution(@kamon.annotation.MinMaxCount !static * (@kamon.annotation.EnableKamon AnnotationInstruments+).*(..)) && this(obj)") + def minMax(pjp: ProceedingJoinPoint, obj: AnnotationInstruments): AnyRef = { + var minMax = obj.minMaxCounters.get(pjp.getStaticPart.getId) + if (minMax == null) minMax = registerMinMaxCounter(pjp.getStaticPart, obj.minMaxCounters, StringEvaluator(obj), TagsEvaluator(obj)) + processMinMax(minMax, pjp) + } + + @AfterReturning(pointcut = "execution(@kamon.annotation.Histogram !static (int || long || double || float) (@kamon.annotation.EnableKamon AnnotationInstruments+).*(..)) && this(obj)", returning = "result") + def histogram(jps: JoinPoint.StaticPart, obj: AnnotationInstruments, result: AnyRef): Unit = { + var histogram = obj.histograms.get(jps.getId) + if (histogram == null) histogram = registerHistogram(jps, obj.histograms, StringEvaluator(obj), TagsEvaluator(obj)) + processHistogram(histogram, result, jps) + } +} diff --git a/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/BaseAnnotationInstrumentation.scala b/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/BaseAnnotationInstrumentation.scala new file mode 100644 index 00000000..57e8c4d7 --- /dev/null +++ b/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/BaseAnnotationInstrumentation.scala @@ -0,0 +1,178 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation.instrumentation + +import java.util.concurrent.atomic.AtomicReferenceArray +import javax.el.ELProcessor + +import kamon.Kamon +import kamon.annotation.el.{ EnhancedELProcessor, ELProcessorFactory } +import kamon.annotation.{ Histogram, _ } +import kamon.metric.instrument.Histogram.DynamicRange +import kamon.metric.instrument.{ Counter, MinMaxCounter } +import kamon.metric._ +import kamon.trace.Tracer +import kamon.util.Latency +import org.aspectj.lang.{ JoinPoint, ProceedingJoinPoint } +import org.aspectj.lang.annotation.{ Aspect, DeclareMixin } +import org.aspectj.lang.reflect.MethodSignature +import EnhancedELProcessor.Syntax + +class BaseAnnotationInstrumentation { + + @inline final def registerTime(jps: JoinPoint.StaticPart, histograms: AtomicReferenceArray[instrument.Histogram], evalString: StringEvaluator, evalTags: TagsEvaluator): instrument.Histogram = { + val method = jps.getSignature.asInstanceOf[MethodSignature].getMethod + val time = method.getAnnotation(classOf[Time]) + val name = evalString(time.name()) + val tags = evalTags(time.tags()) + val currentHistogram = Kamon.simpleMetrics.histogram(HistogramKey(name, tags)) + histograms.set(jps.getId, currentHistogram) + currentHistogram + } + + @inline final def registerHistogram(jps: JoinPoint.StaticPart, histograms: AtomicReferenceArray[instrument.Histogram], evalString: StringEvaluator, evalTags: TagsEvaluator): instrument.Histogram = { + val method = jps.getSignature.asInstanceOf[MethodSignature].getMethod + val histogram = method.getAnnotation(classOf[Histogram]) + val name = evalString(histogram.name()) + val tags = evalTags(histogram.tags()) + val dynamicRange = DynamicRange(histogram.lowestDiscernibleValue(), histogram.highestTrackableValue(), histogram.precision()) + val currentHistogram = Kamon.simpleMetrics.histogram(HistogramKey(name, tags), dynamicRange) + histograms.set(jps.getId, currentHistogram) + currentHistogram + } + + @inline final def registerMinMaxCounter(jps: JoinPoint.StaticPart, minMaxCounters: AtomicReferenceArray[MinMaxCounter], evalString: StringEvaluator, evalTags: TagsEvaluator): instrument.MinMaxCounter = { + val method = jps.getSignature.asInstanceOf[MethodSignature].getMethod + val minMaxCount = method.getAnnotation(classOf[MinMaxCount]) + val name = evalString(minMaxCount.name()) + val tags = evalTags(minMaxCount.tags()) + val minMaxCounter = Kamon.simpleMetrics.minMaxCounter(MinMaxCounterKey(name, tags)) + minMaxCounters.set(jps.getId, minMaxCounter) + minMaxCounter + } + + @inline final def registerCounter(jps: JoinPoint.StaticPart, counters: AtomicReferenceArray[Counter], evalString: StringEvaluator, evalTags: TagsEvaluator): instrument.Counter = { + val method = jps.getSignature.asInstanceOf[MethodSignature].getMethod + val count = method.getAnnotation(classOf[Count]) + val name = evalString(count.name()) + val tags = evalTags(count.tags()) + val counter = Kamon.simpleMetrics.counter(CounterKey(name, tags)) + counters.set(jps.getId, counter) + counter + } + + @inline final def registerTrace(jps: JoinPoint.StaticPart, traces: AtomicReferenceArray[TraceContextInfo], evalString: StringEvaluator, evalTags: TagsEvaluator): TraceContextInfo = { + val method = jps.getSignature.asInstanceOf[MethodSignature].getMethod + val trace = method.getAnnotation(classOf[Trace]) + val name = evalString(trace.value()) + val tags = evalTags(trace.tags()) + val traceContextInfo = TraceContextInfo(name, tags) + traces.set(jps.getId, traceContextInfo) + traceContextInfo + } + + @inline final def registerSegment(jps: JoinPoint.StaticPart, segments: AtomicReferenceArray[SegmentInfo], evalString: StringEvaluator, evalTags: TagsEvaluator): SegmentInfo = { + val method = jps.getSignature.asInstanceOf[MethodSignature].getMethod + val segment = method.getAnnotation(classOf[Segment]) + val name = evalString(segment.name()) + val category = evalString(segment.category()) + val library = evalString(segment.library()) + val tags = evalTags(segment.tags()) + val segmentInfo = SegmentInfo(name, category, library, tags) + segments.set(jps.getId, segmentInfo) + segmentInfo + } + + @inline final def processTrace(traceInfo: TraceContextInfo, pjp: ProceedingJoinPoint): AnyRef = { + Tracer.withContext(Kamon.tracer.newContext(traceInfo.name)) { + traceInfo.tags.foreach { case (key, value) ⇒ Tracer.currentContext.addMetadata(key, value) } + val result = pjp.proceed() + Tracer.currentContext.finish() + result + } + } + + @inline final def processSegment(segmentInfo: SegmentInfo, pjp: ProceedingJoinPoint): AnyRef = { + Tracer.currentContext.collect { ctx ⇒ + val currentSegment = ctx.startSegment(segmentInfo.name, segmentInfo.category, segmentInfo.library) + segmentInfo.tags.foreach { case (key, value) ⇒ currentSegment.addMetadata(key, value) } + val result = pjp.proceed() + currentSegment.finish() + result + } getOrElse pjp.proceed() + } + + @inline final def processTime(histogram: instrument.Histogram, pjp: ProceedingJoinPoint): AnyRef = { + Latency.measure(histogram)(pjp.proceed) + } + + @inline final def processHistogram(histogram: instrument.Histogram, result: AnyRef, jps: JoinPoint.StaticPart): Unit = { + histogram.record(result.asInstanceOf[Number].longValue()) + } + + final def processCount(counter: instrument.Counter, pjp: ProceedingJoinPoint): AnyRef = { + try pjp.proceed() finally counter.increment() + } + + final def processMinMax(minMaxCounter: instrument.MinMaxCounter, pjp: ProceedingJoinPoint): AnyRef = { + minMaxCounter.increment() + try pjp.proceed() finally minMaxCounter.decrement() + } + + private[annotation] def declaringType(signature: org.aspectj.lang.Signature) = signature.getDeclaringType +} + +@Aspect +class ClassToAnnotationInstrumentsMixin { + @DeclareMixin("(@kamon.annotation.EnableKamon *)") + def mixinClassToAnnotationInstruments: AnnotationInstruments = new AnnotationInstruments {} +} + +trait AnnotationInstruments { + var traces: AtomicReferenceArray[TraceContextInfo] = _ + var segments: AtomicReferenceArray[SegmentInfo] = _ + var histograms: AtomicReferenceArray[instrument.Histogram] = _ + var counters: AtomicReferenceArray[Counter] = _ + var minMaxCounters: AtomicReferenceArray[MinMaxCounter] = _ +} + +case class SegmentInfo(name: String, category: String, library: String, tags: Map[String, String]) +case class TraceContextInfo(name: String, tags: Map[String, String]) + +abstract class StringEvaluator(val processor: ELProcessor) extends (String ⇒ String) + +object StringEvaluator { + def apply(obj: AnyRef) = new StringEvaluator(ELProcessorFactory.withObject(obj)) { + def apply(str: String) = processor.evalToString(str) + } + + def apply(clazz: Class[_]) = new StringEvaluator(ELProcessorFactory.withClass(clazz)) { + def apply(str: String) = processor.evalToString(str) + } +} + +abstract class TagsEvaluator(val processor: ELProcessor) extends (String ⇒ Map[String, String]) + +object TagsEvaluator { + def apply(obj: AnyRef) = new TagsEvaluator(ELProcessorFactory.withObject(obj)) { + def apply(str: String) = processor.evalToMap(str) + } + + def apply(clazz: Class[_]) = new TagsEvaluator(ELProcessorFactory.withClass(clazz)) { + def apply(str: String) = processor.evalToMap(str) + } +}
\ No newline at end of file diff --git a/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/StaticAnnotationInstrumentation.scala b/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/StaticAnnotationInstrumentation.scala new file mode 100644 index 00000000..f5677377 --- /dev/null +++ b/kamon-annotation/src/main/scala/kamon/annotation/instrumentation/StaticAnnotationInstrumentation.scala @@ -0,0 +1,101 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation.instrumentation + +import java.util.concurrent.atomic.AtomicReferenceArray + +import kamon.Kamon +import kamon.annotation.Annotation +import kamon.metric.instrument +import kamon.metric.instrument.{ Counter, MinMaxCounter } +import org.aspectj.lang.annotation.{ After, AfterReturning, Around, Aspect } +import org.aspectj.lang.{ JoinPoint, ProceedingJoinPoint } + +@Aspect("pertypewithin(kamon.annotation.instrumentation.AnnotationInstruments+ && !kamon.annotation.instrumentation.*)") +class StaticAnnotationInstrumentation extends BaseAnnotationInstrumentation with AnnotationInstruments { + + println("statics") + @After("staticinitialization(*) && !within(kamon.annotation.instrumentation.*)") + def creation(jps: JoinPoint.StaticPart): Unit = { + val size = Kamon(Annotation).arraySize + traces = new AtomicReferenceArray[TraceContextInfo](size) + segments = new AtomicReferenceArray[SegmentInfo](size) + counters = new AtomicReferenceArray[Counter](size) + minMaxCounters = new AtomicReferenceArray[MinMaxCounter](size) + histograms = new AtomicReferenceArray[instrument.Histogram](size) + } + + @Around("execution(@kamon.annotation.Trace static * (@kamon.annotation.EnableKamon *).*(..))") + def trace(pjp: ProceedingJoinPoint): AnyRef = { + var traceInfo = traces.get(pjp.getStaticPart.getId) + if (traceInfo == null) { + val clazz = declaringType(pjp.getSignature) + traceInfo = registerTrace(pjp.getStaticPart, traces, StringEvaluator(clazz), TagsEvaluator(clazz)) + } + processTrace(traceInfo, pjp) + } + + @Around("execution(@kamon.annotation.Segment static * (@kamon.annotation.EnableKamon *).*(..))") + def segment(pjp: ProceedingJoinPoint): AnyRef = { + var segmentInfo = segments.get(pjp.getStaticPart.getId) + if (segmentInfo == null) { + val clazz = declaringType(pjp.getSignature) + segmentInfo = registerSegment(pjp.getStaticPart, segments, StringEvaluator(clazz), TagsEvaluator(clazz)) + } + processSegment(segmentInfo, pjp) + } + + @Around("execution(@kamon.annotation.Time static * (@kamon.annotation.EnableKamon *).*(..))") + def time(pjp: ProceedingJoinPoint): AnyRef = { + var histogram = histograms.get(pjp.getStaticPart.getId) + if (histogram == null) { + val clazz = declaringType(pjp.getSignature) + histogram = registerTime(pjp.getStaticPart, histograms, StringEvaluator(clazz), TagsEvaluator(clazz)) + } + processTime(histogram, pjp) + } + + @Around("execution(@kamon.annotation.Count static * (@kamon.annotation.EnableKamon *).*(..))") + def count(pjp: ProceedingJoinPoint): AnyRef = { + var counter = counters.get(pjp.getStaticPart.getId) + if (counter == null) { + val clazz = declaringType(pjp.getSignature) + counter = registerCounter(pjp.getStaticPart, counters, StringEvaluator(clazz), TagsEvaluator(clazz)) + } + processCount(counter, pjp) + } + + @Around("execution(@kamon.annotation.MinMaxCount static * (@kamon.annotation.EnableKamon *).*(..))") + def minMax(pjp: ProceedingJoinPoint): AnyRef = { + var minMax = minMaxCounters.get(pjp.getStaticPart.getId) + if (minMax == null) { + val clazz = declaringType(pjp.getSignature) + minMax = registerMinMaxCounter(pjp.getStaticPart, minMaxCounters, StringEvaluator(clazz), TagsEvaluator(clazz)) + } + processMinMax(minMax, pjp) + } + + @AfterReturning(pointcut = "execution(@kamon.annotation.Histogram static (int || long || double || float) (@kamon.annotation.EnableKamon *).*(..))", returning = "result") + def histogram(jps: JoinPoint.StaticPart, result: AnyRef): Unit = { + var histogram = histograms.get(jps.getId) + if (histogram == null) { + val clazz = declaringType(jps.getSignature) + histogram = registerHistogram(jps, histograms, StringEvaluator(clazz), TagsEvaluator(clazz)) + } + processHistogram(histogram, result, jps) + } +} diff --git a/kamon-annotation/src/test/java/kamon/annotation/AnnotatedJavaClass.java b/kamon-annotation/src/test/java/kamon/annotation/AnnotatedJavaClass.java new file mode 100644 index 00000000..285ccc74 --- /dev/null +++ b/kamon-annotation/src/test/java/kamon/annotation/AnnotatedJavaClass.java @@ -0,0 +1,66 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation; + +@EnableKamon +public class AnnotatedJavaClass { + + public static String ID = "10"; + + @Trace("trace") + public static void trace() {} + + @Trace("trace-with-segment") + public static void segment() { + inner(); // method annotated with @Segment + } + + @Trace("trace-with-segment-el") + public static void segmentWithEL() { + innerWithEL(); // method annotated with @Segment + } + + @Count(name = "count") + public static void count() {} + + @Count(name = "${'count:' += AnnotatedJavaClass.ID}", tags = "${'counter':'1', 'env':'prod'}") + public static void countWithEL() {} + + @MinMaxCount(name = "minMax") + public static void countMinMax() {} + + @MinMaxCount(name = "#{'minMax:' += AnnotatedJavaClass.ID}", tags = "#{'minMax':'1', 'env':'dev'}") + public static void countMinMaxWithEL() {} + + @Time(name = "time") + public static void time() {} + + @Time(name = "${'time:' += AnnotatedJavaClass.ID}", tags = "${'slow-service':'service', 'env':'prod'}") + public static void timeWithEL() {} + + @Histogram(name = "histogram") + public static long histogram(Long value) { return value; } + + @Histogram(name = "#{'histogram:' += AnnotatedJavaClass.ID}", tags = "${'histogram':'hdr', 'env':'prod'}") + public static long histogramWithEL(Long value) { return value;} + + @Segment(name = "inner-segment", category = "inner", library = "segment") + private static void inner() {} + + @Segment(name = "#{'inner-segment:' += AnnotatedJavaClass.ID}", category = "segments", library = "segment") + private static void innerWithEL() {} +}
\ No newline at end of file diff --git a/kamon-annotation/src/test/resources/logback.xml b/kamon-annotation/src/test/resources/logback.xml new file mode 100644 index 00000000..c336bbfe --- /dev/null +++ b/kamon-annotation/src/test/resources/logback.xml @@ -0,0 +1,12 @@ +<configuration> + <statusListener class="ch.qos.logback.core.status.NopStatusListener"/> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> + </encoder> + </appender> + + <root level="OFF"> + <appender-ref ref="STDOUT"/> + </root> +</configuration>
\ No newline at end of file diff --git a/kamon-annotation/src/test/scala/kamon/annotation/AnnotationInstrumentationSpec.scala b/kamon-annotation/src/test/scala/kamon/annotation/AnnotationInstrumentationSpec.scala new file mode 100644 index 00000000..41f0fc34 --- /dev/null +++ b/kamon-annotation/src/test/scala/kamon/annotation/AnnotationInstrumentationSpec.scala @@ -0,0 +1,206 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation + +import com.typesafe.config.ConfigFactory +import kamon.metric._ +import kamon.testkit.BaseKamonSpec + +class AnnotationInstrumentationSpec extends BaseKamonSpec("annotation-instrumentation-spec") { + import kamon.metric.TraceMetricsSpec.SegmentSyntax + + override lazy val config = + ConfigFactory.parseString( + """ + |kamon.metric { + | tick-interval = 1 hour + | default-collection-context-buffer-size = 100 + |} + """.stripMargin) + + "the Kamon Annotation module" should { + "create a new trace when is invoked a method annotated with @Trace" in { + for (id ← 1 to 10) Annotated(id).trace() + + val snapshot = takeSnapshotOf("trace", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + snapshot.segments.size should be(0) + } + + "create a segment when is invoked a method annotated with @Segment" in { + for (id ← 1 to 10) Annotated().segment() + + val snapshot = takeSnapshotOf("trace-with-segment", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + + snapshot.segments.size should be(1) + snapshot.segment("inner-segment", "inner", "segment") should not be empty + } + + "create a segment when is invoked a method annotated with @Segment and evaluate EL expressions" in { + for (id ← 1 to 10) Annotated(id).segmentWithEL() + + val snapshot = takeSnapshotOf("trace-with-segment-el", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + + snapshot.segments.size should be(10) + snapshot.segment("inner-segment:1", "inner", "segment") should not be empty + } + + "count the invocations of a method annotated with @Count" in { + for (id ← 1 to 10) Annotated(id).count() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.counter("count").get.count should be(10) + } + + "count the invocations of a method annotated with @Count and evaluate EL expressions" in { + for (id ← 1 to 2) Annotated(id).countWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.counter("count:1").get.count should be(1) + snapshot.counter("count:2").get.count should be(1) + + val counterKey = (name: String) ⇒ (key: CounterKey) ⇒ key.name == name + + snapshot.counters.keys.find(counterKey("count:1")).get.metadata should be(Map("counter" -> "1", "env" -> "prod")) + snapshot.counters.keys.find(counterKey("count:2")).get.metadata should be(Map("counter" -> "1", "env" -> "prod")) + } + + "count the current invocations of a method annotated with @MinMaxCount" in { + for (id ← 1 to 10) { + Annotated(id).countMinMax() + } + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.minMaxCounter("minMax").get.max should be(1) + } + + "count the current invocations of a method annotated with @MinMaxCount and evaluate EL expressions" in { + for (id ← 1 to 10) Annotated(id).countMinMaxWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.minMaxCounter("minMax:1").get.sum should be(1) + snapshot.minMaxCounter("minMax:2").get.sum should be(1) + + val minMaxKey = (name: String) ⇒ (key: MinMaxCounterKey) ⇒ key.name == name + + snapshot.minMaxCounters.keys.find(minMaxKey("minMax:1")).get.metadata should be(Map("minMax" -> "1", "env" -> "dev")) + snapshot.minMaxCounters.keys.find(minMaxKey("minMax:2")).get.metadata should be(Map("minMax" -> "1", "env" -> "dev")) + } + + "measure the time spent in the execution of a method annotated with @Time" in { + for (id ← 1 to 1) Annotated(id).time() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("time").get.numberOfMeasurements should be(1) + } + + "measure the time spent in the execution of a method annotated with @Time and evaluate EL expressions" in { + for (id ← 1 to 1) Annotated(id).timeWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("time:1").get.numberOfMeasurements should be(1) + + val histogramKey = (name: String) ⇒ (key: HistogramKey) ⇒ key.name == name + + snapshot.histograms.keys.find(histogramKey("time:1")).get.metadata should be(Map("slow-service" -> "service", "env" -> "prod")) + } + + "record the value returned by a method annotated with @Histogram" in { + for (value ← 1 to 5) Annotated().histogram(value) + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("histogram").get.numberOfMeasurements should be(5) + snapshot.histogram("histogram").get.min should be(1) + snapshot.histogram("histogram").get.max should be(5) + snapshot.histogram("histogram").get.sum should be(15) + } + + "record the value returned by a method annotated with @Histogram and evaluate EL expressions" in { + for (value ← 1 to 2) Annotated(value).histogramWithEL(value) + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("histogram:1").get.numberOfMeasurements should be(1) + snapshot.histogram("histogram:1").get.min should be(1) + snapshot.histogram("histogram:1").get.max should be(1) + snapshot.histogram("histogram:1").get.sum should be(1) + + snapshot.histogram("histogram:2").get.numberOfMeasurements should be(1) + snapshot.histogram("histogram:2").get.min should be(2) + snapshot.histogram("histogram:2").get.max should be(2) + snapshot.histogram("histogram:2").get.sum should be(2) + + val histogramKey = (name: String) ⇒ (key: HistogramKey) ⇒ key.name == name + + snapshot.histograms.keys.find(histogramKey("histogram:1")).get.metadata should be(Map("histogram" -> "hdr", "env" -> "prod")) + snapshot.histograms.keys.find(histogramKey("histogram:2")).get.metadata should be(Map("histogram" -> "hdr", "env" -> "prod")) + } + + } +} + +@EnableKamon +case class Annotated(id: Long) { + + @Trace("trace") + def trace(): Unit = {} + + @Trace("trace-with-segment") + def segment(): Unit = { + inner() // method annotated with @Segment + } + + @Trace("trace-with-segment-el") + def segmentWithEL(): Unit = { + innerWithEL() // method annotated with @Segment + } + + @Count(name = "count") + def count(): Unit = {} + + @Count(name = "${'count:' += this.id}", tags = "${'counter':'1', 'env':'prod'}") + def countWithEL(): Unit = {} + + @MinMaxCount(name = "minMax") + def countMinMax(): Unit = {} + + @MinMaxCount(name = "#{'minMax:' += this.id}", tags = "#{'minMax':'1', 'env':'dev'}") + def countMinMaxWithEL(): Unit = {} + + @Time(name = "time") + def time(): Unit = {} + + @Time(name = "${'time:' += this.id}", tags = "${'slow-service':'service', 'env':'prod'}") + def timeWithEL(): Unit = {} + + @Histogram(name = "histogram") + def histogram(value: Long): Long = value + + @Histogram(name = "#{'histogram:' += this.id}", tags = "${'histogram':'hdr', 'env':'prod'}") + def histogramWithEL(value: Long): Long = value + + @Segment(name = "inner-segment", category = "inner", library = "segment") + private def inner(): Unit = {} + + @Segment(name = "#{'inner-segment:' += this.id}", category = "inner", library = "segment") + private def innerWithEL(): Unit = {} +} + +object Annotated { + def apply(): Annotated = new Annotated(0L) +}
\ No newline at end of file diff --git a/kamon-annotation/src/test/scala/kamon/annotation/StaticAnnotationInstrumentationJavaSpec.scala b/kamon-annotation/src/test/scala/kamon/annotation/StaticAnnotationInstrumentationJavaSpec.scala new file mode 100644 index 00000000..4bae9f1d --- /dev/null +++ b/kamon-annotation/src/test/scala/kamon/annotation/StaticAnnotationInstrumentationJavaSpec.scala @@ -0,0 +1,142 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation + +import com.typesafe.config.ConfigFactory +import kamon.metric.{ HistogramKey, MinMaxCounterKey, CounterKey } +import kamon.testkit.BaseKamonSpec + +class StaticAnnotationInstrumentationJavaSpec extends BaseKamonSpec("static-annotation-instrumentation-java-spec") { + import kamon.metric.TraceMetricsSpec.SegmentSyntax + + override lazy val config = + ConfigFactory.parseString( + """ + |kamon.metric { + | tick-interval = 1 hour + | default-collection-context-buffer-size = 100 + |} + """.stripMargin) + + "the Kamon Annotation module" should { + "create a new trace when is invoked a static method annotated with @Trace" in { + for (id ← 1 to 10) AnnotatedJavaClass.trace() + + val snapshot = takeSnapshotOf("trace", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + snapshot.segments.size should be(0) + } + "create a segment when is invoked a static method annotated with @Segment" in { + for (id ← 1 to 10) AnnotatedJavaClass.segment() + + val snapshot = takeSnapshotOf("trace-with-segment", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + + snapshot.segments.size should be(1) + snapshot.segment("inner-segment", "inner", "segment") should not be empty + } + + "create a segment when is invoked a static method annotated with @Segment and evaluate EL expressions" in { + for (id ← 1 to 10) AnnotatedJavaClass.segmentWithEL() + + val snapshot = takeSnapshotOf("trace-with-segment-el", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + + snapshot.segments.size should be(1) + snapshot.segment("inner-segment:10", "segments", "segment") should not be empty + } + + "count the invocations of a static method annotated with @Count" in { + for (id ← 1 to 10) AnnotatedJavaClass.count() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.counter("count").get.count should be(10) + } + + "count the invocations of a static method annotated with @Count and evaluate EL expressions" in { + for (id ← 1 to 2) AnnotatedJavaClass.countWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.counter("count:10").get.count should be(2) + + val counterKey = (name: String) ⇒ (key: CounterKey) ⇒ key.name == name + + snapshot.counters.keys.find(counterKey("count:10")).get.metadata should be(Map("counter" -> "1", "env" -> "prod")) + } + + "count the current invocations of a static method annotated with @MinMaxCount" in { + for (id ← 1 to 10) { + AnnotatedJavaClass.countMinMax() + } + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.minMaxCounter("minMax").get.max should be(1) + } + + "count the current invocations of a static method annotated with @MinMaxCount and evaluate EL expressions" in { + for (id ← 1 to 10) AnnotatedJavaClass.countMinMaxWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.minMaxCounter("minMax:10").get.max should be(1) + + val minMaxKey = (name: String) ⇒ (key: MinMaxCounterKey) ⇒ key.name == name + + snapshot.minMaxCounters.keys.find(minMaxKey("minMax:10")).get.metadata should be(Map("minMax" -> "1", "env" -> "dev")) + } + + "measure the time spent in the execution of a static method annotated with @Time" in { + for (id ← 1 to 1) AnnotatedJavaClass.time() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("time").get.numberOfMeasurements should be(1) + } + + "measure the time spent in the execution of a static method annotated with @Time and evaluate EL expressions" in { + for (id ← 1 to 1) AnnotatedJavaClass.timeWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("time:10").get.numberOfMeasurements should be(1) + + val histogramKey = (name: String) ⇒ (key: HistogramKey) ⇒ key.name == name + + snapshot.histograms.keys.find(histogramKey("time:10")).get.metadata should be(Map("slow-service" -> "service", "env" -> "prod")) + } + + "record the value returned by a static method annotated with @Histogram" in { + for (value ← 1 to 5) AnnotatedJavaClass.histogram(value.toLong) + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("histogram").get.numberOfMeasurements should be(5) + snapshot.histogram("histogram").get.min should be(1) + snapshot.histogram("histogram").get.max should be(5) + snapshot.histogram("histogram").get.sum should be(15) + } + + "record the value returned by a static method annotated with @Histogram and evaluate EL expressions" in { + for (value ← 1 to 2) AnnotatedJavaClass.histogramWithEL(value.toLong) + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("histogram:10").get.numberOfMeasurements should be(2) + snapshot.histogram("histogram:10").get.min should be(1) + snapshot.histogram("histogram:10").get.max should be(2) + + val histogramKey = (name: String) ⇒ (key: HistogramKey) ⇒ key.name == name + + snapshot.histograms.keys.find(histogramKey("histogram:10")).get.metadata should be(Map("histogram" -> "hdr", "env" -> "prod")) + } + } +}
\ No newline at end of file diff --git a/kamon-annotation/src/test/scala/kamon/annotation/StaticAnnotationInstrumentationSpec.scala b/kamon-annotation/src/test/scala/kamon/annotation/StaticAnnotationInstrumentationSpec.scala new file mode 100644 index 00000000..aea83409 --- /dev/null +++ b/kamon-annotation/src/test/scala/kamon/annotation/StaticAnnotationInstrumentationSpec.scala @@ -0,0 +1,192 @@ +/* + * ========================================================================================= + * Copyright © 2013-2015 the kamon project <http://kamon.io/> + * + * 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 kamon.annotation + +import com.typesafe.config.ConfigFactory +import kamon.metric.{ HistogramKey, MinMaxCounterKey, CounterKey } +import kamon.testkit.BaseKamonSpec + +class StaticAnnotationInstrumentationSpec extends BaseKamonSpec("static-annotation-instrumentation-spec") { + import kamon.metric.TraceMetricsSpec.SegmentSyntax + + override lazy val config = + ConfigFactory.parseString( + """ + |kamon.metric { + | tick-interval = 1 hour + | default-collection-context-buffer-size = 100 + |} + """.stripMargin) + + "the Kamon Annotation module" should { + "create a new trace when is invoked a method annotated with @Trace in a Scala Object" in { + for (id ← 1 to 10) AnnotatedObject.trace() + + val snapshot = takeSnapshotOf("trace", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + snapshot.segments.size should be(0) + } + "create a segment when is invoked a method annotated with @Trace and @Segment in a Scala Object" in { + for (id ← 1 to 10) AnnotatedObject.segment() + + val snapshot = takeSnapshotOf("trace-with-segment", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + + snapshot.segments.size should be(2) + snapshot.segment("segment", "segments", "segment") should not be empty + snapshot.segment("inner-segment", "inner", "segment") should not be empty + } + + "create a segment when is invoked a method annotated with @Trace and @Segment and evaluate EL expressions in a Scala Object" in { + for (id ← 1 to 10) AnnotatedObject.segmentWithEL() + + val snapshot = takeSnapshotOf("trace-with-segment-el", "trace") + snapshot.histogram("elapsed-time").get.numberOfMeasurements should be(10) + + snapshot.segments.size should be(2) + snapshot.segment("segment:10", "segments", "segment") should not be empty + snapshot.segment("inner-segment", "inner", "segment") should not be empty + } + + "count the invocations of a method annotated with @Count in a Scala Object" in { + for (id ← 1 to 10) AnnotatedObject.count() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.counter("count").get.count should be(10) + } + + "count the invocations of a method annotated with @Count and evaluate EL expressions in a Scala Object" in { + for (id ← 1 to 2) AnnotatedObject.countWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.counter("count:10").get.count should be(2) + + val counterKey = (name: String) ⇒ (key: CounterKey) ⇒ key.name == name + + snapshot.counters.keys.find(counterKey("count:10")).get.metadata should be(Map("counter" -> "1", "env" -> "prod")) + } + + "count the current invocations of a method annotated with @MinMaxCount in a Scala Object" in { + for (id ← 1 to 10) { + AnnotatedObject.countMinMax() + } + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.minMaxCounter("minMax").get.max should be(1) + } + + "count the current invocations of a method annotated with @MinMaxCount and evaluate EL expressions in a Scala Object" in { + for (id ← 1 to 10) AnnotatedObject.countMinMaxWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.minMaxCounter("minMax:10").get.max should be(1) + + val minMaxKey = (name: String) ⇒ (key: MinMaxCounterKey) ⇒ key.name == name + + snapshot.minMaxCounters.keys.find(minMaxKey("minMax:10")).get.metadata should be(Map("minMax" -> "1", "env" -> "dev")) + } + + "measure the time spent in the execution of a method annotated with @Time in a Scala Object" in { + for (id ← 1 to 1) AnnotatedObject.time() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("time").get.numberOfMeasurements should be(1) + } + + "measure the time spent in the execution of a method annotated with @Time and evaluate EL expressions in a Scala Object" in { + for (id ← 1 to 1) AnnotatedObject.timeWithEL() + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("time:10").get.numberOfMeasurements should be(1) + + val histogramKey = (name: String) ⇒ (key: HistogramKey) ⇒ key.name == name + + snapshot.histograms.keys.find(histogramKey("time:10")).get.metadata should be(Map("slow-service" -> "service", "env" -> "prod")) + } + + "record the value returned by a method annotated with @Histogram in a Scala Object" in { + for (value ← 1 to 5) AnnotatedObject.histogram(value) + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("histogram").get.numberOfMeasurements should be(5) + snapshot.histogram("histogram").get.min should be(1) + snapshot.histogram("histogram").get.max should be(5) + snapshot.histogram("histogram").get.sum should be(15) + } + + "record the value returned by a method annotated with @Histogram and evaluate EL expressions in a Scala Object" in { + for (value ← 1 to 2) AnnotatedObject.histogramWithEL(value) + + val snapshot = takeSnapshotOf("simple-metric", "simple-metric") + snapshot.histogram("histogram:10").get.numberOfMeasurements should be(2) + snapshot.histogram("histogram:10").get.min should be(1) + snapshot.histogram("histogram:10").get.max should be(2) + + val histogramKey = (name: String) ⇒ (key: HistogramKey) ⇒ key.name == name + + snapshot.histograms.keys.find(histogramKey("histogram:10")).get.metadata should be(Map("histogram" -> "hdr", "env" -> "prod")) + } + } +} + +@EnableKamon +object AnnotatedObject { + + val Id = "10" + + @Trace("trace") + def trace(): Unit = {} + + @Trace("trace-with-segment") + @Segment(name = "segment", category = "segments", library = "segment") + def segment(): Unit = { + inner() // method annotated with @Segment + } + + @Trace("trace-with-segment-el") + @Segment(name = "#{'segment:' += AnnotatedObject$.MODULE$.Id}", category = "segments", library = "segment") + def segmentWithEL(): Unit = { + inner() // method annotated with @Segment + } + + @Count(name = "count") + def count(): Unit = {} + + @Count(name = "${'count:' += AnnotatedObject$.MODULE$.Id}", tags = "${'counter':'1', 'env':'prod'}") + def countWithEL(): Unit = {} + + @MinMaxCount(name = "minMax") + def countMinMax(): Unit = {} + + @MinMaxCount(name = "#{'minMax:' += AnnotatedObject$.MODULE$.Id}", tags = "#{'minMax':'1', 'env':'dev'}") + def countMinMaxWithEL(): Unit = {} + + @Time(name = "time") + def time(): Unit = {} + + @Time(name = "${'time:' += AnnotatedObject$.MODULE$.Id}", tags = "${'slow-service':'service', 'env':'prod'}") + def timeWithEL(): Unit = {} + + @Histogram(name = "histogram") + def histogram(value: Long): Long = value + + @Histogram(name = "#{'histogram:' += AnnotatedObject$.MODULE$.Id}", tags = "${'histogram':'hdr', 'env':'prod'}") + def histogramWithEL(value: Long): Long = value + + @Segment(name = "inner-segment", category = "inner", library = "segment") + private def inner(): Unit = {} +}
\ No newline at end of file |