1.9.30 sync.
[gae.git] / java / src / main / com / google / apphosting / api / CloudTrace.java
blob2ffeb894d4e0ddf6ab1afedd559e7ac0506ed2f0
1 package com.google.apphosting.api;
3 import java.util.Map;
5 import javax.annotation.Nullable;
7 /**
8 * Holds the current trace context visible to user code. If present, this object will be stored
9 * under the KEY-variable in an Environment's property.
11 * This class is used to share the current trace context between run time and user code. It is not
12 * responsible for managing contexts. It only keeps the most current context for a given thread.
14 public abstract class CloudTrace {
15 private static final String KEY = "com.google.apphosting.api.cloudTrace";
17 private static final ThreadLocal<CloudTraceContext> perThreadContext = new ThreadLocal<>();
19 /**
20 * Returns the corresponding CloudTrace object for a given environment. If the
21 * environment does not have a CloudTrace object, null will be returned.
23 @Nullable
24 private static CloudTrace get(ApiProxy.Environment env) {
25 return (CloudTrace) env.getAttributes().get(KEY);
28 /**
29 * Returns the current trace context for the given environment and the current thread.
30 * @param env the current environment.
32 @Nullable
33 public static CloudTraceContext getCurrentContext(ApiProxy.Environment env) {
34 CloudTrace cloudTrace = CloudTrace.get(env);
35 return (cloudTrace == null) ? null : cloudTrace.getCurrentContext();
38 /**
39 * Returns the current trace context for the current thread.
41 @Nullable
42 private CloudTraceContext getCurrentContext() {
43 CloudTraceContext context = perThreadContext.get();
44 return (context == null) ? getDefaultContext() : context;
47 /**
48 * Sets the current trace context for the current environment and the current thread.
49 * @param env the current environment.
50 * @param context the current trace context.
52 public static void setCurrentContext(
53 ApiProxy.Environment env,
54 @Nullable CloudTraceContext context) {
55 CloudTrace cloudTrace = CloudTrace.get(env);
56 if (cloudTrace != null) {
57 perThreadContext.set(context);
61 /**
62 * Binds this object to a particular environment.
63 * @param env the Environment object to bind this object to.
64 * @throws IllegalStateException if an object is already bound
66 protected void bind(ApiProxy.Environment env) {
67 CloudTrace original;
68 Map<String, Object> attrs = env.getAttributes();
70 synchronized (attrs) {
71 original = (CloudTrace) attrs.get(KEY);
72 if (original == null) {
73 attrs.put(KEY, this);
74 return;
77 if (original != this) {
78 throw new IllegalStateException("Cannot replace existing CloudTrace object");
82 /**
83 * Returns the default context when a thread-specific one doesn't exist.
85 protected abstract CloudTraceContext getDefaultContext();