aboutsummaryrefslogtreecommitdiff
path: root/impl_core/src/main/java/io/opencensus/implcore/stats/RecordUtils.java
blob: fbb593f59cb26231d4469473e7b896656ca1cf46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
 * Copyright 2018, OpenCensus Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.opencensus.implcore.stats;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Maps;
import io.opencensus.common.Function;
import io.opencensus.common.Functions;
import io.opencensus.implcore.stats.MutableAggregation.MutableCount;
import io.opencensus.implcore.stats.MutableAggregation.MutableDistribution;
import io.opencensus.implcore.stats.MutableAggregation.MutableLastValueDouble;
import io.opencensus.implcore.stats.MutableAggregation.MutableLastValueLong;
import io.opencensus.implcore.stats.MutableAggregation.MutableMean;
import io.opencensus.implcore.stats.MutableAggregation.MutableSumDouble;
import io.opencensus.implcore.stats.MutableAggregation.MutableSumLong;
import io.opencensus.implcore.tags.TagContextImpl;
import io.opencensus.stats.Aggregation;
import io.opencensus.stats.Aggregation.Count;
import io.opencensus.stats.Aggregation.Distribution;
import io.opencensus.stats.Aggregation.LastValue;
import io.opencensus.stats.Aggregation.Sum;
import io.opencensus.stats.AggregationData;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measure.MeasureDouble;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.stats.Measurement;
import io.opencensus.stats.Measurement.MeasurementDouble;
import io.opencensus.stats.Measurement.MeasurementLong;
import io.opencensus.tags.InternalUtils;
import io.opencensus.tags.Tag;
import io.opencensus.tags.TagContext;
import io.opencensus.tags.TagKey;
import io.opencensus.tags.TagValue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/*>>>
import org.checkerframework.checker.nullness.qual.Nullable;
*/

@SuppressWarnings("deprecation")
/* Common static utilities for stats recording. */
final class RecordUtils {

  @javax.annotation.Nullable @VisibleForTesting static final TagValue UNKNOWN_TAG_VALUE = null;

  static Map<TagKey, TagValue> getTagMap(TagContext ctx) {
    if (ctx instanceof TagContextImpl) {
      return ((TagContextImpl) ctx).getTags();
    } else {
      Map<TagKey, TagValue> tags = Maps.newHashMap();
      for (Iterator<Tag> i = InternalUtils.getTags(ctx); i.hasNext(); ) {
        Tag tag = i.next();
        tags.put(tag.getKey(), tag.getValue());
      }
      return tags;
    }
  }

  @VisibleForTesting
  static List</*@Nullable*/ TagValue> getTagValues(
      Map<? extends TagKey, ? extends TagValue> tags, List<? extends TagKey> columns) {
    List</*@Nullable*/ TagValue> tagValues = new ArrayList</*@Nullable*/ TagValue>(columns.size());
    // Record all the measures in a "Greedy" way.
    // Every view aggregates every measure. This is similar to doing a GROUPBY view’s keys.
    for (int i = 0; i < columns.size(); ++i) {
      TagKey tagKey = columns.get(i);
      if (!tags.containsKey(tagKey)) {
        // replace not found key values by null.
        tagValues.add(UNKNOWN_TAG_VALUE);
      } else {
        tagValues.add(tags.get(tagKey));
      }
    }
    return tagValues;
  }

  /**
   * Create an empty {@link MutableAggregation} based on the given {@link Aggregation}.
   *
   * @param aggregation {@code Aggregation}.
   * @return an empty {@code MutableAggregation}.
   */
  @VisibleForTesting
  static MutableAggregation createMutableAggregation(
      Aggregation aggregation, final Measure measure) {
    return aggregation.match(
        new Function<Sum, MutableAggregation>() {
          @Override
          public MutableAggregation apply(Sum arg) {
            return measure.match(
                CreateMutableSumDouble.INSTANCE,
                CreateMutableSumLong.INSTANCE,
                Functions.<MutableAggregation>throwAssertionError());
          }
        },
        CreateMutableCount.INSTANCE,
        CreateMutableDistribution.INSTANCE,
        new Function<LastValue, MutableAggregation>() {
          @Override
          public MutableAggregation apply(LastValue arg) {
            return measure.match(
                CreateMutableLastValueDouble.INSTANCE,
                CreateMutableLastValueLong.INSTANCE,
                Functions.<MutableAggregation>throwAssertionError());
          }
        },
        AggregationDefaultFunction.INSTANCE);
  }

