|
| 1 | +/* |
| 2 | + * ========================================================================================== |
| 3 | + * Copyright © 2013-2022 The Kamon Project <https://kamon.io/> |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file |
| 6 | + * except in compliance with the License. You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software distributed under the |
| 11 | + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, |
| 12 | + * either express or implied. See the License for the specific language governing permissions |
| 13 | + * and limitations under the License. |
| 14 | + * ========================================================================================== |
| 15 | + */ |
| 16 | + |
| 17 | +package kamon |
| 18 | +package instrumentation |
| 19 | +package pekko |
| 20 | +package connectors |
| 21 | +package kafka |
| 22 | + |
| 23 | +import kamon.Kamon |
| 24 | +import kamon.context.Storage |
| 25 | +import kamon.context.Storage.Scope |
| 26 | +import kamon.instrumentation.context.HasContext |
| 27 | +import kanela.agent.api.instrumentation.InstrumentationBuilder |
| 28 | +import kanela.agent.libs.net.bytebuddy.asm.Advice |
| 29 | + |
| 30 | +class ProducerMessageInstrumentation extends InstrumentationBuilder { |
| 31 | + |
| 32 | + /** |
| 33 | + * Captures the current context the a Message or MultiMessage is created and restores it while |
| 34 | + * the ProducerLogic is running, so the proper context gets propagated to the Kafka Producer. |
| 35 | + */ |
| 36 | + onTypes("org.apache.pekko.kafka.ProducerMessage$Message", "org.apache.pekko.kafka.ProducerMessage$MultiMessage") |
| 37 | + .mixin(classOf[HasContext.MixinWithInitializer]) |
| 38 | + |
| 39 | + onTypes( |
| 40 | + "org.apache.pekko.kafka.internal.DefaultProducerStageLogic", |
| 41 | + "org.apache.pekko.kafka.internal.CommittingProducerSinkStageLogic" |
| 42 | + ) |
| 43 | + .advise(method("produce"), ProduceWithEnvelopeContext) |
| 44 | +} |
| 45 | + |
| 46 | +object ProduceWithEnvelopeContext { |
| 47 | + |
| 48 | + @Advice.OnMethodEnter |
| 49 | + def enter(@Advice.Argument(0) envelope: Any): Storage.Scope = { |
| 50 | + envelope match { |
| 51 | + case hasContext: HasContext => Kamon.storeContext(hasContext.context) |
| 52 | + case _ => Scope.Empty |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + @Advice.OnMethodExit(onThrowable = classOf[Throwable]) |
| 57 | + def exit(@Advice.Enter scope: Storage.Scope): Unit = |
| 58 | + scope.close() |
| 59 | +} |
0 commit comments