summaryrefslogtreecommitdiffstats
path: root/simplemetrics/src/main/java/com/yahoo/metrics/simple/DimensionCache.java
blob: 83d6d6142e018a8779de76a0a5a35c1cbfd412f3 (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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * The persistence layer for metrics. Both CPU and memory hungry, but
 * it runs in its own little world.
 *
 * @author <a href="mailto:steinar@yahoo-inc.com">Steinar Knutsen</a>
 */
class DimensionCache {

    private final Map<String, LinkedHashMap<Point, UntypedMetric>> persistentData = new HashMap<>();
    private final int pointsToKeep;

    public DimensionCache(int pointsToKeep) {
        this.pointsToKeep = pointsToKeep;
    }

    void updateDimensionPersistence(Bucket toDelete, Bucket toPresent) {
        updatePersistentData(toDelete);
        padPresentation(toPresent);
    }

    private void padPresentation(Bucket toPresent) {
        Map<String, List<Entry<Point, UntypedMetric>>> currentMetricNames = toPresent.getValuesByMetricName();

        for (Map.Entry<String, List<Entry<Point, UntypedMetric>>> metric : currentMetricNames.entrySet()) {
            final int currentDataPoints = metric.getValue().size();
            if (currentDataPoints < pointsToKeep) {
                padMetric(metric.getKey(), toPresent, currentDataPoints);
            }
        }
        Set<String> keysMissingFromPresentation = new HashSet<>(persistentData.keySet());
        keysMissingFromPresentation.removeAll(currentMetricNames.keySet());
        for (String cachedMetric : keysMissingFromPresentation) {
            padMetric(cachedMetric, toPresent, 0);
        }
    }

    private void updatePersistentData(Bucket toDelete) {
        if (toDelete == null) {
            return;
        }
        for (Map.Entry<String, List<Entry<Point, UntypedMetric>>> metric : toDelete.getValuesByMetricName().entrySet()) {
            LinkedHashMap<Point, UntypedMetric> cachedPoints = getCachedMetric(metric.getKey());

            for (Entry<Point, UntypedMetric> newestInterval : metric.getValue()) {
                // overwriting an existing entry does not update the order
                // in the map
                cachedPoints.remove(newestInterval.getKey());
                cachedPoints.put(newestInterval.getKey(), newestInterval.getValue());
            }
        }
    }

    private void padMetric(String metric,
            Bucket toPresent,
            int currentDataPoints) {
        final LinkedHashMap<Point, UntypedMetric>  cachedPoints = getCachedMetric(metric);
        int toAdd = pointsToKeep - currentDataPoints;
        @SuppressWarnings({"unchecked","rawtypes"})
            Entry<Point, UntypedMetric>[] cachedEntries = cachedPoints.entrySet().toArray(new Entry[0]);
        for (int i = cachedEntries.length - 1; i >= 0 && toAdd > 0; --i) {
            Entry<Point, UntypedMetric> leastOld = cachedEntries[i];
            final Identifier id = new Identifier(metric, leastOld.getKey());
            if (!toPresent.hasIdentifier(id)) {
                toPresent.put(id, leastOld.getValue().pruneData());
                --toAdd;
            }
        }
    }

    @SuppressWarnings("serial")
    private LinkedHashMap<Point, UntypedMetric> getCachedMetric(String metricName) {
        LinkedHashMap<Point, UntypedMetric> points = persistentData.get(metricName);
        if (points == null) {
            points = new LinkedHashMap<Point, UntypedMetric>(16, 0.75f, false) {
                protected boolean removeEldestEntry(Map.Entry<Point, UntypedMetric> eldest) {
                    return size() > pointsToKeep;
                }
            };
            persistentData.put(metricName, points);
        }
        return points;
    }

}