-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathbmqprometheus_prometheusstatconsumer.cpp
1065 lines (919 loc) · 37.9 KB
/
bmqprometheus_prometheusstatconsumer.cpp
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2023 Bloomberg Finance L.P.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <bmqprometheus_prometheusstatconsumer.h>
// PROMETHEUS
#include <bmqprometheus_version.h>
// MQB
#include <mqbstat_brokerstats.h>
#include <mqbstat_clusterstats.h>
#include <mqbstat_domainstats.h>
#include <mqbstat_queuestats.h>
// BMQ
#include <bmqio_statchannelfactory.h>
#include <bmqsys_statmonitor.h>
#include <bmqsys_threadutil.h>
#include <bmqsys_time.h>
#include <bmqu_memoutstream.h>
// BDE
#include <ball_log.h>
#include <bdlb_arrayutil.h>
#include <bdld_manageddatum.h>
#include <bdlf_bind.h>
#include <bdlt_currenttime.h>
#include <bsl_atomic.h>
#include <bsl_vector.h>
#include <bslmt_condition.h>
#include <bslmt_mutex.h>
#include <bslmt_threadutil.h>
#include <bsls_annotation.h>
#include <bsls_performancehint.h>
// PROMETHEUS
#include "prometheus/counter.h"
#include "prometheus/exposer.h"
#include "prometheus/gateway.h"
#include "prometheus/gauge.h"
#include "prometheus/labels.h"
namespace BloombergLP {
namespace bmqprometheus {
namespace {
BALL_LOG_SET_NAMESPACE_CATEGORY("BMQBRKR.PROMETHEUSSTATCONSUMER");
const char* k_THREADNAME = "bmqPrometheusPush";
class Tagger {
private:
// DATA
::prometheus::Labels labels;
public:
// MANIPULATORS
Tagger& setCluster(const bslstl::StringRef& value)
{
labels["Cluster"] = value;
return *this;
}
Tagger& setDomain(const bslstl::StringRef& value)
{
labels["Domain"] = value;
return *this;
}
Tagger& setTier(const bslstl::StringRef& value)
{
labels["Tier"] = value;
return *this;
}
Tagger& setQueue(const bslstl::StringRef& value)
{
labels["Queue"] = value;
return *this;
}
Tagger& setRole(const bslstl::StringRef& value)
{
labels["Role"] = value;
return *this;
}
Tagger& setInstance(const bslstl::StringRef& value)
{
labels["Instance"] = value;
return *this;
}
Tagger& setRemoteHost(const bslstl::StringRef& value)
{
labels["RemoteHost"] = value;
return *this;
}
Tagger& setDataType(const bslstl::StringRef& value)
{
labels["DataType"] = value;
return *this;
}
Tagger& setAppId(const bslstl::StringRef& value)
{
labels["AppId"] = value;
return *this;
}
Tagger& setPort(const bslstl::StringRef& value)
{
labels["Port"] = value;
return *this;
}
// ACCESSORS
::prometheus::Labels& getLabels() { return labels; }
};
bsl::unique_ptr<PrometheusStatExporter>
makeExporter(const mqbcfg::ExportMode::Value& mode,
const bsl::string& host,
const bsl::size_t port,
std::shared_ptr< ::prometheus::Registry>& registry);
} // close unnamed namespace
// ----------------------------
// class PrometheusStatConsumer
// ----------------------------
void PrometheusStatConsumer::stopImpl()
{
if (!d_isStarted || !d_prometheusStatExporter_p) {
return; // RETURN
}
d_prometheusStatExporter_p->stop();
d_isStarted = false;
}
PrometheusStatConsumer::~PrometheusStatConsumer()
{
stopImpl();
}
PrometheusStatConsumer::PrometheusStatConsumer(
const StatContextsMap& statContextsMap,
BSLS_ANNOTATION_UNUSED bslma::Allocator* allocator)
: d_contextsMap(statContextsMap)
, d_publishInterval(0)
, d_snapshotInterval(0)
, d_snapshotId(0)
, d_actionCounter(0)
, d_isStarted(false)
, d_prometheusRegistry_p(std::make_shared< ::prometheus::Registry>())
{
// Initialize stat contexts
d_systemStatContext_p = getStatContext("system");
d_brokerStatContext_p = getStatContext("broker");
d_clustersStatContext_p = getStatContext("clusters");
d_clusterNodesStatContext_p = getStatContext("clusterNodes");
d_domainsStatContext_p = getStatContext("domains");
d_domainQueuesStatContext_p = getStatContext("domainQueues");
d_clientStatContext_p = getStatContext("clients");
d_channelsStatContext_p = getStatContext("channels");
}
int PrometheusStatConsumer::start(
BSLS_ANNOTATION_UNUSED bsl::ostream& errorDescription)
{
d_consumerConfig_p = mqbplug::StatConsumerUtil::findConsumerConfig(name());
if (!d_consumerConfig_p) {
BALL_LOG_ERROR << "Could not find config for StatConsumer '" << name()
<< "'";
return -1; // RETURN
}
const mqbcfg::AppConfig& brkrCfg = mqbcfg::BrokerConfig::get();
d_publishInterval = d_consumerConfig_p->publishInterval();
d_snapshotInterval = brkrCfg.stats().snapshotInterval();
if (!isEnabled() || d_isStarted) {
return 0; // RETURN
}
setActionCounter();
d_snapshotId = static_cast<int>(d_publishInterval.seconds() /
d_snapshotInterval.seconds());
const auto& prometheusCfg = d_consumerConfig_p->prometheusSpecific();
if (prometheusCfg.isNull()) {
BALL_LOG_ERROR
<< "Could not find 'prometheusSpecific' section in the config";
return -2; // RETURN
}
if (!d_prometheusStatExporter_p) {
d_prometheusStatExporter_p = makeExporter(prometheusCfg->mode(),
prometheusCfg->host(),
prometheusCfg->port(),
d_prometheusRegistry_p);
}
if (!d_prometheusStatExporter_p) {
BALL_LOG_ERROR
<< "Could not create an instance of PrometheusStatExporter";
return -3; // RETURN
}
if (0 != d_prometheusStatExporter_p->start()) {
BALL_LOG_ERROR << "Could not start the PrometheusStatExporter";
return -4; // RETURN
}
d_isStarted = true;
return 0;
}
void PrometheusStatConsumer::stop()
{
stopImpl();
}
void PrometheusStatConsumer::onSnapshot()
{
// executed by the *SCHEDULER* thread of StatController
if (!isEnabled()) {
return; // RETURN
}
if (--d_actionCounter != 0) {
return; // RETURN
}
setActionCounter();
captureSystemStats();
captureNetworkStats();
captureBrokerStats();
LeaderSet leaders;
collectLeaders(&leaders);
captureClusterStats(leaders);
captureClusterPartitionsStats();
captureDomainStats(leaders);
captureQueueStats();
d_prometheusStatExporter_p->onData();
}
void PrometheusStatConsumer::captureQueueStats()
{
// Lookup the 'domainQueues' stat context
// This is guaranteed to work because it was asserted in the ctor.
const bmqst::StatContext& domainsStatContext =
*d_domainQueuesStatContext_p;
typedef mqbstat::QueueStatsDomain::Stat Stat; // Shortcut
for (bmqst::StatContextIterator domainIt =
domainsStatContext.subcontextIterator();
domainIt;
++domainIt) {
for (bmqst::StatContextIterator queueIt =
domainIt->subcontextIterator();
queueIt;
++queueIt) {
bslma::ManagedPtr<bdld::ManagedDatum> mdSp = queueIt->datum();
bdld::DatumMapRef map = mdSp->datum().theMap();
const auto role = mqbstat::QueueStatsDomain::getValue(
*queueIt,
d_snapshotId,
mqbstat::QueueStatsDomain::Stat::e_ROLE);
Tagger tagger;
tagger.setCluster(map.find("cluster")->theString())
.setDomain(map.find("domain")->theString())
.setTier(map.find("tier")->theString())
.setQueue(map.find("queue")->theString())
.setRole(mqbstat::QueueStatsDomain::Role::toAscii(
static_cast<mqbstat::QueueStatsDomain::Role::Enum>(role)))
.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setDataType("host-data");
const auto labels = tagger.getLabels();
// Heartbeat metric
{
// This metric is *always* reported for every queue, so that
// there is guarantee to always (i.e. at any point in time) be
// a time series containing all the tags that can be leveraged
// in Grafana.
auto& heartbeatGauge = ::prometheus::BuildGauge()
.Name("queue_heartbeat")
.Register(*d_prometheusRegistry_p);
heartbeatGauge.Add(labels).Set(0);
}
// Queue metrics
{ // for scoping only
static const DatapointDef defs[] = {
{"queue_producers_count", Stat::e_NB_PRODUCER, false},
{"queue_consumers_count", Stat::e_NB_CONSUMER, false},
{"queue_put_msgs", Stat::e_PUT_MESSAGES_DELTA, true},
{"queue_put_bytes", Stat::e_PUT_BYTES_DELTA, true},
{"queue_push_msgs", Stat::e_PUSH_MESSAGES_DELTA, true},
{"queue_push_bytes", Stat::e_PUSH_BYTES_DELTA, true},
{"queue_ack_msgs", Stat::e_ACK_DELTA, true},
{"queue_ack_time_avg", Stat::e_ACK_TIME_AVG, false},
{"queue_ack_time_max", Stat::e_ACK_TIME_MAX, false},
{"queue_nack_msgs", Stat::e_NACK_DELTA, true},
{"queue_confirm_msgs", Stat::e_CONFIRM_DELTA, true},
{"queue_confirm_time_avg",
Stat::e_CONFIRM_TIME_AVG,
false},
{"queue_confirm_time_max",
Stat::e_CONFIRM_TIME_MAX,
false}};
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
// If there are subcontexts, skip 'confirm_time_max'
// metric, it will be processed later.
if (static_cast<mqbstat::QueueStatsDomain::Stat::Enum>(
dpIt->d_stat) == Stat::e_CONFIRM_TIME_MAX &&
queueIt->numSubcontexts() > 0) {
continue;
}
const bsls::Types::Int64 value =
mqbstat::QueueStatsDomain::getValue(
*queueIt,
d_snapshotId,
static_cast<mqbstat::QueueStatsDomain::Stat::Enum>(
dpIt->d_stat));
updateMetric(dpIt, labels, value);
}
}
// The following metrics only make sense to be reported from the
// primary node only.
if (role == mqbstat::QueueStatsDomain::Role::e_PRIMARY) {
static const DatapointDef defs[] = {
{"queue_gc_msgs", Stat::e_GC_MSGS_DELTA, true},
{"queue_cfg_msgs", Stat::e_CFG_MSGS, false},
{"queue_cfg_bytes", Stat::e_CFG_BYTES, false},
{"queue_content_msgs_max", Stat::e_MESSAGES_MAX, false},
{"queue_msgs_utilization",
Stat::e_MESSAGES_UTILIZATION,
false},
{"queue_content_bytes_max", Stat::e_BYTES_MAX, false},
{"queue_bytes_utilization",
Stat::e_BYTES_UTILIZATION,
false},
{"queue_queue_time_avg", Stat::e_QUEUE_TIME_AVG, false},
{"queue_queue_time_max", Stat::e_QUEUE_TIME_MAX, false},
{"queue_reject_msgs", Stat::e_REJECT_DELTA, true},
{"queue_nack_noquorum_msgs",
Stat::e_NO_SC_MSGS_DELTA,
true},
};
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
// If there are subcontexts, skip 'cqueue_time_max' metric,
// it will be processed later.
if (static_cast<mqbstat::QueueStatsDomain::Stat::Enum>(
dpIt->d_stat) == Stat::e_QUEUE_TIME_MAX &&
queueIt->numSubcontexts() > 0) {
continue;
}
const bsls::Types::Int64 value =
mqbstat::QueueStatsDomain::getValue(
*queueIt,
d_snapshotId,
static_cast<mqbstat::QueueStatsDomain::Stat::Enum>(
dpIt->d_stat));
updateMetric(dpIt, labels, value);
}
}
// Add `appId` tag to metrics.
// These per-appId metrics exist for both primary and replica
static const DatapointDef defsCommon[] = {
{"queue_confirm_time_max", Stat::e_CONFIRM_TIME_MAX, false},
};
// These per-appId metrics exist only for primary
static const DatapointDef defsPrimary[] = {
{"queue_queue_time_max", Stat::e_QUEUE_TIME_MAX, false},
{"queue_content_msgs_max", Stat::e_MESSAGES_MAX, false},
{"queue_content_bytes_max", Stat::e_BYTES_MAX, false},
};
for (bmqst::StatContextIterator appIdIt =
queueIt->subcontextIterator();
appIdIt;
++appIdIt) {
tagger.setAppId(appIdIt->name());
const auto labels = tagger.getLabels();
for (DatapointDefCIter dpIt =
bdlb::ArrayUtil::begin(defsCommon);
dpIt != bdlb::ArrayUtil::end(defsCommon);
++dpIt) {
const bsls::Types::Int64 value =
mqbstat::QueueStatsDomain::getValue(
*appIdIt,
d_snapshotId,
static_cast<mqbstat::QueueStatsDomain::Stat::Enum>(
dpIt->d_stat));
updateMetric(dpIt, labels, value);
}
if (role == mqbstat::QueueStatsDomain::Role::e_PRIMARY) {
for (DatapointDefCIter dpIt =
bdlb::ArrayUtil::begin(defsPrimary);
dpIt != bdlb::ArrayUtil::end(defsPrimary);
++dpIt) {
const bsls::Types::Int64 value =
mqbstat::QueueStatsDomain::getValue(
*appIdIt,
d_snapshotId,
static_cast<
mqbstat::QueueStatsDomain::Stat::Enum>(
dpIt->d_stat));
updateMetric(dpIt, labels, value);
}
}
}
}
}
}
void PrometheusStatConsumer::captureSystemStats()
{
bsl::vector<bsl::pair<bsl::string, double> > datapoints;
const int k_NUM_SYS_STATS = 10;
datapoints.reserve(k_NUM_SYS_STATS);
#define COPY_METRIC(TAIL, ACCESSOR) \
datapoints.emplace_back( \
"brkr_system_" TAIL, \
bmqsys::StatMonitorUtil::ACCESSOR(*d_systemStatContext_p, \
d_snapshotId));
COPY_METRIC("cpu_sys", cpuSystem);
COPY_METRIC("cpu_usr", cpuUser);
COPY_METRIC("cpu_all", cpuAll);
COPY_METRIC("mem_res", memResident);
COPY_METRIC("mem_virt", memVirtual);
COPY_METRIC("os_pagefaults_minor", minorPageFaults);
COPY_METRIC("os_pagefaults_major", majorPageFaults);
COPY_METRIC("os_swaps", numSwaps);
COPY_METRIC("os_ctxswitch_voluntary", voluntaryContextSwitches);
COPY_METRIC("os_ctxswitch_involuntary", involuntaryContextSwitches);
#undef COPY_METRIC
Tagger tagger;
tagger.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setDataType("host-data");
for (bsl::vector<bsl::pair<bsl::string, double> >::iterator it =
datapoints.begin();
it != datapoints.end();
++it) {
auto& gauge = ::prometheus::BuildGauge().Name(it->first).Register(
*d_prometheusRegistry_p);
gauge.Add(tagger.getLabels()).Set(it->second);
}
// POSTCONDITIONS
BSLS_ASSERT_SAFE(datapoints.size() == k_NUM_SYS_STATS);
}
void PrometheusStatConsumer::captureNetworkStats()
{
bsl::vector<bsl::pair<bsl::string, double> > datapoints;
const int k_NUM_NETWORK_STATS = 4;
datapoints.reserve(k_NUM_NETWORK_STATS);
const bmqst::StatContext* localContext =
d_channelsStatContext_p->getSubcontext("local");
const bmqst::StatContext* remoteContext =
d_channelsStatContext_p->getSubcontext("remote");
// NOTE: Should be StatController::k_CHANNEL_STAT_*, but can't due to
// dependency limitations.
Tagger tagger;
tagger.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setDataType("host-data");
#define RETRIEVE_METRIC(TAIL, STAT, CONTEXT) \
datapoints.emplace_back("brkr_system_net_" TAIL, \
bmqio::StatChannelFactoryUtil::getValue( \
*CONTEXT, \
d_snapshotId, \
bmqio::StatChannelFactoryUtil::Stat::STAT));
RETRIEVE_METRIC("local_in_bytes", e_BYTES_IN_DELTA, localContext);
RETRIEVE_METRIC("local_out_bytes", e_BYTES_OUT_DELTA, localContext);
RETRIEVE_METRIC("remote_in_bytes", e_BYTES_IN_DELTA, remoteContext);
RETRIEVE_METRIC("remote_out_bytes", e_BYTES_OUT_DELTA, remoteContext);
#undef RETRIEVE_METRIC
for (bsl::vector<bsl::pair<bsl::string, double> >::iterator it =
datapoints.begin();
it != datapoints.end();
++it) {
auto& counter = ::prometheus::BuildCounter().Name(it->first).Register(
*d_prometheusRegistry_p);
counter.Add(tagger.getLabels()).Increment(it->second);
}
auto reportConnections = [&](const bsl::string& metricName,
const bmqst::StatContext* context) {
// In order to eliminate possible duplication of port contexts
// aggregate them before posting
bsl::unordered_map<bsl::string,
bsl::pair<bsls::Types::Int64, bsls::Types::Int64> >
portMap;
bmqst::StatContextIterator it = context->subcontextIterator();
for (; it; ++it) {
if (it->isDeleted()) {
// As we iterate over 'living' sub contexts in the begining and
// over deleted sub contexts in the end, we can just stop here.
break;
}
tagger.setPort(bsl::to_string(it->id()));
::prometheus::BuildCounter()
.Name("brkr_system_net_" + metricName + "_delta")
.Register(*d_prometheusRegistry_p)
.Add(tagger.getLabels())
.Increment(static_cast<double>(
bmqio::StatChannelFactoryUtil::getValue(
*it,
d_snapshotId,
bmqio::StatChannelFactoryUtil::Stat::
e_CONNECTIONS_DELTA)));
::prometheus::BuildGauge()
.Name("brkr_system_net_" + metricName)
.Register(*d_prometheusRegistry_p)
.Add(tagger.getLabels())
.Set(static_cast<
double>(bmqio::StatChannelFactoryUtil::getValue(
*it,
d_snapshotId,
bmqio::StatChannelFactoryUtil::Stat::e_CONNECTIONS_ABS)));
}
};
reportConnections("local_tcp_connections", localContext);
reportConnections("remote_tcp_connections", remoteContext);
// POSTCONDITIONS
BSLS_ASSERT_SAFE(datapoints.size() == k_NUM_NETWORK_STATS);
}
void PrometheusStatConsumer::captureBrokerStats()
{
typedef mqbstat::BrokerStats::Stat Stat; // Shortcut
static const DatapointDef defs[] = {
{"brkr_summary_queues_count", Stat::e_QUEUE_COUNT, false},
{"brkr_summary_clients_count", Stat::e_CLIENT_COUNT, false},
};
Tagger tagger;
tagger.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setDataType("host-data");
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
const bsls::Types::Int64 value = mqbstat::BrokerStats::getValue(
*d_brokerStatContext_p,
d_snapshotId,
static_cast<Stat::Enum>(dpIt->d_stat));
updateMetric(dpIt, tagger.getLabels(), value);
}
}
void PrometheusStatConsumer::collectLeaders(LeaderSet* leaders)
{
for (bmqst::StatContextIterator clusterIt =
d_clustersStatContext_p->subcontextIterator();
clusterIt;
++clusterIt) {
if (mqbstat::ClusterStats::getValue(
*clusterIt,
d_snapshotId,
mqbstat::ClusterStats::Stat::e_LEADER_STATUS) ==
mqbstat::ClusterStats::LeaderStatus::e_LEADER) {
leaders->insert(clusterIt->name());
}
}
}
void PrometheusStatConsumer::captureClusterStats(const LeaderSet& leaders)
{
const bmqst::StatContext& clustersStatContext = *d_clustersStatContext_p;
for (bmqst::StatContextIterator clusterIt =
clustersStatContext.subcontextIterator();
clusterIt;
++clusterIt) {
typedef mqbstat::ClusterStats::Stat Stat; // Shortcut
// scope
{
static const DatapointDef defs[] = {
{"cluster_healthiness", Stat::e_CLUSTER_STATUS, false},
};
const mqbstat::ClusterStats::Role::Enum role =
static_cast<mqbstat::ClusterStats::Role::Enum>(
mqbstat::ClusterStats::getValue(
*clusterIt,
d_snapshotId,
mqbstat::ClusterStats::Stat::e_ROLE));
Tagger tagger;
tagger.setCluster(clusterIt->name())
.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setRole(mqbstat::ClusterStats::Role::toAscii(role))
.setDataType("host-data");
if (role == mqbstat::ClusterStats::Role::e_PROXY) {
bslma::ManagedPtr<bdld::ManagedDatum> mdSp =
clusterIt->datum();
bdld::DatumMapRef map = mdSp->datum().theMap();
bslstl::StringRef upstream = map.find("upstream")->theString();
tagger.setRemoteHost(upstream.isEmpty() ? "_none_" : upstream);
}
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
const bsls::Types::Int64 value =
mqbstat::ClusterStats::getValue(
*clusterIt,
d_snapshotId,
static_cast<Stat::Enum>(dpIt->d_stat));
updateMetric(dpIt, tagger.getLabels(), value);
}
}
if (leaders.find(clusterIt->name()) != leaders.end()) {
static const DatapointDef defs[] = {
{"cluster_partition_cfg_journal_bytes",
Stat::e_PARTITION_CFG_JOURNAL_BYTES,
false},
{"cluster_partition_cfg_data_bytes",
Stat::e_PARTITION_CFG_DATA_BYTES,
false},
};
Tagger tagger;
tagger.setCluster(clusterIt->name())
.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setDataType("global-data");
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
const bsls::Types::Int64 value =
mqbstat::ClusterStats::getValue(
*clusterIt,
d_snapshotId,
static_cast<Stat::Enum>(dpIt->d_stat));
updateMetric(dpIt, tagger.getLabels(), value);
}
}
}
}
void PrometheusStatConsumer::captureClusterPartitionsStats()
{
// Iterate over each cluster
for (bmqst::StatContextIterator clusterIt =
d_clustersStatContext_p->subcontextIterator();
clusterIt;
++clusterIt) {
// Iterate over each partition
for (bmqst::StatContextIterator partitionIt =
clusterIt->subcontextIterator();
partitionIt;
++partitionIt) {
mqbstat::ClusterStats::PrimaryStatus::Enum primaryStatus =
static_cast<mqbstat::ClusterStats::PrimaryStatus::Enum>(
mqbstat::ClusterStats::getValue(
*partitionIt,
d_snapshotId,
mqbstat::ClusterStats::Stat::
e_PARTITION_PRIMARY_STATUS));
if (primaryStatus !=
mqbstat::ClusterStats::PrimaryStatus::e_PRIMARY) {
// Only report partition stats from the primary node
continue; // CONTINUE
}
// Generate the metric name from the partition name (e.g.,
// 'cluster_partition1_rollover_time')
const bsl::string prefix = "cluster_" + partitionIt->name() + "_";
const bsl::string rollover_time = prefix + "rollover_time";
const bsl::string journal_outstanding_bytes =
prefix + "journal_outstanding_bytes";
const bsl::string data_outstanding_bytes =
prefix + "data_outstanding_bytes";
const DatapointDef defs[] = {
{rollover_time.c_str(),
mqbstat::ClusterStats::Stat::e_PARTITION_ROLLOVER_TIME,
false},
{journal_outstanding_bytes.c_str(),
mqbstat::ClusterStats::Stat::e_PARTITION_JOURNAL_CONTENT,
false},
{data_outstanding_bytes.c_str(),
mqbstat::ClusterStats::Stat::e_PARTITION_DATA_CONTENT,
false}};
Tagger tagger;
tagger.setCluster(clusterIt->name())
.setInstance(mqbcfg::BrokerConfig::get().brokerInstanceName())
.setDataType("global-data");
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
const bsls::Types::Int64 value =
mqbstat::ClusterStats::getValue(
*partitionIt,
d_snapshotId,
static_cast<mqbstat::ClusterStats::Stat::Enum>(
dpIt->d_stat));
updateMetric(dpIt, tagger.getLabels(), value);
}
}
}
}
void PrometheusStatConsumer::captureDomainStats(const LeaderSet& leaders)
{
const bmqst::StatContext& domainsStatContext = *d_domainsStatContext_p;
typedef mqbstat::DomainStats::Stat Stat; // Shortcut
for (bmqst::StatContextIterator domainIt =
domainsStatContext.subcontextIterator();
domainIt;
++domainIt) {
bslma::ManagedPtr<bdld::ManagedDatum> mdSp = domainIt->datum();
bdld::DatumMapRef map = mdSp->datum().theMap();
const bslstl::StringRef clusterName = map.find("cluster")->theString();
if (leaders.find(clusterName) == leaders.end()) {
// is NOT leader
continue; // CONTINUE
}
Tagger tagger;
tagger.setCluster(clusterName)
.setDomain(map.find("domain")->theString())
.setTier(map.find("tier")->theString())
.setDataType("global-data");
static const DatapointDef defs[] = {
{"domain_cfg_msgs", Stat::e_CFG_MSGS, false},
{"domain_cfg_bytes", Stat::e_CFG_BYTES, false},
{"domain_queue_count", Stat::e_QUEUE_COUNT, false},
};
for (DatapointDefCIter dpIt = bdlb::ArrayUtil::begin(defs);
dpIt != bdlb::ArrayUtil::end(defs);
++dpIt) {
const bsls::Types::Int64 value = mqbstat::DomainStats::getValue(
*domainIt,
d_snapshotId,
static_cast<Stat::Enum>(dpIt->d_stat));
updateMetric(dpIt, tagger.getLabels(), value);
}
}
}
void PrometheusStatConsumer::updateMetric(const DatapointDef* def_p,
const ::prometheus::Labels& labels,
const bsls::Types::Int64 value)
{
if (value != 0) {
// To save metrics, only report non-null values
if (def_p->d_isCounter) {
auto& counter = ::prometheus::BuildCounter()
.Name(def_p->d_name)
.Register(*d_prometheusRegistry_p);
counter.Add(labels).Increment(static_cast<double>(value));
}
else {
auto& gauge = ::prometheus::BuildGauge()
.Name(def_p->d_name)
.Register(*d_prometheusRegistry_p);
gauge.Add(labels).Set(static_cast<double>(value));
}
}
}
void PrometheusStatConsumer::setPublishInterval(
bsls::TimeInterval publishInterval)
{
// executed by the *SCHEDULER* thread of StatController
// PRECONDITIONS
BSLS_ASSERT(publishInterval.seconds() >= 0);
BSLS_ASSERT(d_snapshotInterval.seconds() > 0);
BSLS_ASSERT(publishInterval.seconds() % d_snapshotInterval.seconds() == 0);
BALL_LOG_INFO << "Set PrometheusStatConsumer publish interval to "
<< publishInterval;
d_publishInterval = publishInterval;
d_snapshotId = static_cast<int>(d_publishInterval.seconds() /
d_snapshotInterval.seconds());
setActionCounter();
}
const bmqst::StatContext*
PrometheusStatConsumer::getStatContext(const char* name) const
{
StatContextsMap::const_iterator cIt = d_contextsMap.find(name);
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(cIt == d_contextsMap.end())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
BSLS_ASSERT_SAFE(false &&
"StatContext not found in PrometheusStatConsumer");
return 0; // RETURN
}
return cIt->second;
}
void PrometheusStatConsumer::setActionCounter()
{
// PRECONDITIONS
BSLS_ASSERT(d_snapshotInterval > 0);
BSLS_ASSERT(d_publishInterval >= 0);
BSLS_ASSERT(d_publishInterval.seconds() % d_snapshotInterval.seconds() ==
0);
d_actionCounter = static_cast<int>(d_publishInterval.seconds() /
d_snapshotInterval.seconds());
}
// -----------------------------------------
// class PrometheusStatConsumerPluginFactory
// -----------------------------------------
// CREATORS
PrometheusStatConsumerPluginFactory::PrometheusStatConsumerPluginFactory()
{
// NOTHING
}
PrometheusStatConsumerPluginFactory::~PrometheusStatConsumerPluginFactory()
{
// NOTHING
}
bslma::ManagedPtr<StatConsumer> PrometheusStatConsumerPluginFactory::create(
const StatContextsMap& statContexts,
const CommandProcessorFn& /*commandProcessor*/,
bdlbb::BlobBufferFactory* /*bufferFactory*/,
bslma::Allocator* allocator)
{
allocator = bslma::Default::allocator(allocator);
bslma::ManagedPtr<mqbplug::StatConsumer> result(
new (*allocator) PrometheusStatConsumer(statContexts, allocator),
allocator);
return result;
}
// --------------------------------
// class PrometheusPullStatExporter
// --------------------------------
class PrometheusPullStatExporter : public PrometheusStatExporter {
std::weak_ptr< ::prometheus::Registry> d_registry_p;
bsl::unique_ptr< ::prometheus::Exposer> d_exposer_p;
bsl::string d_exposerEndpoint;
public:
PrometheusPullStatExporter(
const bsl::string& host,
const bsl::size_t port,
const std::shared_ptr< ::prometheus::Registry>& registry)
: d_registry_p(registry)
{
bsl::ostringstream endpoint;
endpoint << host << ":" << port;
d_exposerEndpoint = endpoint.str();
}
int start() override
{
try {
d_exposer_p = bsl::make_unique< ::prometheus::Exposer>(
d_exposerEndpoint);
d_exposer_p->RegisterCollectable(d_registry_p);
return 0; // RETURN
}
catch (const bsl::exception& e) {
BALL_LOG_WARN << "#PROMETHEUS_REPORTING "
<< "Failed to start http server for Prometheus: "
<< e.what();
return -1; // RETURN
}
}
void stop() override { d_exposer_p.reset(); }
};
// --------------------------------
// class PrometheusPushStatExporter
// --------------------------------
class PrometheusPushStatExporter : public PrometheusStatExporter {
bsl::unique_ptr< ::prometheus::Gateway> d_prometheusGateway_p;
/// Handle of the Prometheus publishing thread
bslmt::ThreadUtil::Handle d_prometheusPushThreadHandle;
bslmt::Mutex d_prometheusThreadMutex;
bslmt::Condition d_prometheusThreadCondition;
bsl::atomic_bool d_threadStop;
/// Push gathered statistics to the push gateway in 'push' mode.
/// THREAD: This method is called from the dedicated thread.
void prometheusPushThread()
{
// executed by the dedicated prometheus push thread
bmqsys::ThreadUtil::setCurrentThreadName(k_THREADNAME);
BALL_LOG_INFO << "Prometheus Push thread has started [id: "
<< bslmt::ThreadUtil::selfIdAsUint64() << "]";
auto returnCode = 200;
while (!d_threadStop) {
bslmt::LockGuard<bslmt::Mutex> lock(&d_prometheusThreadMutex);
d_prometheusThreadCondition.wait(&d_prometheusThreadMutex);
auto newReturnCode = d_prometheusGateway_p->Push();
if (newReturnCode != 200 && newReturnCode != returnCode) {
BALL_LOG_WARN << "Push to Prometheus failed with code: "
<< newReturnCode;
}
returnCode = newReturnCode;
}
BALL_LOG_INFO << "Prometheus Push thread terminated "
<< "[id: " << bslmt::ThreadUtil::selfIdAsUint64() << "]";
}
void stopImpl()
{
if (d_threadStop) {
return;
}
d_threadStop = true;
d_prometheusThreadCondition.signal();
bslmt::ThreadUtil::join(d_prometheusPushThreadHandle);
}
public:
PrometheusPushStatExporter(
const bsl::string& host,
const bsl::size_t& port,
const std::shared_ptr< ::prometheus::Registry>& registry)
: d_threadStop(false)
{