summaryrefslogtreecommitdiffstats
path: root/metrics/src/main/java/com/yahoo/metrics/SumMetric.java
blob: cc6d693ce1f1f6985df6ee2743a78d78f01ea8a1 (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
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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * @class metrics::CounterMetric
 * @ingroup metrics
 *
 * @brief Counts a value that only moves upwards.
 *
 * NB! If you have a MetricSet subclass you want to create a sum for, use
 * MetricSet itself as the template argument. Otherwise you'll need to override
 * clone(...) in order to make it return the correct type for your
 * implementation.
 */

package com.yahoo.metrics;

import com.yahoo.text.XMLWriter;

import java.util.ArrayList;
import java.util.List;

public class SumMetric extends Metric
{
    ArrayList<Metric> metricsToSum = new ArrayList<Metric>();

    public SumMetric(String name, String tags, String description, MetricSet owner) {
        super(name, tags, description, owner);
        metricsToSum = new ArrayList<Metric>();
    }

    public SumMetric(SumMetric other, MetricSet owner) {
        super(other, owner);


        if (other.owner == null) {
            throw new IllegalStateException(
                    "Cannot copy a sum metric not registered in a metric set, as " +
                            "we need to use parent to detect new metrics to point to.");
        }
        if (owner == null) {
            throw new IllegalStateException(
                    "Cannot copy a sum metric directly. One needs to at least " +
                            "include metric set above it in order to include metrics " +
                            "summed.");
        }

        metricsToSum.ensureCapacity(other.metricsToSum.size());
        List<String> parentPath = other.owner.getPathVector();

        for (Metric metric : other.metricsToSum) {
            List<String> addendPath = metric.getPathVector();
            MetricSet newAddendParent = owner;

            for (int i = parentPath.size(); i < addendPath.size() - 1; ++i) {
                String path = addendPath.get(i);
                Metric child = newAddendParent.getMetric(path);
                if (child == null) {
                    throw new IllegalStateException(
                            "Metric " + path + " in metric set "
                                    + newAddendParent.getPath() + " was expected to " +
                                    "exist. This sounds like a bug.");
                }

                newAddendParent = (MetricSet)child;
            }

            String path = addendPath.get(addendPath.size() - 1);
            Metric child = newAddendParent.getMetric(path);
            if (child == null) {
                throw new IllegalStateException(
                        "Metric " + path + " in metric set "
                                + newAddendParent.getPath() + " was expected to " +
                                "exist. This sounds like a bug.");
            }

            metricsToSum.add(child);
        }
    }

    @Override
    public boolean visit(MetricVisitor visitor, boolean tagAsAutoGenerated) {
        if (metricsToSum.isEmpty()) return true;

        Metric sum = generateSum();

        if (sum == null) {
            return true;
        }

        if (sum instanceof MetricSet) {
            sum.visit(visitor, true);
            return true;
        } else {
            return visitor.visitPrimitiveMetric(sum, true);
        }
    }

    @Override
    public Metric clone(CopyType copyType, MetricSet owner, boolean includeUnused) {
        if (copyType == CopyType.CLONE) {
            return new SumMetric(this, owner);
        }

        Metric sum = null;
        for (Metric metric : metricsToSum) {
            if (sum == null) {
                sum = metric.clone(CopyType.INACTIVE, null, includeUnused);
                sum.setName(getName());
                sum.setDescription(getDescription());
                sum.setTags(getTags());

                if (owner != null) {
                    owner.registerMetric(sum);
                }
            } else {
                metric.addToPart(sum);
            }
        }

        return sum;
    }

    @Override
    public void addToPart(Metric partMetric) {
        Metric m = generateSum();
        if (m != null) {
            m.addToPart(partMetric);
        }
    }

    @Override
    public void addToSnapshot(Metric snapshotMetric) {
        Metric m = generateSum();
        if (m != null) {
            m.addToSnapshot(snapshotMetric);
        }
    }

    public void addMetricToSum(Metric metric) {
        if (owner == null) {
            throw new IllegalStateException(
                    "Sum metric needs to be registered in a parent metric set " +
                            "prior to adding metrics to sum.");
        }
        if (!metricsToSum.isEmpty() && !(metric.getClass().equals(metricsToSum.get(0).getClass()))) {
            throw new IllegalStateException(
                    "All metrics in a metric set must be of the same type.");
        }

        List<String> sumParentPath = owner.getPathVector();
        List<String> addedPath = metric.getPathVector();

        boolean error = false;
        if (addedPath.size() <= sumParentPath.size()) {
            error = true;
        } else for (int i=0; i<sumParentPath.size(); ++i) {
            if (!sumParentPath.get(i).equals(addedPath.get(i))) {
                error = true;
                break;
            }
        }
        if (error) {
            throw new IllegalStateException(
                        "Metric added to sum is required to be a child of the sum's " +
                        "direct parent metric set. (Need not be a direct child) " +
                        "Metric set " + metric.getPath() + " is not a child of " +
                        owner.getPath());
        }

        ArrayList<Metric> metrics = new ArrayList<Metric>(metricsToSum.size() + 1);
        for (int i = 0; i < metricsToSum.size(); ++i) {
            metrics.add(metricsToSum.get(i));
        }
        metrics.add(metric);
        metricsToSum = metrics;
    }

    public void removeMetricFromSum(Metric metric) {
        metricsToSum.remove(metric);
    }

    public Metric generateSum() {
        Metric m = clone(CopyType.INACTIVE, null, true);

        if (m != null) {
            m.owner = owner;
        }
        return m;
    }

    @Override
    public long getLongValue(String id) {
        Metric s = generateSum();
        if (s == null) {
            return 0;
        }
        return s.getLongValue(id);
    }

    @Override
    public double getDoubleValue(String id) {
        Metric s = generateSum();
        if (s == null) {
            return 0.0;
        }
        return generateSum().getDoubleValue(id);
    }

    @Override
    public void logEvent(EventLogger logger, String fullName) {
        Metric s = generateSum();
        if (s != null) {
            s.logEvent(logger, fullName);
        }
    }

    @Override
    public void printXml(XMLWriter writer, int secondsPassed, int verbosity) {
        Metric s = generateSum();
        if (s == null) {
            openXMLTag(writer, verbosity);
            writer.closeTag();
            return;
        }

        generateSum().printXml(writer, secondsPassed, verbosity);
    }

    @Override
    public boolean used() {
        for (Metric m : metricsToSum) {
            if (m.used()) return true;
        }
        return false;
    }

    @Override
    public void reset() {}
}