aboutsummaryrefslogtreecommitdiff
path: root/impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java
blob: 641737134ab11f86dc5f08ac1a570569f8308e77 (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
/*
 * Copyright 2017, 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.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import io.opencensus.common.Clock;
import io.opencensus.common.Function;
import io.opencensus.common.Functions;
import io.opencensus.common.Timestamp;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measurement;
import io.opencensus.stats.Measurement.MeasurementDouble;
import io.opencensus.stats.Measurement.MeasurementLong;
import io.opencensus.stats.StatsCollectionState;
import io.opencensus.stats.View;
import io.opencensus.stats.View.AggregationWindow;
import io.opencensus.stats.ViewData;
import io.opencensus.tags.TagContext;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.concurrent.GuardedBy;

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

/** A class that stores a singleton map from {@code MeasureName}s to {@link MutableViewData}s. */
final class MeasureToViewMap {

  /*
   * A synchronized singleton map that stores the one-to-many mapping from Measures
   * to MutableViewDatas.
   */
  @GuardedBy("this")
  private final Multimap<String, MutableViewData> mutableMap =
      HashMultimap.<String, MutableViewData>create();

  @GuardedBy("this")
  private final Map<View.Name, View> registeredViews = new HashMap<View.Name, View>();

  // TODO(songya): consider adding a Measure.Name class
  @GuardedBy("this")
  private final Map<String, Measure> registeredMeasures = Maps.newHashMap();

  // Cached set of exported views. It must be set to null whenever a view is registered or
  // unregistered.
  @javax.annotation.Nullable private volatile Set<View> exportedViews;

  /** Returns a {@link ViewData} corresponding to the given {@link View.Name}. */
  @javax.annotation.Nullable
  synchronized ViewData getView(View.Name viewName, Clock clock, StatsCollectionState state) {
    MutableViewData view = getMutableViewData(viewName);
    return view == null ? null : view.toViewData(clock.now(), state);
  }

  Set<View> getExportedViews() {
    Set<View> views = exportedViews;
    if (views == null) {
      synchronized (this) {
        exportedViews = views = filterExportedViews(registeredViews.values());
      }
    }
    return views;
  }

  // Returns the subset of the given views that should be exported
  private static Set<View> filterExportedViews(Collection<View> allViews) {
    Set<View> views = Sets.newHashSet();
    for (View view : allViews) {
      if (view.getWindow() instanceof AggregationWindow.Cumulative) {
        views.add(view);
      }
    }
    return Collections.unmodifiableSet(views);
  }

  /** Enable stats collection for the given {@link View}. */
  synchronized void registerView(View view, Clock clock) {
    exportedViews = null;
    View existing = registeredViews.get(view.getName());
    if (existing != null) {
      if (existing.equals(view)) {
        // Ignore views that are already registered.
        return;
      } else {
        throw new IllegalArgumentException(
            "A different view with the same name is already registered: " + existing);
      }
    }
    Measure measure = view.getMeasure();
    Measure registeredMeasure = registeredMeasures.get(measure.getName());
    if (registeredMeasure != null && !registeredMeasure.equals(measure)) {
      throw new IllegalArgumentException(
          "A different measure with the same name is already registered: " + registeredMeasure);
    }
    registeredViews.put(view.getName(), view);
    if (registeredMeasure == null) {
      registeredMeasures.put(measure.getName(), measure);
    }
    mutableMap.put(view.getMeasure().getName(), MutableViewData.create(view, clock.now()));
  }

  @javax.annotation.Nullable
  private synchronized MutableViewData getMutableViewData(View.Name viewName) {
    View view = registeredViews.get(viewName);
    if (view == null) {
      return null;
    }
    Collection<MutableViewData> views = mutableMap.get(view.getMeasure().getName());
    for (MutableViewData viewData : views) {
      if (viewData.getView().getName().equals(viewName)) {
        return viewData;
      }
    }
    throw new AssertionError(
        "Internal error: Not recording stats for view: \""
            + viewName
            + "\" registeredViews="
            + registeredViews
            + ", mutableMap="
            + mutableMap);
  }

  // Records stats with a set of tags.
  synchronized void record(TagContext tags, MeasureMapInternal stats, Timestamp timestamp) {
    Iterator<Measurement> iterator = stats.iterator();
    while (iterator.hasNext()) {
      Measurement measurement = iterator.next();
      Measure measure = measurement.getMeasure();
      if (!measure.equals(registeredMeasures.get(measure.getName()))) {
        // unregistered measures will be ignored.
        continue;
      }
      Collection<MutableViewData> views = mutableMap.get(measure.getName());
      for (MutableViewData view : views) {
        measurement.match(
            new RecordDoubleValueFunc(tags, view, timestamp),
            new RecordLongValueFunc(tags, view, timestamp),
            Functions.</*@Nullable*/ Void>throwAssertionError());
      }
    }
  }

  // Clear stats for all the current MutableViewData
  synchronized void clearStats() {
    for (Entry<String, Collection<MutableViewData>> entry : mutableMap.asMap().entrySet()) {
      for (MutableViewData mutableViewData : entry.getValue()) {
        mutableViewData.clearStats();
      }
    }
  }

  // Resume stats collection for all MutableViewData.
  synchronized void resumeStatsCollection(Timestamp now) {
    for (Entry<String, Collection<MutableViewData>> entry : mutableMap.asMap().entrySet()) {
      for (MutableViewData mutableViewData : entry.getValue()) {
        mutableViewData.resumeStatsCollection(now);
      }
    }
  }

  private static final class RecordDoubleValueFunc implements Function<MeasurementDouble, Void> {
    @Override
    public Void apply(MeasurementDouble arg) {
      view.record(tags, arg.getValue(), timestamp);
      return null;
    }

    private final TagContext tags;
    private final MutableViewData view;
    private final Timestamp timestamp;

    private RecordDoubleValueFunc(TagContext tags, MutableViewData view, Timestamp timestamp) {
      this.tags = tags;
      this.view = view;
      this.timestamp = timestamp;
    }
  }

  private static final class RecordLongValueFunc implements Function<MeasurementLong, Void> {
    @Override
    public Void apply(MeasurementLong arg) {
      view.record(tags, arg.getValue(), timestamp);
      return null;
    }

    private final TagContext tags;
    private final MutableViewData view;
    private final Timestamp timestamp;

    private RecordLongValueFunc(TagContext tags, MutableViewData view, Timestamp timestamp) {
      this.tags = tags;
      this.view = view;
      this.timestamp = timestamp;
    }
  }
}