|
| 1 | +package datadog.trace.core.baggage; |
| 2 | + |
| 3 | +import datadog.context.Context; |
| 4 | +import datadog.context.propagation.CarrierSetter; |
| 5 | +import datadog.context.propagation.CarrierVisitor; |
| 6 | +import datadog.context.propagation.Propagator; |
| 7 | +import datadog.trace.api.Config; |
| 8 | +import datadog.trace.bootstrap.instrumentation.api.BaggageContext; |
| 9 | +import datadog.trace.core.util.EscapedData; |
| 10 | +import datadog.trace.core.util.PercentEscaper; |
| 11 | +import java.io.UnsupportedEncodingException; |
| 12 | +import java.net.URLDecoder; |
| 13 | +import java.util.Collections; |
| 14 | +import java.util.HashMap; |
| 15 | +import java.util.Map; |
| 16 | +import java.util.function.BiConsumer; |
| 17 | +import javax.annotation.ParametersAreNonnullByDefault; |
| 18 | +import org.slf4j.Logger; |
| 19 | +import org.slf4j.LoggerFactory; |
| 20 | + |
| 21 | +@ParametersAreNonnullByDefault |
| 22 | +public class BaggagePropagator implements Propagator { |
| 23 | + private static final Logger log = LoggerFactory.getLogger(BaggagePropagator.class); |
| 24 | + private static final PercentEscaper UTF_ESCAPER = PercentEscaper.create(); |
| 25 | + static final String BAGGAGE_KEY = "baggage"; |
| 26 | + private final Config config; |
| 27 | + private final boolean injectBaggage; |
| 28 | + private final boolean extractBaggage; |
| 29 | + |
| 30 | + public BaggagePropagator(Config config) { |
| 31 | + this.injectBaggage = config.isBaggageInject(); |
| 32 | + this.extractBaggage = config.isBaggageExtract(); |
| 33 | + this.config = config; |
| 34 | + } |
| 35 | + |
| 36 | + // use primarily for testing purposes |
| 37 | + public BaggagePropagator(boolean injectBaggage, boolean extractBaggage) { |
| 38 | + this.injectBaggage = injectBaggage; |
| 39 | + this.extractBaggage = extractBaggage; |
| 40 | + config = Config.get(); |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public <C> void inject(Context context, C carrier, CarrierSetter<C> setter) { |
| 45 | + int maxItems = config.getTraceBaggageMaxItems(); |
| 46 | + int maxBytes = config.getTraceBaggageMaxBytes(); |
| 47 | + //noinspection ConstantValue |
| 48 | + if (!this.injectBaggage |
| 49 | + || maxItems == 0 |
| 50 | + || maxBytes == 0 |
| 51 | + || context == null |
| 52 | + || carrier == null |
| 53 | + || setter == null) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + BaggageContext baggageContext = BaggageContext.fromContext(context); |
| 58 | + if (baggageContext == null) { |
| 59 | + log.debug("BaggageContext instance is missing from the following context {}", context); |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + String baggageHeader = baggageContext.getW3cBaggageHeader(); |
| 64 | + if (baggageHeader != null) { |
| 65 | + setter.set(carrier, BAGGAGE_KEY, baggageHeader); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + int processedBaggage = 0; |
| 70 | + int currentBytes = 0; |
| 71 | + StringBuilder baggageText = new StringBuilder(); |
| 72 | + for (final Map.Entry<String, String> entry : baggageContext.asMap().entrySet()) { |
| 73 | + // if there are already baggage items processed, add and allocate bytes for a comma |
| 74 | + int extraBytes = 1; |
| 75 | + if (processedBaggage != 0) { |
| 76 | + baggageText.append(','); |
| 77 | + extraBytes++; |
| 78 | + } |
| 79 | + |
| 80 | + EscapedData escapedKey = UTF_ESCAPER.escapeKey(entry.getKey()); |
| 81 | + EscapedData escapedVal = UTF_ESCAPER.escapeValue(entry.getValue()); |
| 82 | + |
| 83 | + baggageText.append(escapedKey.getData()); |
| 84 | + baggageText.append('='); |
| 85 | + baggageText.append(escapedVal.getData()); |
| 86 | + |
| 87 | + processedBaggage++; |
| 88 | + // reached the max number of baggage items allowed |
| 89 | + if (processedBaggage == maxItems) { |
| 90 | + break; |
| 91 | + } |
| 92 | + // Drop newest k/v pair if adding it leads to exceeding the limit |
| 93 | + if (currentBytes + escapedKey.getSize() + escapedVal.getSize() + extraBytes > maxBytes) { |
| 94 | + baggageText.setLength(currentBytes); |
| 95 | + break; |
| 96 | + } |
| 97 | + currentBytes += escapedKey.getSize() + escapedVal.getSize() + extraBytes; |
| 98 | + } |
| 99 | + |
| 100 | + String baggageString = baggageText.toString(); |
| 101 | + baggageContext.setW3cBaggageHeader(baggageString); |
| 102 | + setter.set(carrier, BAGGAGE_KEY, baggageString); |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + public <C> Context extract(Context context, C carrier, CarrierVisitor<C> visitor) { |
| 107 | + //noinspection ConstantValue |
| 108 | + if (!this.extractBaggage || context == null || carrier == null || visitor == null) { |
| 109 | + return context; |
| 110 | + } |
| 111 | + BaggageContextExtractor baggageContextExtractor = new BaggageContextExtractor(); |
| 112 | + visitor.forEachKeyValue(carrier, baggageContextExtractor); |
| 113 | + BaggageContext extractedContext = baggageContextExtractor.extractedContext; |
| 114 | + if (extractedContext == null) { |
| 115 | + return context; |
| 116 | + } |
| 117 | + return extractedContext.storeInto(context); |
| 118 | + } |
| 119 | + |
| 120 | + public static class BaggageContextExtractor implements BiConsumer<String, String> { |
| 121 | + private BaggageContext extractedContext; |
| 122 | + |
| 123 | + BaggageContextExtractor() {} |
| 124 | + |
| 125 | + /** URL decode value */ |
| 126 | + private String decode(final String value) { |
| 127 | + String decoded = value; |
| 128 | + try { |
| 129 | + decoded = URLDecoder.decode(value, "UTF-8"); |
| 130 | + } catch (final UnsupportedEncodingException | IllegalArgumentException e) { |
| 131 | + log.debug("Failed to decode {}", value); |
| 132 | + } |
| 133 | + return decoded; |
| 134 | + } |
| 135 | + |
| 136 | + private Map<String, String> parseBaggageHeaders(String input) { |
| 137 | + Map<String, String> baggage = new HashMap<>(); |
| 138 | + char keyValueSeparator = '='; |
| 139 | + char pairSeparator = ','; |
| 140 | + int start = 0; |
| 141 | + |
| 142 | + int pairSeparatorInd = input.indexOf(pairSeparator); |
| 143 | + pairSeparatorInd = pairSeparatorInd == -1 ? input.length() : pairSeparatorInd; |
| 144 | + int kvSeparatorInd = input.indexOf(keyValueSeparator); |
| 145 | + while (kvSeparatorInd != -1) { |
| 146 | + int end = pairSeparatorInd; |
| 147 | + if (kvSeparatorInd > end) { |
| 148 | + log.debug( |
| 149 | + "Dropping baggage headers due to key with no value {}", input.substring(start, end)); |
| 150 | + return Collections.emptyMap(); |
| 151 | + } |
| 152 | + String key = decode(input.substring(start, kvSeparatorInd).trim()); |
| 153 | + String value = decode(input.substring(kvSeparatorInd + 1, end).trim()); |
| 154 | + if (key.isEmpty() || value.isEmpty()) { |
| 155 | + log.debug("Dropping baggage headers due to empty k/v {}:{}", key, value); |
| 156 | + return Collections.emptyMap(); |
| 157 | + } |
| 158 | + baggage.put(key, value); |
| 159 | + |
| 160 | + kvSeparatorInd = input.indexOf(keyValueSeparator, pairSeparatorInd + 1); |
| 161 | + pairSeparatorInd = input.indexOf(pairSeparator, pairSeparatorInd + 1); |
| 162 | + pairSeparatorInd = pairSeparatorInd == -1 ? input.length() : pairSeparatorInd; |
| 163 | + start = end + 1; |
| 164 | + } |
| 165 | + return baggage; |
| 166 | + } |
| 167 | + |
| 168 | + @Override |
| 169 | + public void accept(String key, String value) { |
| 170 | + // Only process tags that are relevant to baggage |
| 171 | + if (key != null && key.equalsIgnoreCase(BAGGAGE_KEY)) { |
| 172 | + Map<String, String> baggage = parseBaggageHeaders(value); |
| 173 | + if (!baggage.isEmpty()) { |
| 174 | + extractedContext = BaggageContext.create(baggage, value); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | +} |
0 commit comments