aboutsummaryrefslogtreecommitdiffstats
path: root/metrics/src/vespa/metrics/metric.cpp
blob: fe9b55501041bb9b965e2e24d5864313933a8573 (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
239
240
241
242
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "metric.h"
#include "countmetric.h"
#include "valuemetric.h"
#include "metricset.h"
#include "memoryconsumption.h"
#include <vespa/vespalib/text/stringtokenizer.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <iterator>
#include <cassert>
#include <algorithm>
#include <ostream>
#include <regex>

namespace metrics {

bool
MetricVisitor::visitCountMetric(const AbstractCountMetric& m, bool autoGenerated)
{
    return visitMetric(m, autoGenerated);
}

bool
MetricVisitor::visitValueMetric(const AbstractValueMetric& m, bool autoGenerated)
{
    return visitMetric(m, autoGenerated);
}

bool
MetricVisitor::visitMetric(const Metric&, bool)
{
    throw vespalib::IllegalStateException(
            "visitMetric called with default implementation. You should either "
            "override specific visit functions or this catchall function.",
            VESPA_STRLOC);
}

namespace {
    std::string namePattern = "[a-zA-Z][_a-zA-Z0-9]*";
    std::regex name_pattern_regex(namePattern);
}

Tag::Tag(vespalib::stringref k)
    : _key(NameRepo::tagKeyId(k)),
      _value(TagValueId::empty_handle)
{ }
Tag::Tag(vespalib::stringref k, vespalib::stringref v)
    : _key(NameRepo::tagKeyId(k)),
      _value(NameRepo::tagValueId(v))
{ }

Tag::Tag(const Tag &) noexcept = default;
Tag & Tag::operator = (const Tag &) = default;
Tag::~Tag() {}

Metric::Metric(const String& name,
               Tags dimensions,
               const String& description,
               MetricSet* owner)
    : _name(NameRepo::metricId(name)),
      _mangledName(_name),
      _description(NameRepo::descriptionId(description)),
      _tags(std::move(dimensions)),
      _owner(nullptr)
{
    verifyConstructionParameters();
    assignMangledNameWithDimensions();
    registerWithOwnerIfRequired(owner);
}


Metric::Metric(const Metric& other, MetricSet* owner)
    : Printable(other),
      _name(other._name),
      _mangledName(other._mangledName),
      _description(other._description),
      _tags(other._tags),
      _owner(nullptr)
{
    assignMangledNameWithDimensions();
    registerWithOwnerIfRequired(owner);
}

Metric::Metric(const Metric& rhs) = default;
Metric & Metric::operator =(const Metric& rhs) = default;

Metric::~Metric() { }

bool
Metric::tagsSpecifyAtLeastOneDimension(const Tags& tags) const
{
    auto hasNonEmptyTagValue = [](const Tag& t) { return t.hasValue(); };
    return std::any_of(tags.begin(), tags.end(), hasNonEmptyTagValue);
}

void
Metric::assignMangledNameWithDimensions()
{
    if (!tagsSpecifyAtLeastOneDimension(_tags)) {
        _mangledName = _name;
        return;
    }
    sortTagsInDeterministicOrder();
    vespalib::string mangled = createMangledNameWithDimensions();
    _mangledName = NameRepo::metricId(mangled);
}

void
Metric::sortTagsInDeterministicOrder()
{
    std::sort(_tags.begin(), _tags.end(), [](const Tag& a, const Tag& b) {
        return a.key() < b.key();
    });
}

vespalib::string
Metric::createMangledNameWithDimensions() const
{
    vespalib::asciistream s;
    s << getName() << '{';
    const size_t sz = _tags.size();
    for (size_t i = 0; i < sz; ++i) {
        const Tag& dimension(_tags[i]);
        if (dimension.value().empty()) {
            continue;
        }
        if (i != 0) {
            s << ',';
        }
        s << dimension.key() << ':' << dimension.value();
    }
    s << '}';
    return s.str();
}

void
Metric::verifyConstructionParameters()
{
    if (getName().size() == 0) {
        throw vespalib::IllegalArgumentException(
                "Metric cannot have empty name", VESPA_STRLOC);
    }
    const auto &name = getName();
    if (!std::regex_search(name.c_str(), name.c_str() + name.size(), name_pattern_regex)) {
        throw vespalib::IllegalArgumentException(
                "Illegal metric name '" + getName() + "'. Names must match pattern "
                + namePattern, VESPA_STRLOC);
    }
}

void
Metric::registerWithOwnerIfRequired(MetricSet* owner)
{
    if (owner) {
        owner->registerMetric(*this);
    }
}

const MetricSet*
Metric::getRoot() const
{
    return (_owner == 0 ? (isMetricSet() ? static_cast<const MetricSet*>(this)
                                         : 0)
                        : _owner->getRoot());
}

vespalib::string
Metric::getPath() const
{
    if (_owner == 0 || _owner->_owner == 0) {
        return getName();
    } else {
        vespalib::string path(_owner->getPath());
        path.append('.');
        path.append(getName());
        return path;
    }
}

std::vector<Metric::String>
Metric::getPathVector() const
{
    std::vector<String> result;
    result.push_back(getName());
    const MetricSet* owner(_owner);
    while (owner != 0) {
        result.push_back(owner->getName());
        owner = owner->_owner;
    }
    std::reverse(result.begin(), result.end());
    return result;
}

bool
Metric::hasTag(const String& tag) const
{
    return std::find_if(_tags.begin(), _tags.end(), [&](const Tag& t) {
        return t.key() == tag;
    }) != _tags.end();
}

void
Metric::addMemoryUsage(MemoryConsumption& mc) const
{
    ++mc._metricCount;
    mc._metricName += mc.getStringMemoryUsage(getName(), mc._metricNameUnique);
    mc._metricDescription += mc.getStringMemoryUsage(getDescription(), mc._metricDescriptionUnique);
    mc._metricTagCount += _tags.size();
    // XXX figure out what we actually want to report from tags here...
    // XXX we don't care about unique strings since they don't matter anymore.
    //mc._metricTags += mc.getStringMemoryUsage(_tags, mc._metricTagsUnique);
    mc._metricMeta += sizeof(Metric);
}

void
Metric::printDebug(std::ostream& out, const std::string& indent) const
{
    (void) indent;
    out << "name=" << getName() << ", instance=" << ((const void*) this)
        << ", owner=" << ((const void*) _owner);
}

Metric*
Metric::assignValues(const Metric& m) {
    std::vector<Metric::UP> ownerList;
    const_cast<Metric&>(m).addToSnapshot(*this, ownerList);
    // As this should only be called among active metrics, all metrics
    // should exist and owner list should thus always end up empty.
    assert(ownerList.empty());
    return this;
}

bool
Metric::is_sum_metric() const
{
    return false;
}

} // metrics