diff options
author | Diego <diegolparra@gmail.com> | 2015-02-07 14:26:26 -0300 |
---|---|---|
committer | Diego <diegolparra@gmail.com> | 2015-03-01 18:44:04 -0300 |
commit | 2cc7eeee6fe31a4dfd479f3c0abf1085c7bbf879 (patch) | |
tree | ba75d454858f4d020e79b084c5166e300962a437 /kamon-annotation/src/main | |
parent | 0f2f2be4e4fc44a512ed79ab09f0d83d3fd0e871 (diff) | |
download | Kamon-2cc7eeee6fe31a4dfd479f3c0abf1085c7bbf879.tar.gz Kamon-2cc7eeee6fe31a4dfd479f3c0abf1085c7bbf879.tar.bz2 Kamon-2cc7eeee6fe31a4dfd479f3c0abf1085c7bbf879.zip |
! kamon-annotation: defined instruments @Trace @Segment @Gauge @Timed @Counted @Histogram and full implemetation
Diffstat (limited to 'kamon-annotation/src/main')
16 files changed, 1108 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) + } +} |