aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/main/java/com/yahoo/metrics/simple/Bucket.java
blob: 516f9461f4037936a49b7640e0a99eeb001b3160 (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;

import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import com.yahoo.collections.LazyMap;
import com.yahoo.collections.LazySet;
import java.util.logging.Level;

/**
 * An aggregation of data which is only written to from a single thread.
 *
 * @author Steinar Knutsen
 */
public class Bucket {

    private static final Logger log = Logger.getLogger(Bucket.class.getName());
    private final Map<Identifier, UntypedMetric> values = LazyMap.newHashMap();

    boolean gotTimeStamps;
    long fromMillis;
    long toMillis;

    public Bucket() {
        this.gotTimeStamps = false;
        this.fromMillis = 0;
        this.toMillis = 0;
    }

    public Bucket(long fromMillis, long toMillis) {
        this.gotTimeStamps = true;
        this.fromMillis = fromMillis;
        this.toMillis = toMillis;
    }

    public Set<Map.Entry<Identifier, UntypedMetric>> entrySet() {
        return values.entrySet();
    }

    void put(Sample x) {
        UntypedMetric value = get(x);
        Measurement m = x.getMeasurement();
        switch (x.getMetricType()) {
            case GAUGE:
                value.put(m.getMagnitude());
                break;
            case COUNTER:
                value.add(m.getMagnitude());
                break;
            default:
                throw new IllegalArgumentException("Unsupported metric type: " + x.getMetricType());
        }
    }

    void put(Identifier id, UntypedMetric value) {
        values.put(id, value);
    }

    boolean hasIdentifier(Identifier id) {
        return values.containsKey(id);
    }

    void merge(Bucket other, boolean otherIsNewer) {
        LazySet<String> malformedMetrics = LazySet.newHashSet();
        for (Map.Entry<Identifier, UntypedMetric> entry : other.values.entrySet()) {
            String metricName = entry.getKey().getName();
            try {
                if (!malformedMetrics.contains(metricName)) {
                    get(entry.getKey(), entry.getValue()).merge(entry.getValue(), otherIsNewer);
                }
            } catch (IllegalArgumentException e) {
                log.log(Level.WARNING, "Problems merging metric " + metricName + ", possibly ignoring data.");
                // avoid spamming the log if there are a lot of mismatching
                // threads
                malformedMetrics.add(metricName);
            }
        }
    }

    void merge(Bucket other) {
        boolean otherIsNewer = resolveTimeStamps(other);
        merge(other, otherIsNewer);
    }

    private boolean resolveTimeStamps(Bucket other) {
        boolean otherIsNewer = other.fromMillis > this.fromMillis;
        if (! gotTimeStamps) {
            fromMillis = other.fromMillis;
            toMillis = other.toMillis;
            gotTimeStamps = other.gotTimeStamps;
        } else if (other.gotTimeStamps) {
            fromMillis = Math.min(fromMillis, other.fromMillis);
            toMillis = Math.max(toMillis, other.toMillis);
        }
        return otherIsNewer;
    }

    private UntypedMetric get(Sample sample) {
        Identifier dim = sample.getIdentifier();
        UntypedMetric v = values.get(dim);

        if (v == null) {
            // please keep inside guard, as sample.getHistogramDefinition(String) touches a volatile
            v = new UntypedMetric(sample.getHistogramDefinition(dim.getName()));
            values.put(dim, v);
        }
        return v;
    }

    private UntypedMetric get(Identifier dim, UntypedMetric other) {
        UntypedMetric v = values.get(dim);

        if (v == null) {
            v = new UntypedMetric(other.getMetricDefinition());
            values.put(dim, v);
        }
        return v;
    }

    public Collection<String> getAllMetricNames() {
        Set<String> names = new HashSet<>();
        for (Identifier id : values.keySet()) {
            names.add(id.getName());
        }
        return names;
    }

    public Collection<Map.Entry<Point, UntypedMetric>> getValuesForMetric(String metricName) {
        List<Map.Entry<Point, UntypedMetric>> singleMetric = new ArrayList<>();
        for (Map.Entry<Identifier, UntypedMetric> entry : values.entrySet()) {
            if (metricName.equals(entry.getKey().getName())) {
                singleMetric.add(locationValuePair(entry));
            }
        }
        return singleMetric;
    }

    public Map<Point, UntypedMetric> getMapForMetric(String metricName) {
        Map<Point, UntypedMetric> result = new HashMap<>();
        for (Map.Entry<Identifier, UntypedMetric> entry : values.entrySet()) {
            if (metricName.equals(entry.getKey().getName())) {
                result.put(entry.getKey().getLocation(), entry.getValue());
            }
        }
        return result;
    }

    public Map<String, List<Map.Entry<Point, UntypedMetric>>> getValuesByMetricName() {
        Map<String, List<Map.Entry<Point, UntypedMetric>>> result = new HashMap<>();
        for (Map.Entry<Identifier, UntypedMetric> entry : values.entrySet()) {
            List<Map.Entry<Point, UntypedMetric>> singleMetric;
            if (result.containsKey(entry.getKey().getName())) {
                singleMetric = result.get(entry.getKey().getName());
            } else {
                singleMetric = new ArrayList<>();
                result.put(entry.getKey().getName(), singleMetric);
            }
            singleMetric.add(locationValuePair(entry));
        }
        return result;
    }

    private SimpleImmutableEntry<Point, UntypedMetric> locationValuePair(Map.Entry<Identifier, UntypedMetric> entry) {
        return new SimpleImmutableEntry<>(entry.getKey().getLocation(), entry.getValue());
    }

    @Override
    public String toString() {
        return "Bucket [values=" + toString(values.entrySet(), 3) + "]";
    }

    private String toString(Collection<?> collection, int maxLen) {
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        int i = 0;
        for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {
            if (i > 0) {
                builder.append(", ");
            }
            builder.append(iterator.next());
        }
        builder.append("]");
        return builder.toString();
    }

    /**
     * This bucket contains data newer than approximately this point in time.
     */
    public long getFromMillis() {
        return fromMillis;
    }

    /**
     * This bucket contains data older than approximately this point in time.
     */
    public long getToMillis() {
        return toMillis;
    }

}