|
| 1 | +/* |
| 2 | + * Copyright 2018 Bruno Green. |
| 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.arpnetworking.metrics.mad.parsers; |
| 17 | + |
| 18 | +import com.arpnetworking.commons.builder.ThreadLocalBuilder; |
| 19 | +import com.arpnetworking.metrics.common.parsers.Parser; |
| 20 | +import com.arpnetworking.metrics.common.parsers.exceptions.ParsingException; |
| 21 | +import com.arpnetworking.metrics.mad.model.DefaultMetric; |
| 22 | +import com.arpnetworking.metrics.mad.model.DefaultRecord; |
| 23 | +import com.arpnetworking.metrics.mad.model.HttpRequest; |
| 24 | +import com.arpnetworking.metrics.mad.model.Metric; |
| 25 | +import com.arpnetworking.metrics.mad.model.Record; |
| 26 | +import com.arpnetworking.metrics.prometheus.Remote; |
| 27 | +import com.arpnetworking.metrics.prometheus.Types; |
| 28 | +import com.arpnetworking.metrics.prometheus.Types.TimeSeries; |
| 29 | +import com.arpnetworking.tsdcore.model.MetricType; |
| 30 | +import com.arpnetworking.tsdcore.model.Quantity; |
| 31 | +import com.arpnetworking.tsdcore.model.Unit; |
| 32 | +import com.google.common.base.MoreObjects; |
| 33 | +import com.google.common.collect.ImmutableList; |
| 34 | +import com.google.common.collect.ImmutableMap; |
| 35 | +import com.google.common.collect.ImmutableSet; |
| 36 | +import com.google.common.collect.Lists; |
| 37 | +import com.google.protobuf.InvalidProtocolBufferException; |
| 38 | +import net.sf.oval.exception.ConstraintsViolatedException; |
| 39 | +import org.xerial.snappy.Snappy; |
| 40 | + |
| 41 | +import java.io.IOException; |
| 42 | +import java.time.Instant; |
| 43 | +import java.time.ZoneOffset; |
| 44 | +import java.time.ZonedDateTime; |
| 45 | +import java.util.List; |
| 46 | +import java.util.Objects; |
| 47 | +import java.util.Optional; |
| 48 | +import java.util.UUID; |
| 49 | + |
| 50 | +/** |
| 51 | + * Parses the Prometheus protobuf binary protocol into records. |
| 52 | + * |
| 53 | + * @author Bruno Green (bruno dot green at gmail dot com) |
| 54 | + */ |
| 55 | +public final class PrometheusToRecordParser implements Parser<List<Record>, HttpRequest> { |
| 56 | + |
| 57 | + /** |
| 58 | + * public constructor. |
| 59 | + * |
| 60 | + * @param interpretUnits specifies whether or not to interpret units. |
| 61 | + */ |
| 62 | + public PrometheusToRecordParser(final boolean interpretUnits) { |
| 63 | + _interpretUnits = interpretUnits; |
| 64 | + } |
| 65 | + |
| 66 | + /* |
| 67 | + * Parses a unit and the new name from the name of a metric. |
| 68 | + * Prometheus will, by default, add unit names to the end of a metric name. |
| 69 | + * We want to parse that name and apply that unit to the metric. |
| 70 | + * An unit suffix might be added to the name of the metric, we currently have a set of |
| 71 | + * whitelisted suffixes that is most likely not exhaustive. |
| 72 | + * For more information see: https://prometheus.io/docs/practices/naming/ |
| 73 | + */ |
| 74 | + ParseResult parseNameAndUnit(final String name) { |
| 75 | + if (!_interpretUnits) { |
| 76 | + return new ParseResult(name, Optional.empty()); |
| 77 | + } |
| 78 | + final StringBuilder builder = new StringBuilder(); |
| 79 | + for (int i = name.length() - 1; i >= 0; i--) { |
| 80 | + final char ch = name.charAt(i); |
| 81 | + if (ch == '_') { |
| 82 | + final String key = builder.toString(); |
| 83 | + if (PROMETHEUS_AGGREGATION_KEYS.contains(key)) { |
| 84 | + builder.setLength(0); //reset builder |
| 85 | + } else { |
| 86 | + final Unit value = UNIT_MAP.get(key); |
| 87 | + if (value != null) { |
| 88 | + final String newName = name.substring(0, i).concat(name.substring(i + 1 + key.length())); |
| 89 | + return new ParseResult(newName, Optional.of(value)); |
| 90 | + } else { |
| 91 | + return new ParseResult(name, Optional.empty()); |
| 92 | + } |
| 93 | + } |
| 94 | + } else { |
| 95 | + builder.append(ch); |
| 96 | + } |
| 97 | + } |
| 98 | + final String possibleUnit = builder.toString(); |
| 99 | + final Unit value = UNIT_MAP.get(possibleUnit); |
| 100 | + if (value != null) { |
| 101 | + final String newName = name.substring(Math.min(possibleUnit.length() + 1, name.length())); |
| 102 | + return new ParseResult(newName, Optional.of(value)); |
| 103 | + } else { |
| 104 | + return new ParseResult(name, Optional.empty()); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + @Override |
| 109 | + public List<Record> parse(final HttpRequest data) throws ParsingException { |
| 110 | + final List<Record> records = Lists.newArrayList(); |
| 111 | + final byte[] uncompressed; |
| 112 | + try { |
| 113 | + uncompressed = Snappy.uncompress(data.getBody().toArray()); |
| 114 | + } catch (final IOException e) { |
| 115 | + throw new ParsingException("Failed to decompress snappy stream", data.getBody().toArray(), e); |
| 116 | + } |
| 117 | + try { |
| 118 | + final Remote.WriteRequest writeRequest = Remote.WriteRequest.parseFrom(uncompressed); |
| 119 | + for (final TimeSeries timeSeries : writeRequest.getTimeseriesList()) { |
| 120 | + Optional<String> nameOpt = Optional.empty(); |
| 121 | + final ImmutableMap.Builder<String, String> dimensionsBuilder = ImmutableMap.builder(); |
| 122 | + for (final Types.Label label : timeSeries.getLabelsList()) { |
| 123 | + if ("__name__".equals(label.getName())) { |
| 124 | + final String value = label.getValue(); |
| 125 | + nameOpt = Optional.ofNullable(value); |
| 126 | + } else { |
| 127 | + dimensionsBuilder.put(label.getName(), label.getValue()); |
| 128 | + } |
| 129 | + } |
| 130 | + final ParseResult result = parseNameAndUnit(nameOpt.orElse("").trim()); |
| 131 | + final String metricName = result.getName(); |
| 132 | + if (metricName.isEmpty()) { |
| 133 | + throw new ParsingException("Found a metric with an empty name", data.getBody().toArray()); |
| 134 | + } |
| 135 | + final ImmutableMap<String, String> immutableDimensions = dimensionsBuilder.build(); |
| 136 | + for (final Types.Sample sample : timeSeries.getSamplesList()) { |
| 137 | + final Record record = ThreadLocalBuilder.build( |
| 138 | + DefaultRecord.Builder.class, |
| 139 | + b -> b.setId(UUID.randomUUID().toString()) |
| 140 | + .setTime( |
| 141 | + ZonedDateTime.ofInstant( |
| 142 | + Instant.ofEpochMilli(sample.getTimestamp()), |
| 143 | + ZoneOffset.UTC)) |
| 144 | + .setMetrics( |
| 145 | + createMetric( |
| 146 | + metricName, |
| 147 | + sample, |
| 148 | + result.getUnit())) |
| 149 | + .setDimensions(immutableDimensions) |
| 150 | + ); |
| 151 | + records.add(record); |
| 152 | + } |
| 153 | + } |
| 154 | + } catch (final InvalidProtocolBufferException e) { |
| 155 | + throw new ParsingException("Could not create Request message from data", data.getBody().toArray(), e); |
| 156 | + } catch (final ConstraintsViolatedException | IllegalArgumentException e) { |
| 157 | + throw new ParsingException("Could not build record", data.getBody().toArray(), e); |
| 158 | + } |
| 159 | + return records; |
| 160 | + } |
| 161 | + |
| 162 | + private ImmutableMap<String, ? extends Metric> createMetric(final String name, final Types.Sample sample, final Optional<Unit> unit) { |
| 163 | + final Metric metric = ThreadLocalBuilder.build( |
| 164 | + DefaultMetric.Builder.class, |
| 165 | + p -> p |
| 166 | + .setType(MetricType.GAUGE) |
| 167 | + .setValues(ImmutableList.of(createQuantity(sample, unit))) |
| 168 | + .build() |
| 169 | + ); |
| 170 | + return ImmutableMap.of(name, metric); |
| 171 | + } |
| 172 | + |
| 173 | + private Quantity createQuantity(final Types.Sample sample, final Optional<Unit> unit) { |
| 174 | + return ThreadLocalBuilder.build( |
| 175 | + Quantity.Builder.class, |
| 176 | + p -> p |
| 177 | + .setValue(sample.getValue()) |
| 178 | + .setUnit(unit.orElse(null)) |
| 179 | + ); |
| 180 | + } |
| 181 | + |
| 182 | + private static String createUnitMapKey(final String name) { |
| 183 | + return new StringBuilder(name).reverse().toString(); |
| 184 | + } |
| 185 | + |
| 186 | + private final boolean _interpretUnits; |
| 187 | + |
| 188 | + private static final ImmutableMap<String, Unit> UNIT_MAP = ImmutableMap.of( |
| 189 | + createUnitMapKey("seconds"), Unit.SECOND, |
| 190 | + createUnitMapKey("celcius"), Unit.CELCIUS, |
| 191 | + createUnitMapKey("bytes"), Unit.BYTE, |
| 192 | + createUnitMapKey("bits"), Unit.BIT |
| 193 | + ); |
| 194 | + private static final ImmutableSet<String> PROMETHEUS_AGGREGATION_KEYS = ImmutableSet.of( |
| 195 | + createUnitMapKey("total"), |
| 196 | + createUnitMapKey("bucket"), |
| 197 | + createUnitMapKey("sum"), |
| 198 | + createUnitMapKey("avg"), |
| 199 | + createUnitMapKey("count") |
| 200 | + ); |
| 201 | + |
| 202 | + static final class ParseResult { |
| 203 | + |
| 204 | + @Override |
| 205 | + public boolean equals(final Object o) { |
| 206 | + if (this == o) { |
| 207 | + return true; |
| 208 | + } |
| 209 | + if (o == null || getClass() != o.getClass()) { |
| 210 | + return false; |
| 211 | + } |
| 212 | + final ParseResult that = (ParseResult) o; |
| 213 | + return _unit.equals(that._unit) |
| 214 | + && _name.equals(that._name); |
| 215 | + } |
| 216 | + |
| 217 | + @Override |
| 218 | + public String toString() { |
| 219 | + return MoreObjects.toStringHelper(this) |
| 220 | + .add("unit", _unit) |
| 221 | + .add("name", _name) |
| 222 | + .toString(); |
| 223 | + } |
| 224 | + |
| 225 | + @Override |
| 226 | + public int hashCode() { |
| 227 | + return Objects.hash(_unit, _name); |
| 228 | + } |
| 229 | + |
| 230 | + public Optional<Unit> getUnit() { |
| 231 | + return _unit; |
| 232 | + } |
| 233 | + |
| 234 | + public String getName() { |
| 235 | + return _name; |
| 236 | + } |
| 237 | + |
| 238 | + ParseResult(final String name, final Optional<Unit> unit) { |
| 239 | + _unit = unit; |
| 240 | + _name = name; |
| 241 | + } |
| 242 | + |
| 243 | + private final String _name; |
| 244 | + private final Optional<Unit> _unit; |
| 245 | + } |
| 246 | +} |
0 commit comments