aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/monlib/encode/json/json_encoder.cpp
blob: 69da5170f0d3103f0538846505079b2fed985131 (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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#include "json.h"
#include "typed_point.h"

#include <library/cpp/monlib/encode/buffered/buffered_encoder_base.h>
#include <library/cpp/monlib/encode/encoder_state.h>
#include <library/cpp/monlib/metrics/metric.h>
#include <library/cpp/monlib/metrics/metric_value.h>
#include <library/cpp/monlib/metrics/labels.h>

#include <library/cpp/json/writer/json.h>

#include <util/charset/utf8.h>
#include <util/generic/algorithm.h>

namespace NMonitoring {
    namespace {
        enum class EJsonStyle {
            Solomon,
            Cloud
        };

        ///////////////////////////////////////////////////////////////////////
        // TJsonWriter
        ///////////////////////////////////////////////////////////////////////
        class TJsonWriter {
        public:
            TJsonWriter(IOutputStream* out, int indentation, EJsonStyle style, TStringBuf metricNameLabel)
                : Buf_(NJsonWriter::HEM_UNSAFE, out)
                , Style_(style)
                , MetricNameLabel_(metricNameLabel)
                , CurrentMetricName_()
            {
                Buf_.SetIndentSpaces(indentation);
                Buf_.SetWriteNanAsString();
            }

            void WriteTime(TInstant time) {
                if (time != TInstant::Zero()) {
                    Buf_.WriteKey(TStringBuf("ts"));
                    if (Style_ == EJsonStyle::Solomon) {
                        Buf_.WriteULongLong(time.Seconds());
                    } else {
                        Buf_.WriteString(time.ToString());
                    }
                }
            }

            void WriteValue(double value) {
                Buf_.WriteKey(TStringBuf("value"));
                Buf_.WriteDouble(value);
            }

            void WriteValue(i64 value) {
                Buf_.WriteKey(TStringBuf("value"));
                Buf_.WriteLongLong(value);
            }

            void WriteValue(ui64 value) {
                Buf_.WriteKey(TStringBuf("value"));
                Buf_.WriteULongLong(value);
            }

            void WriteValue(IHistogramSnapshot* s) {
                Y_ENSURE(Style_ == EJsonStyle::Solomon);

                Buf_.WriteKey(TStringBuf("hist"));
                Buf_.BeginObject();
                if (ui32 count = s->Count()) {
                    bool hasInf = (s->UpperBound(count - 1) == Max<double>());
                    if (hasInf) {
                        count--;
                    }

                    Buf_.WriteKey(TStringBuf("bounds"));
                    Buf_.BeginList();
                    for (ui32 i = 0; i < count; i++) {
                        Buf_.WriteDouble(s->UpperBound(i));
                    }
                    Buf_.EndList();

                    Buf_.WriteKey(TStringBuf("buckets"));
                    Buf_.BeginList();
                    for (ui32 i = 0; i < count; i++) {
                        Buf_.WriteULongLong(s->Value(i));
                    }
                    Buf_.EndList();

                    if (hasInf) {
                        Buf_.WriteKey(TStringBuf("inf"));
                        Buf_.WriteULongLong(s->Value(count));
                    }
                }
                Buf_.EndObject();
            }

            void WriteValue(ISummaryDoubleSnapshot* s) {
                Y_ENSURE(Style_ == EJsonStyle::Solomon);

                Buf_.WriteKey(TStringBuf("summary"));
                Buf_.BeginObject();

                Buf_.WriteKey(TStringBuf("sum"));
                Buf_.WriteDouble(s->GetSum());

                Buf_.WriteKey(TStringBuf("min"));
                Buf_.WriteDouble(s->GetMin());

                Buf_.WriteKey(TStringBuf("max"));
                Buf_.WriteDouble(s->GetMax());

                Buf_.WriteKey(TStringBuf("last"));
                Buf_.WriteDouble(s->GetLast());

                Buf_.WriteKey(TStringBuf("count"));
                Buf_.WriteULongLong(s->GetCount());

                Buf_.EndObject();
            }

            void WriteValue(TLogHistogramSnapshot* s) {
                Y_ENSURE(Style_ == EJsonStyle::Solomon);

                Buf_.WriteKey(TStringBuf("log_hist"));
                Buf_.BeginObject();

                Buf_.WriteKey(TStringBuf("base"));
                Buf_.WriteDouble(s->Base());

                Buf_.WriteKey(TStringBuf("zeros_count"));
                Buf_.WriteULongLong(s->ZerosCount());

                Buf_.WriteKey(TStringBuf("start_power"));
                Buf_.WriteInt(s->StartPower());

                Buf_.WriteKey(TStringBuf("buckets"));
                Buf_.BeginList();
                for (size_t i = 0; i < s->Count(); ++i) {
                    Buf_.WriteDouble(s->Bucket(i));
                }
                Buf_.EndList();

                Buf_.EndObject();
            }

            void WriteValue(EMetricValueType type, TMetricValue value) {
                switch (type) {
                    case EMetricValueType::DOUBLE:
                        WriteValue(value.AsDouble());
                        break;

                    case EMetricValueType::INT64:
                        WriteValue(value.AsInt64());
                        break;

                    case EMetricValueType::UINT64:
                        WriteValue(value.AsUint64());
                        break;

                    case EMetricValueType::HISTOGRAM:
                        WriteValue(value.AsHistogram());
                        break;

                    case EMetricValueType::SUMMARY:
                        WriteValue(value.AsSummaryDouble());
                        break;

                    case EMetricValueType::LOGHISTOGRAM:
                        WriteValue(value.AsLogHistogram());
                        break;

                    case EMetricValueType::UNKNOWN:
                        ythrow yexception() << "unknown metric value type";
                }
            }

            void WriteLabel(TStringBuf name, TStringBuf value) {
                Y_ENSURE(IsUtf(name), "label name is not valid UTF-8 string");
                Y_ENSURE(IsUtf(value), "label value is not valid UTF-8 string");
                if (Style_ == EJsonStyle::Cloud && name == MetricNameLabel_) {
                    CurrentMetricName_ = value;
                } else {
                    Buf_.WriteKey(name);
                    Buf_.WriteString(value);
                }
            }

            void WriteMetricType(EMetricType type) {
                if (Style_ == EJsonStyle::Cloud) {
                    Buf_.WriteKey("type");
                    Buf_.WriteString(MetricTypeToCloudStr(type));
                } else {
                    Buf_.WriteKey("kind");
                    Buf_.WriteString(MetricTypeToStr(type));
                }
            }

            void WriteName() {
                if (Style_ != EJsonStyle::Cloud) {
                    return;
                }
                if (CurrentMetricName_.empty()) {
                    ythrow yexception() << "label '" << MetricNameLabel_ << "' is not defined";
                }
                Buf_.WriteKey("name");
                Buf_.WriteString(CurrentMetricName_);
                CurrentMetricName_.clear();
            }

        private:
            static TStringBuf MetricTypeToCloudStr(EMetricType type) {
                switch (type) {
                    case EMetricType::GAUGE:
                        return TStringBuf("DGAUGE");
                    case EMetricType::COUNTER:
                        return TStringBuf("COUNTER");
                    case EMetricType::RATE:
                        return TStringBuf("RATE");
                    case EMetricType::IGAUGE:
                        return TStringBuf("IGAUGE");
                    default:
                        ythrow yexception() << "metric type '" << type << "' is not supported by cloud json format";
                }
            }

        protected:
            NJsonWriter::TBuf Buf_;
            EJsonStyle Style_;
            TString MetricNameLabel_;
            TString CurrentMetricName_;
        };

        ///////////////////////////////////////////////////////////////////////
        // TEncoderJson
        ///////////////////////////////////////////////////////////////////////
        class TEncoderJson final: public IMetricEncoder, public TJsonWriter {
        public:
            TEncoderJson(IOutputStream* out, int indentation, EJsonStyle style, TStringBuf metricNameLabel)
                : TJsonWriter{out, indentation, style, metricNameLabel}
            {
            }

            ~TEncoderJson() override {
                Close();
            }

        private:
            void OnStreamBegin() override {
                State_.Expect(TEncoderState::EState::ROOT);
                Buf_.BeginObject();
            }

            void OnStreamEnd() override {
                State_.Expect(TEncoderState::EState::ROOT);
                if (!Buf_.KeyExpected()) {
                    // not closed metrics array
                    Buf_.EndList();
                }
                Buf_.EndObject();
            }

            void OnCommonTime(TInstant time) override {
                State_.Expect(TEncoderState::EState::ROOT);
                WriteTime(time);
            }

            void OnMetricBegin(EMetricType type) override {
                State_.Switch(TEncoderState::EState::ROOT, TEncoderState::EState::METRIC);
                if (Buf_.KeyExpected()) {
                    // first metric, so open metrics array
                    Buf_.WriteKey(TStringBuf(Style_ == EJsonStyle::Solomon ? "sensors" : "metrics"));
                    Buf_.BeginList();
                }
                Buf_.BeginObject();
                WriteMetricType(type);
            }

            void OnMetricEnd() override {
                State_.Switch(TEncoderState::EState::METRIC, TEncoderState::EState::ROOT);
                if (!Buf_.KeyExpected()) {
                    // not closed timeseries array
                    Buf_.EndList();
                }

                if (!TimeSeries_ && LastPoint_.HasValue()) {
                    // we have seen only one point between OnMetricBegin() and
                    // OnMetricEnd() calls
                    WriteTime(LastPoint_.GetTime());
                    WriteValue(LastPoint_.GetValueType(), LastPoint_.GetValue());
                }
                Buf_.EndObject();

                LastPoint_ = {};
                TimeSeries_ = false;
            }

            void OnLabelsBegin() override {
                if (!Buf_.KeyExpected()) {
                    // not closed metrics or timeseries array if labels go after values
                    Buf_.EndList();
                }
                if (State_ == TEncoderState::EState::ROOT) {
                    State_ = TEncoderState::EState::COMMON_LABELS;
                    Buf_.WriteKey(TStringBuf(Style_ == EJsonStyle::Solomon ? "commonLabels" : "labels"));
                } else if (State_ == TEncoderState::EState::METRIC) {
                    State_ = TEncoderState::EState::METRIC_LABELS;
                    Buf_.WriteKey(TStringBuf("labels"));
                } else {
                    State_.ThrowInvalid("expected METRIC or ROOT");
                }
                Buf_.BeginObject();

                EmptyLabels_ = true;
            }

            void OnLabelsEnd() override {
                if (State_ == TEncoderState::EState::METRIC_LABELS) {
                    State_ = TEncoderState::EState::METRIC;
                } else if (State_ == TEncoderState::EState::COMMON_LABELS) {
                    State_ = TEncoderState::EState::ROOT;
                } else {
                    State_.ThrowInvalid("expected LABELS or COMMON_LABELS");
                }

                Y_ENSURE(!EmptyLabels_, "Labels cannot be empty");
                Buf_.EndObject();
                if (State_ == TEncoderState::EState::METRIC) {
                    WriteName();
                }
            }

            void OnLabel(TStringBuf name, TStringBuf value) override {
                if (State_ == TEncoderState::EState::METRIC_LABELS || State_ == TEncoderState::EState::COMMON_LABELS) {
                    WriteLabel(name, value);
                } else {
                    State_.ThrowInvalid("expected LABELS or COMMON_LABELS");
                }

                EmptyLabels_ = false;
            }

            void OnDouble(TInstant time, double value) override {
                State_.Expect(TEncoderState::EState::METRIC);
                Write<double>(time, value);
            }

            void OnInt64(TInstant time, i64 value) override {
                State_.Expect(TEncoderState::EState::METRIC);
                Write<i64>(time, value);
            }

            void OnUint64(TInstant time, ui64 value) override {
                State_.Expect(TEncoderState::EState::METRIC);
                Write<ui64>(time, value);
            }

            void OnHistogram(TInstant time, IHistogramSnapshotPtr snapshot) override {
                State_.Expect(TEncoderState::EState::METRIC);
                Write<IHistogramSnapshot*>(time, snapshot.Get());
            }

            void OnSummaryDouble(TInstant time, ISummaryDoubleSnapshotPtr snapshot) override {
                State_.Expect(TEncoderState::EState::METRIC);
                Write<ISummaryDoubleSnapshot*>(time, snapshot.Get());
            }

            void OnLogHistogram(TInstant time, TLogHistogramSnapshotPtr snapshot) override {
                State_.Expect(TEncoderState::EState::METRIC);
                Write<TLogHistogramSnapshot*>(time, snapshot.Get());
            }

            template <typename T>
            void Write(TInstant time, T value) {
                State_.Expect(TEncoderState::EState::METRIC);

                if (!LastPoint_.HasValue()) {
                    LastPoint_ = {time, value};
                } else {
                    // second point
                    // TODO: output types
                    Y_ENSURE(LastPoint_.GetValueType() == TValueType<T>::Type,
                             "mixed metric value types in one metric");

                    if (!TimeSeries_) {
                        Buf_.WriteKey(TStringBuf("timeseries"));
                        Buf_.BeginList();
                        Buf_.BeginObject();
                        Y_ENSURE(LastPoint_.GetTime() != TInstant::Zero(),
                            "time cannot be empty or zero in a timeseries point");
                        WriteTime(LastPoint_.GetTime());
                        WriteValue(LastPoint_.GetValueType(), LastPoint_.GetValue());
                        Buf_.EndObject();
                        TimeSeries_ = true;
                    }

                    if (TimeSeries_) {
                        Buf_.BeginObject();
                        Y_ENSURE(time != TInstant::Zero(),
                            "time cannot be empty or zero in a timeseries point");

                        WriteTime(time);
                        WriteValue(value);
                        Buf_.EndObject();
                    }
                }
            }

            void Close() override {
                LastPoint_ = {};
            }

        private:
            TEncoderState State_;
            TTypedPoint LastPoint_;
            bool TimeSeries_ = false;
            bool EmptyLabels_ = false;
        };

        ///////////////////////////////////////////////////////////////////////
        // TBufferedJsonEncoder
        ///////////////////////////////////////////////////////////////////////
        class TBufferedJsonEncoder : public TBufferedEncoderBase, public TJsonWriter {
        public:
            TBufferedJsonEncoder(IOutputStream* out, int indentation, EJsonStyle style, TStringBuf metricNameLabel)
                : TJsonWriter{out, indentation, style, metricNameLabel}
            {
                MetricsMergingMode_ = EMetricsMergingMode::MERGE_METRICS;
            }

            ~TBufferedJsonEncoder() override {
                Close();
            }

            void OnLabelsBegin() override {
                TBufferedEncoderBase::OnLabelsBegin();
                EmptyLabels_ = true;
            }

            void OnLabel(TStringBuf name, TStringBuf value) override {
                TBufferedEncoderBase::OnLabel(name, value);
                EmptyLabels_ = false;
            }

            void OnLabel(ui32 name, ui32 value) override {
                TBufferedEncoderBase::OnLabel(name, value);
                EmptyLabels_ = false;
            }

            void OnLabelsEnd() override {
                TBufferedEncoderBase::OnLabelsEnd();
                Y_ENSURE(!EmptyLabels_, "Labels cannot be empty");
            }

            void Close() final {
                if (Closed_) {
                    return;
                }

                Closed_ = true;

                LabelValuesPool_.Build();
                LabelNamesPool_.Build();

                Buf_.BeginObject();

                WriteTime(CommonTime_);
                if (CommonLabels_.size() > 0) {
                    Buf_.WriteKey(TStringBuf(Style_ == EJsonStyle::Solomon ? "commonLabels": "labels"));
                    WriteLabels(CommonLabels_, true);
                }

                if (Metrics_.size() > 0) {
                    Buf_.WriteKey(TStringBuf(Style_ == EJsonStyle::Solomon ? "sensors" : "metrics"));
                    WriteMetrics();
                }

                Buf_.EndObject();
            }

        private:
            void WriteMetrics() {
                Buf_.BeginList();
                for (auto&& metric : Metrics_) {
                    WriteMetric(metric);
                }
                Buf_.EndList();
            }

            void WriteMetric(TMetric& metric) {
                Buf_.BeginObject();

                WriteMetricType(metric.MetricType);

                Buf_.WriteKey(TStringBuf("labels"));
                WriteLabels(metric.Labels, false);

                metric.TimeSeries.SortByTs();
                if (metric.TimeSeries.Size() == 1) {
                    const auto& point = metric.TimeSeries[0];
                    WriteTime(point.GetTime());
                    WriteValue(metric.TimeSeries.GetValueType(), point.GetValue());
                } else if (metric.TimeSeries.Size() > 1) {
                    Buf_.WriteKey(TStringBuf("timeseries"));
                    Buf_.BeginList();
                    metric.TimeSeries.ForEach([this](TInstant time, EMetricValueType type, TMetricValue value) {
                        Buf_.BeginObject();
                        // make gcc 6.1 happy https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61636
                        this->WriteTime(time);
                        this->WriteValue(type, value);
                        Buf_.EndObject();
                    });

                    Buf_.EndList();
                }

                Buf_.EndObject();
            }

            void WriteLabels(const TPooledLabels& labels, bool isCommon) {
                Buf_.BeginObject();

                for (auto i = 0u; i < labels.size(); ++i) {
                    TStringBuf name = LabelNamesPool_.Get(labels[i].Key->Index);
                    TStringBuf value = LabelValuesPool_.Get(labels[i].Value->Index);

                    WriteLabel(name, value);
                }

                Buf_.EndObject();

                if (!isCommon) {
                    WriteName();
                }
            }

        private:
            bool Closed_{false};
            bool EmptyLabels_ = false;
        };
    }

    IMetricEncoderPtr EncoderJson(IOutputStream* out, int indentation) {
        return MakeHolder<TEncoderJson>(out, indentation, EJsonStyle::Solomon, "");
    }

    IMetricEncoderPtr BufferedEncoderJson(IOutputStream* out, int indentation) {
        return MakeHolder<TBufferedJsonEncoder>(out, indentation, EJsonStyle::Solomon, "");
    }

    IMetricEncoderPtr EncoderCloudJson(IOutputStream* out, int indentation, TStringBuf metricNameLabel) {
        return MakeHolder<TEncoderJson>(out, indentation, EJsonStyle::Cloud, metricNameLabel);
    }

    IMetricEncoderPtr BufferedEncoderCloudJson(IOutputStream* out, int indentation, TStringBuf metricNameLabel) {
        return MakeHolder<TBufferedJsonEncoder>(out, indentation, EJsonStyle::Cloud, metricNameLabel);
    }
}