  // Covert a mapping from TagValues to MutableAggregation, to a mapping from TagValues to
  // AggregationData.
  static <T> Map<T, AggregationData> createAggregationMap(
      Map<T, MutableAggregation> tagValueAggregationMap, Measure measure) {
    Map<T, AggregationData> map = Maps.newHashMap();
    for (Entry<T, MutableAggregation> entry : tagValueAggregationMap.entrySet()) {
      map.put(entry.getKey(), entry.getValue().toAggregationData());
    }
    return map;
  }

  static double getDoubleValueFromMeasurement(Measurement measurement) {
    return measurement.match(
        GET_VALUE_FROM_MEASUREMENT_DOUBLE,
        GET_VALUE_FROM_MEASUREMENT_LONG,
        Functions.<Double>throwAssertionError());
  }

  // static inner Function classes

  private static final Function<MeasurementDouble, Double> GET_VALUE_FROM_MEASUREMENT_DOUBLE =
      new Function<MeasurementDouble, Double>() {
        @Override
        public Double apply(MeasurementDouble arg) {
          return arg.getValue();
        }
      };

  private static final Function<MeasurementLong, Double> GET_VALUE_FROM_MEASUREMENT_LONG =
      new Function<MeasurementLong, Double>() {
        @Override
        public Double apply(MeasurementLong arg) {
          // TODO: consider checking truncation here.
          return (double) arg.getValue();
        }
      };

  private static final class CreateMutableSumDouble
      implements Function<MeasureDouble, MutableAggregation> {
    @Override
    public MutableAggregation apply(MeasureDouble arg) {
      return MutableSumDouble.create();
    }

    private static final CreateMutableSumDouble INSTANCE = new CreateMutableSumDouble();
  }

  private static final class CreateMutableSumLong
      implements Function<MeasureLong, MutableAggregation> {
    @Override
    public MutableAggregation apply(MeasureLong arg) {
      return MutableSumLong.create();
    }

    private static final CreateMutableSumLong INSTANCE = new CreateMutableSumLong();
  }

  private static final class CreateMutableCount implements Function<Count, MutableAggregation> {
    @Override
    public MutableAggregation apply(Count arg) {
      return MutableCount.create();
    }

    private static final CreateMutableCount INSTANCE = new CreateMutableCount();
  }

  // TODO(songya): remove this once Mean aggregation is completely removed. Before that
  // we need to continue supporting Mean, since it could still be used by users and some
  // deprecated RPC views.
  private static final class AggregationDefaultFunction
      implements Function<Aggregation, MutableAggregation> {
    @Override
    public MutableAggregation apply(Aggregation arg) {
      if (arg instanceof Aggregation.Mean) {
        return MutableMean.create();
      }
      throw new IllegalArgumentException("Unknown Aggregation.");
    }

    private static final AggregationDefaultFunction INSTANCE = new AggregationDefaultFunction();
  }

  private static final class CreateMutableDistribution
      implements Function<Distribution, MutableAggregation> {
    @Override
    public MutableAggregation apply(Distribution arg) {
      return MutableDistribution.create(arg.getBucketBoundaries());
    }

    private static final CreateMutableDistribution INSTANCE = new CreateMutableDistribution();
  }

  private static final class CreateMutableLastValueDouble
      implements Function<MeasureDouble, MutableAggregation> {
    @Override
    public MutableAggregation apply(MeasureDouble arg) {
      return MutableLastValueDouble.create();
    }

    private static final CreateMutableLastValueDouble INSTANCE = new CreateMutableLastValueDouble();
  }

  private static final class CreateMutableLastValueLong
      implements Function<MeasureLong, MutableAggregation> {
    @Override
    public MutableAggregation apply(MeasureLong arg) {
      return MutableLastValueLong.create();
    }

    private static final CreateMutableLastValueLong INSTANCE = new CreateMutableLastValueLong();
  }

  private RecordUtils() {}
}