aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/kamon/instrumentation/PromiseCompletingRunnableInstrumentation.scala
blob: ce19a7e68dc94dea394493fa444b3cf375c79cd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package kamon.instrumentation

import org.aspectj.lang.annotation._
import kamon.TraceContext
import org.aspectj.lang.ProceedingJoinPoint
import scala.Some

/**
 *  Marker interface, just to make sure we don't instrument all the Runnables in the classpath.
 */
trait TraceContextAwareRunnable extends Runnable {}


@Aspect("perthis(instrumentedRunnableCreation())")
class PromiseCompletingRunnableInstrumentation {

  /**
   *  These are the Runnables that need to be instrumented and make the TraceContext available
   *  while their run method is executed.
   */
  @DeclareMixin("scala.concurrent.impl.CallbackRunnable || scala.concurrent.impl.Future.PromiseCompletingRunnable")
  def onCompleteCallbacksRunnable: TraceContextAwareRunnable = null


  /**
   *  Pointcuts
   */

  @Pointcut("execution(kamon.instrumentation.TraceContextAwareRunnable+.new(..))")
  def instrumentedRunnableCreation(): Unit = {}

  @Pointcut("execution(* kamon.instrumentation.TraceContextAwareRunnable.run())")
  def runnableExecution() = {}


  /**
   *  Aspect members
   */

  private val traceContext = TraceContext.current


  /**
   *  Advices
   */

  @Around("runnableExecution()")
  def around(pjp: ProceedingJoinPoint) = {
    import pjp._

    traceContext match {
      case Some(ctx) => {
        TraceContext.set(ctx)
        proceed()
        TraceContext.clear
      }
      case None => proceed()
    }
  }

}