aboutsummaryrefslogtreecommitdiff
path: root/kamon-core/src/main/scala/kamon/instrumentation/RunnableInstrumentation.scala
blob: 456917e05afd1f36b45352aabecbbe7ed99be638 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package kamon.instrumentation

import org.aspectj.lang.annotation._
import kamon.{Tracer, 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 {
  def traceContext: Option[TraceContext]
}


@Aspect
class RunnableInstrumentation {

  /**
   *  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 = new TraceContextAwareRunnable {
    val traceContext: Option[TraceContext] = Tracer.context()
  }


  /**
   *  Pointcuts
   */

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

  @Pointcut("execution(* kamon.instrumentation.TraceContextAwareRunnable+.run()) && this(runnable)")
  def runnableExecution(runnable: TraceContextAwareRunnable) = {}



  import kamon.TraceContextSwap.withContext

  @After("instrumentedRunnableCreation(runnable)")
  def beforeCreation(runnable: TraceContextAwareRunnable) = {
    val x = runnable.traceContext
    /*if(runnable.traceContext.isEmpty)
      println("WTFWI from: " + (new Throwable).getStackTraceString)
    else
      println("NOWTF: " + (new Throwable).getStackTraceString)*/
  /*  if(traceContext.isEmpty)
      println("NO TRACE CONTEXT FOR RUNNABLE at: [[[%s]]]", (new Throwable).getStackTraceString)//println((new Throwable).getStackTraceString)
    else
      println("SUPER TRACE CONTEXT FOR RUNNABLE at: [[[%s]]]", (new Throwable).getStackTraceString)*/
  }


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

    /*println("EXECUTING")
    if(runnable.traceContext.isEmpty)
      println("NOMONEY")

    runnable.traceContext match {
      case Some(context) => {
        //MDC.put("uow", context.userContext.get.asInstanceOf[String])
        Tracer.set(context)
        val bodyResult = proceed()
        Tracer.clear
        //MDC.remove("uow")

        bodyResult
      }
      case None => proceed()
    }*/
    withContext(runnable.traceContext, proceed())
  }

}