aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/monlib/metrics/labels.cpp
blob: 1eaadb7cba09a47d9cf993ce6504bed61e22d854 (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
#include "labels.h"

#include <util/stream/output.h>
#include <util/string/split.h>

static void OutputLabels(IOutputStream& out, const NMonitoring::ILabels& labels) {
    size_t i = 0;
    out << '{';
    for (const auto& label: labels) {
        if (i++ > 0) {
            out << TStringBuf(", ");
        }
        out << label;
    }
    out << '}';
}

template <>
void Out<NMonitoring::ILabelsPtr>(IOutputStream& out, const NMonitoring::ILabelsPtr& labels) {
    OutputLabels(out, *labels);
}

template <>
void Out<NMonitoring::ILabels>(IOutputStream& out, const NMonitoring::ILabels& labels) {
    OutputLabels(out, labels);
}

template <>
void Out<NMonitoring::ILabel>(IOutputStream& out, const NMonitoring::ILabel& labels) {
    out << labels.Name() << "=" << labels.Value();
}

Y_MONLIB_DEFINE_LABELS_OUT(NMonitoring::TLabels);
Y_MONLIB_DEFINE_LABEL_OUT(NMonitoring::TLabel);

namespace NMonitoring {
    bool TryLoadLabelsFromString(TStringBuf sb, ILabels& labels) {
        if (sb.Empty()) {
            return false;
        }

        if (!sb.StartsWith('{') || !sb.EndsWith('}')) {
            return false;
        }

        sb.Skip(1);
        sb.Chop(1);

        if (sb.Empty()) {
            return true;
        }

        bool ok = true;
        TVector<std::pair<TStringBuf, TStringBuf>> rawLabels;
        StringSplitter(sb).SplitBySet(" ,").SkipEmpty().Consume([&] (TStringBuf label) {
            TStringBuf key, value;
            ok &= label.TrySplit('=', key, value);

            if (!ok) {
                return;
            }

            rawLabels.emplace_back(key, value);
        });

        if (!ok) {
            return false;
        }

        for (auto&& [k, v] : rawLabels) {
            labels.Add(k, v);
        }

        return true;
    }

    bool TryLoadLabelsFromString(IInputStream& is, ILabels& labels) {
        TString str = is.ReadAll();
        return TryLoadLabelsFromString(str, labels);
    }

} // namespace NMonitoring