|
| 1 | +/** |
| 2 | + * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * 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 |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.linkedin.pinot.core.trace; |
| 17 | + |
| 18 | +import com.linkedin.pinot.common.request.InstanceRequest; |
| 19 | +import org.slf4j.Logger; |
| 20 | +import org.slf4j.LoggerFactory; |
| 21 | + |
| 22 | +import java.util.concurrent.Callable; |
| 23 | + |
| 24 | +/** |
| 25 | + * Wrap a {@link Callable} so that the thread executes this job |
| 26 | + * will be automatically registered/unregistered to/from a request. |
| 27 | + * |
| 28 | + */ |
| 29 | +public abstract class TraceCallable<V> implements Callable<V> { |
| 30 | + |
| 31 | + private static final Logger LOGGER = LoggerFactory.getLogger(TraceCallable.class); |
| 32 | + |
| 33 | + private final InstanceRequest request; |
| 34 | + private final TraceContext.Trace parent; |
| 35 | + |
| 36 | + public TraceCallable(InstanceRequest request, TraceContext.Trace parent) { |
| 37 | + if (request == null) { |
| 38 | + LOGGER.warn("Passing null requestId to TraceRunnable, maybe forget to register the request in current thread."); |
| 39 | + } |
| 40 | + this.request = request; |
| 41 | + this.parent = parent; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Only works when the calling thread has registered the requestId |
| 46 | + */ |
| 47 | + public TraceCallable() { |
| 48 | + this(TraceContext.getRequestForCurrentThread(), TraceContext.getLocalTraceForCurrentThread()); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public V call() throws Exception { |
| 53 | + TraceContext.registerThreadToRequest(request, parent); |
| 54 | + try { |
| 55 | + return callJob(); |
| 56 | + } finally { |
| 57 | + TraceContext.unregisterThreadFromRequest(); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public abstract V callJob() throws Exception; |
| 62 | + |
| 63 | +} |
0 commit comments