aboutsummaryrefslogtreecommitdiff
path: root/kamon-play24/src/main/scala
diff options
context:
space:
mode:
Diffstat (limited to 'kamon-play24/src/main/scala')
-rw-r--r--kamon-play24/src/main/scala/kamon/play/Play.scala81
-rw-r--r--kamon-play24/src/main/scala/kamon/play/action/KamonTraceActions.scala29
-rw-r--r--kamon-play24/src/main/scala/kamon/play/di/KamonModule.scala54
-rw-r--r--kamon-play24/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala42
-rw-r--r--kamon-play24/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala86
-rw-r--r--kamon-play24/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala47
6 files changed, 339 insertions, 0 deletions
diff --git a/kamon-play24/src/main/scala/kamon/play/Play.scala b/kamon-play24/src/main/scala/kamon/play/Play.scala
new file mode 100644
index 00000000..4d72f16e
--- /dev/null
+++ b/kamon-play24/src/main/scala/kamon/play/Play.scala
@@ -0,0 +1,81 @@
+/*
+ * =========================================================================================
+ * Copyright © 2013-2014 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.play
+
+import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider }
+import akka.event.Logging
+import kamon.Kamon
+import kamon.http.HttpServerMetrics
+import play.api.libs.ws.WSRequest
+import play.api.mvc.RequestHeader
+
+object Play extends ExtensionId[PlayExtension] with ExtensionIdProvider {
+ override def lookup(): ExtensionId[_ <: Extension] = Play
+ override def createExtension(system: ExtendedActorSystem): PlayExtension = new PlayExtension(system)
+
+ val SegmentLibraryName = "WS-client"
+}
+
+class PlayExtension(private val system: ExtendedActorSystem) extends Kamon.Extension {
+ val log = Logging(system, classOf[PlayExtension])
+ log.info(s"Starting the Kamon(Play) extension")
+
+ private val config = system.settings.config.getConfig("kamon.play")
+ val httpServerMetrics = Kamon.metrics.entity(HttpServerMetrics, "play-server")
+
+ val includeTraceToken: Boolean = config.getBoolean("automatic-trace-token-propagation")
+ val traceTokenHeaderName: String = config.getString("trace-token-header-name")
+
+ private val nameGeneratorFQN = config.getString("name-generator")
+ private val nameGenerator: NameGenerator = system.dynamicAccess.createInstanceFor[NameGenerator](nameGeneratorFQN, Nil).get
+
+ def generateTraceName(requestHeader: RequestHeader): String = nameGenerator.generateTraceName(requestHeader)
+ def generateHttpClientSegmentName(request: WSRequest): String = nameGenerator.generateHttpClientSegmentName(request)
+}
+
+trait NameGenerator {
+ def generateTraceName(requestHeader: RequestHeader): String
+ def generateHttpClientSegmentName(request: WSRequest): String
+}
+
+class DefaultNameGenerator extends NameGenerator {
+ import scala.collection.concurrent.TrieMap
+ import play.api.routing.Router
+ import java.util.Locale
+ import kamon.util.TriemapAtomicGetOrElseUpdate.Syntax
+
+ private val cache = TrieMap.empty[String, String]
+ private val normalizePattern = """\$([^<]+)<[^>]+>""".r
+
+ def generateTraceName(requestHeader: RequestHeader): String = requestHeader.tags.get(Router.Tags.RouteVerb).map { verb ⇒
+ val path = requestHeader.tags(Router.Tags.RoutePattern)
+ cache.atomicGetOrElseUpdate(s"$verb$path", {
+ val traceName = {
+ // Convert paths of form GET /foo/bar/$paramname<regexp>/blah to foo.bar.paramname.blah.get
+ val p = normalizePattern.replaceAllIn(path, "$1").replace('/', '.').dropWhile(_ == '.')
+ val normalisedPath = {
+ if (p.lastOption.filter(_ != '.').isDefined) s"$p."
+ else p
+ }
+ s"$normalisedPath${verb.toLowerCase(Locale.ENGLISH)}"
+ }
+ traceName
+ })
+ } getOrElse s"${requestHeader.method}: ${requestHeader.uri}"
+
+ def generateHttpClientSegmentName(request: WSRequest): String = request.url
+}
diff --git a/kamon-play24/src/main/scala/kamon/play/action/KamonTraceActions.scala b/kamon-play24/src/main/scala/kamon/play/action/KamonTraceActions.scala
new file mode 100644
index 00000000..854989a4
--- /dev/null
+++ b/kamon-play24/src/main/scala/kamon/play/action/KamonTraceActions.scala
@@ -0,0 +1,29 @@
+/* ===================================================
+ * Copyright © 2013-2014 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.play.action
+
+import kamon.trace.Tracer
+import play.api.mvc._
+import scala.concurrent.Future
+
+case class TraceName[A](name: String)(action: Action[A]) extends Action[A] {
+ def apply(request: Request[A]): Future[Result] = {
+ Tracer.currentContext.rename(name)
+ action(request)
+ }
+ lazy val parser = action.parser
+}
diff --git a/kamon-play24/src/main/scala/kamon/play/di/KamonModule.scala b/kamon-play24/src/main/scala/kamon/play/di/KamonModule.scala
new file mode 100644
index 00000000..372e7300
--- /dev/null
+++ b/kamon-play24/src/main/scala/kamon/play/di/KamonModule.scala
@@ -0,0 +1,54 @@
+/* =========================================================================================
+ * 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.play.di
+
+import javax.inject._
+import kamon.metric.MetricsModule
+import kamon.trace.TracerModule
+import play.api.inject.{ ApplicationLifecycle, Module }
+import play.api.{ Logger, Configuration, Environment }
+import scala.concurrent.Future
+
+trait Kamon {
+ def start(): Unit
+ def shutdown(): Unit
+ def metrics(): MetricsModule
+ def tracer(): TracerModule
+}
+
+class KamonModule extends Module {
+ def bindings(environment: Environment, configuration: Configuration) = {
+ Seq(bind[Kamon].to[KamonAPI].eagerly())
+ }
+}
+
+@Singleton
+class KamonAPI @Inject() (lifecycle: ApplicationLifecycle, environment: Environment) extends Kamon {
+ private val log = Logger(classOf[KamonAPI])
+
+ log.info("Registering the Kamon Play Module.")
+
+ start() //force to start kamon eagerly on application startup
+
+ def start(): Unit = kamon.Kamon.start()
+ def shutdown(): Unit = kamon.Kamon.shutdown()
+ def metrics(): MetricsModule = kamon.Kamon.metrics
+ def tracer(): TracerModule = kamon.Kamon.tracer
+
+ lifecycle.addStopHook { () ⇒
+ Future.successful(shutdown())
+ }
+}
diff --git a/kamon-play24/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala b/kamon-play24/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala
new file mode 100644
index 00000000..3c79fae4
--- /dev/null
+++ b/kamon-play24/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala
@@ -0,0 +1,42 @@
+/* =========================================================================================
+ * Copyright © 2013-2014 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.play.instrumentation
+
+import kamon.trace.logging.MdcKeysSupport
+import org.aspectj.lang.ProceedingJoinPoint
+import org.aspectj.lang.annotation._
+
+@Aspect
+class LoggerLikeInstrumentation extends MdcKeysSupport {
+
+ @Pointcut("execution(* play.api.LoggerLike+.info(..))")
+ def infoPointcut(): Unit = {}
+
+ @Pointcut("execution(* play.api.LoggerLike+.warn(..))")
+ def warnPointcut(): Unit = {}
+
+ @Pointcut("execution(* play.api.LoggerLike+.error(..))")
+ def errorPointcut(): Unit = {}
+
+ @Pointcut("execution(* play.api.LoggerLike+.trace(..))")
+ def tracePointcut(): Unit = {}
+
+ @Around("(infoPointcut() || warnPointcut() || errorPointcut() || tracePointcut())")
+ def aroundLog(pjp: ProceedingJoinPoint): Any = withMdc {
+ pjp.proceed()
+ }
+}
+
diff --git a/kamon-play24/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala b/kamon-play24/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala
new file mode 100644
index 00000000..7bf6d0d0
--- /dev/null
+++ b/kamon-play24/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala
@@ -0,0 +1,86 @@
+/* =========================================================================================
+ * 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.play.instrumentation
+
+import kamon.Kamon
+import kamon.Kamon.tracer
+import kamon.play.Play
+import kamon.trace._
+import kamon.util.SameThreadExecutionContext
+import org.aspectj.lang.ProceedingJoinPoint
+import org.aspectj.lang.annotation._
+import play.api.mvc.Results._
+import play.api.mvc._
+
+@Aspect
+class RequestInstrumentation {
+
+ @DeclareMixin("play.api.mvc.RequestHeader+")
+ def mixinContextAwareNewRequest: TraceContextAware = TraceContextAware.default
+
+ @Before("call(* play.api.http.DefaultHttpRequestHandler.routeRequest(..)) && args(requestHeader)")
+ def beforeRouteRequest(requestHeader: RequestHeader): Unit = {
+ val playExtension = Kamon(Play)
+
+ val token = if (playExtension.includeTraceToken) {
+ requestHeader.headers.get(playExtension.traceTokenHeaderName)
+ } else None
+
+ Tracer.setCurrentContext(tracer.newContext("UnnamedTrace", token))
+ }
+
+ @Around("call(* play.api.http.HttpFilters.filters(..))")
+ def filters(pjp: ProceedingJoinPoint): Any = {
+ val filter = new EssentialFilter {
+ def apply(next: EssentialAction): EssentialAction = {
+ val action = (requestHeader: RequestHeader) ⇒ {
+ val playExtension = Kamon(Play)
+
+ def onResult(result: Result): Result = {
+ Tracer.currentContext.collect { ctx ⇒
+ ctx.finish()
+ playExtension.httpServerMetrics.recordResponse(ctx.name, result.header.status.toString)
+
+ if (playExtension.includeTraceToken) result.withHeaders(playExtension.traceTokenHeaderName -> ctx.token)
+ else result
+
+ } getOrElse result
+ }
+ //override the current trace name
+ Tracer.currentContext.rename(playExtension.generateTraceName(requestHeader))
+ // Invoke the action
+ next(requestHeader).map(onResult)(SameThreadExecutionContext)
+ }
+ EssentialAction(action)
+ }
+ }
+ pjp.proceed().asInstanceOf[Seq[EssentialFilter]] :+ filter
+ }
+
+ @Before("call(* play.api.http.HttpErrorHandler.onClientServerError(..)) && args(requestContextAware, statusCode, *)")
+ def onClientError(requestContextAware: TraceContextAware, statusCode: Int): Unit = {
+ requestContextAware.traceContext.collect { ctx ⇒
+ Kamon(Play).httpServerMetrics.recordResponse(ctx.name, statusCode.toString)
+ }
+ }
+
+ @Before("call(* play.api.http.HttpErrorHandler.onServerError(..)) && args(requestContextAware, ex)")
+ def onServerError(requestContextAware: TraceContextAware, ex: Throwable): Unit = {
+ requestContextAware.traceContext.collect { ctx ⇒
+ Kamon(Play).httpServerMetrics.recordResponse(ctx.name, InternalServerError.header.status.toString)
+ }
+ }
+}
diff --git a/kamon-play24/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala b/kamon-play24/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala
new file mode 100644
index 00000000..93f6d95a
--- /dev/null
+++ b/kamon-play24/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala
@@ -0,0 +1,47 @@
+/* ===================================================
+ * Copyright © 2013-2014 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.play.instrumentation
+
+import kamon.Kamon
+import kamon.play.Play
+import kamon.trace.{ Tracer, SegmentCategory }
+import kamon.util.SameThreadExecutionContext
+import org.aspectj.lang.ProceedingJoinPoint
+import org.aspectj.lang.annotation.{ Around, Aspect, Pointcut }
+import play.api.libs.ws.{ WSRequest, WSResponse }
+import scala.concurrent.Future
+import scala.util.Try
+
+@Aspect
+class WSInstrumentation {
+
+ @Pointcut("execution(* play.api.libs.ws.ning.NingWSRequest.execute()) && this(request)")
+ def onExecuteRequest(request: WSRequest): Unit = {}
+
+ @Around("onExecuteRequest(request)")
+ def aroundExecuteRequest(pjp: ProceedingJoinPoint, request: WSRequest): Any = {
+ Tracer.currentContext.collect { ctx ⇒
+ val playExtension = Kamon(Play)
+ val segmentName = playExtension.generateHttpClientSegmentName(request)
+ val segment = ctx.startSegment(segmentName, SegmentCategory.HttpClient, Play.SegmentLibraryName)
+ val response = pjp.proceed().asInstanceOf[Future[WSResponse]]
+
+ response.onComplete(result ⇒ segment.finish())(SameThreadExecutionContext)
+ response
+ } getOrElse pjp.proceed()
+ }
+} \ No newline at end of file