Coverage Report

Created: 2025-11-01 07:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/brpc/src/bvar/recorder.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
// Date 2014/09/25 17:50:21
19
20
#ifndef  BVAR_RECORDER_H
21
#define  BVAR_RECORDER_H
22
23
#include <stdint.h>                              // int64_t uint64_t
24
#include "butil/macros.h"                         // BAIDU_CASSERT
25
#include "butil/logging.h"                        // LOG
26
#include "bvar/detail/combiner.h"                // detail::AgentCombiner
27
#include "bvar/variable.h"
28
#include "bvar/window.h"
29
#include "bvar/detail/sampler.h"
30
#if WITH_BABYLON_COUNTER
31
#include "babylon/concurrent/counter.h"
32
#endif // WITH_BABYLON_COUNTER
33
34
namespace bvar {
35
36
struct Stat {
37
0
    Stat() : sum(0), num(0) {}
38
0
    Stat(int64_t sum2, int64_t num2) : sum(sum2), num(num2) {}
39
    int64_t sum;
40
    int64_t num;
41
        
42
0
    int64_t get_average_int() const {
43
        //num can be changed by sampling thread, use tmp_num
44
0
        int64_t tmp_num = num;
45
0
        if (tmp_num == 0) {
46
0
            return 0;
47
0
        }
48
0
        return sum / (int64_t)tmp_num;
49
0
    }
50
0
    double get_average_double() const {
51
0
        int64_t tmp_num = num;
52
0
        if (tmp_num == 0) {
53
0
            return 0.0;
54
0
        }
55
0
        return (double)sum / (double)tmp_num;
56
0
    }
57
0
    Stat operator-(const Stat& rhs) const {
58
0
        return Stat(sum - rhs.sum, num - rhs.num);
59
0
    }
60
0
    void operator-=(const Stat& rhs) {
61
0
        sum -= rhs.sum;
62
0
        num -= rhs.num;
63
0
    }
64
0
    Stat operator+(const Stat& rhs) const {
65
0
        return Stat(sum + rhs.sum, num + rhs.num);
66
0
    }
67
0
    void operator+=(const Stat& rhs) {
68
0
        sum += rhs.sum;
69
0
        num += rhs.num;
70
0
    }
71
};
72
73
0
inline std::ostream& operator<<(std::ostream& os, const Stat& s) {
74
0
    const int64_t v = s.get_average_int();
75
0
    if (v != 0) {
76
0
        return os << v;
77
0
    } else {
78
0
        return os << s.get_average_double();
79
0
    }
80
0
}
81
82
namespace detail {
83
struct AddStat {
84
0
    void operator()(Stat& s1, const Stat& s2) const { s1 += s2; }
85
};
86
87
struct MinusStat {
88
0
    void operator()(Stat& s1, const Stat& s2) const { s1 -= s2; }
89
};
90
} // namespace detail
91
92
// For calculating average of numbers.
93
// Example:
94
//   IntRecorder latency;
95
//   latency << 1 << 3 << 5;
96
//   CHECK_EQ(3, latency.average());
97
#if !WITH_BABYLON_COUNTER
98
class IntRecorder : public Variable {
99
public:
100
    // Compressing format:
101
    // | 20 bits (unsigned) | sign bit | 43 bits |
102
    //       num                   sum
103
    const static size_t SUM_BIT_WIDTH=44;
104
    const static uint64_t MAX_SUM_PER_THREAD = (1ul << SUM_BIT_WIDTH) - 1;
105
    const static uint64_t MAX_NUM_PER_THREAD = (1ul << (64ul - SUM_BIT_WIDTH)) - 1;
106
    BAIDU_CASSERT(SUM_BIT_WIDTH > 32 && SUM_BIT_WIDTH < 64, 
107
                  SUM_BIT_WIDTH_must_be_between_33_and_63);
108
109
    typedef Stat value_type;
110
    typedef detail::ReducerSampler<IntRecorder, Stat,
111
                                   detail::AddStat,
112
                                   detail::MinusStat> sampler_type;
113
114
    typedef Stat SampleSet;
115
    
116
    struct AddToStat {
117
0
        void operator()(Stat& lhs, uint64_t rhs) const {
118
0
            lhs.sum += _extend_sign_bit(_get_sum(rhs));
119
0
            lhs.num += _get_num(rhs);
120
0
        }
121
    };
122
    
123
    typedef detail::AgentCombiner<Stat, uint64_t, AddToStat> combiner_type;
124
    typedef typename combiner_type::self_shared_type shared_combiner_type;
125
    typedef combiner_type::Agent agent_type;
126
127
0
    IntRecorder() : _combiner(std::make_shared<combiner_type>()), _sampler(NULL) {}
128
129
0
    IntRecorder(const butil::StringPiece& name) : IntRecorder() {
130
0
        expose(name);
131
0
    }
132
133
    IntRecorder(const butil::StringPiece& prefix, const butil::StringPiece& name)
134
0
        : IntRecorder() {
135
0
        expose_as(prefix, name);
136
0
    }
137
138
0
    ~IntRecorder() override {
139
0
        hide();
140
0
        if (_sampler) {
141
0
            _sampler->destroy();
142
0
            _sampler = NULL;
143
0
        }
144
0
    }
145
146
    // Note: The input type is acutally int. Use int64_t to check overflow.
147
    IntRecorder& operator<<(int64_t/*note*/ sample);
148
149
0
    int64_t average() const {
150
0
        return _combiner->combine_agents().get_average_int();
151
0
    }
152
153
0
    double average(double) const {
154
0
        return _combiner->combine_agents().get_average_double();
155
0
    }
156
157
0
    Stat get_value() const {
158
0
        return _combiner->combine_agents();
159
0
    }
160
    
161
0
    Stat reset() {
162
0
        return _combiner->reset_all_agents();
163
0
    }
164
165
0
    detail::AddStat op() const { return detail::AddStat(); }
166
0
    detail::MinusStat inv_op() const { return detail::MinusStat(); }
167
    
168
0
    void describe(std::ostream& os, bool /*quote_string*/) const override {
169
0
        os << get_value();
170
0
    }
171
172
0
    bool valid() const { return _combiner->valid(); }
173
    
174
0
    sampler_type* get_sampler() {
175
0
        if (NULL == _sampler) {
176
0
            _sampler = new sampler_type(this);
177
0
            _sampler->schedule();
178
0
        }
179
0
        return _sampler;
180
0
    }
181
182
    // This name is useful for printing overflow log in operator<< since
183
    // IntRecorder is often used as the source of data and not exposed.
184
0
    void set_debug_name(const butil::StringPiece& name) {
185
0
        _debug_name.assign(name.data(), name.size());
186
0
    }
187
    
188
private:
189
    // TODO: The following numeric functions should be independent utils
190
0
    static uint64_t _get_sum(const uint64_t n) {
191
0
        return (n & MAX_SUM_PER_THREAD);
192
0
    }
193
194
0
    static uint64_t _get_num(const uint64_t n) {
195
0
        return n >> SUM_BIT_WIDTH;
196
0
    }
197
198
    // Fill all the first (64 - SUM_BIT_WIDTH + 1) bits with 1 if the sign bit is 1 
199
    // to represent a complete 64-bit negative number
200
    // Check out http://en.wikipedia.org/wiki/Signed_number_representations if
201
    // you are confused
202
0
    static int64_t _extend_sign_bit(const uint64_t sum) {
203
0
        return (((1ul << (64ul - SUM_BIT_WIDTH + 1)) - 1) 
204
0
               * ((1ul << (SUM_BIT_WIDTH - 1) & sum)))
205
0
               | (int64_t)sum;
206
0
    }
207
208
    // Convert complement into a |SUM_BIT_WIDTH|-bit unsigned integer
209
0
    static uint64_t _get_complement(int64_t n) {
210
0
        return n & (MAX_SUM_PER_THREAD);
211
0
    }
212
213
0
    static uint64_t _compress(const uint64_t num, const uint64_t sum) {
214
0
        return (num << SUM_BIT_WIDTH) 
215
               // There is a redundant '1' in the front of sum which was
216
               // combined with two negative number, so truncation has to be 
217
               // done here
218
0
               | (sum & MAX_SUM_PER_THREAD)
219
0
               ;
220
0
    }
221
222
    // Check whether the sum of the two integer overflows the range of signed
223
    // integer with the width of SUM_BIT_WIDTH, which is 
224
    // [-2^(SUM_BIT_WIDTH -1), 2^(SUM_BIT_WIDTH -1) - 1) (eg. [-128, 127) for
225
    // signed 8-bit integer)
226
0
    static bool _will_overflow(const int64_t lhs, const int rhs) {
227
0
        return 
228
            // Both integers are positive and the sum is larger than the largest
229
            // number
230
0
            ((lhs > 0) && (rhs > 0) 
231
0
                && (lhs + rhs > ((int64_t)MAX_SUM_PER_THREAD >> 1)))
232
            // Or both integers are negative and the sum is less than the lowest
233
            // number
234
0
            || ((lhs < 0) && (rhs < 0) 
235
0
                    && (lhs + rhs < (-((int64_t)MAX_SUM_PER_THREAD >> 1)) - 1))
236
            // otherwise the sum cannot overflow iff lhs does not overflow
237
            // because |sum| < |lhs| 
238
0
            ;
239
0
    }
240
241
private:
242
    shared_combiner_type    _combiner;
243
    sampler_type*           _sampler;
244
    std::string             _debug_name;
245
};
246
247
0
inline IntRecorder& IntRecorder::operator<<(int64_t sample) {
248
0
    if (BAIDU_UNLIKELY((int64_t)(int)sample != sample)) {
249
0
        const char* reason = NULL;
250
0
        if (sample > std::numeric_limits<int>::max()) {
251
0
            reason = "overflows";
252
0
            sample = std::numeric_limits<int>::max();
253
0
        } else {
254
0
            reason = "underflows";
255
0
            sample = std::numeric_limits<int>::min();
256
0
        }
257
        // Truncate to be max or min of int. We're using 44 bits to store the
258
        // sum thus following aggregations are not likely to be over/underflow.
259
0
        if (!name().empty()) {
260
0
            LOG(WARNING) << "Input=" << sample << " to `" << name()
261
0
                       << "\' " << reason;
262
0
        } else if (!_debug_name.empty()) {
263
0
            LOG(WARNING) << "Input=" << sample << " to `" << _debug_name
264
0
                       << "\' " << reason;
265
0
        } else {
266
0
            LOG(WARNING) << "Input=" << sample << " to IntRecorder("
267
0
                       << (void*)this << ") " << reason;
268
0
        }
269
0
    }
270
0
    agent_type* agent = _combiner->get_or_create_tls_agent();
271
0
    if (BAIDU_UNLIKELY(!agent)) {
272
0
        LOG(FATAL) << "Fail to create agent";
273
0
        return *this;
274
0
    }
275
0
    uint64_t n;
276
0
    agent->element.load(&n);
277
0
    const uint64_t complement = _get_complement(sample);
278
0
    uint64_t num;
279
0
    uint64_t sum;
280
0
    do {
281
0
        num = _get_num(n);
282
0
        sum = _get_sum(n);
283
0
        if (BAIDU_UNLIKELY((num + 1 > MAX_NUM_PER_THREAD) ||
284
0
                           _will_overflow(_extend_sign_bit(sum), sample))) {
285
            // Although agent->element might have been cleared at this 
286
            // point, it is just OK because the very value is 0 in
287
            // this case
288
0
            _combiner->commit_and_clear(agent);
289
0
            sum = 0;
290
0
            num = 0;
291
0
            n = 0;
292
0
        }
293
0
    } while (!agent->element.compare_exchange_weak(
294
0
                 n, _compress(num + 1, sum + complement)));
295
0
    return *this;
296
0
}
297
#else // WITH_BABYLON_COUNTER
298
class IntRecorder : public Variable {
299
public:
300
    typedef Stat value_type;
301
    typedef detail::AddStat Op;
302
    typedef detail::MinusStat InvOp;
303
    typedef detail::ReducerSampler<IntRecorder, value_type, Op, InvOp> sampler_type;
304
305
    COMMON_VARIABLE_CONSTRUCTOR(IntRecorder);
306
307
    DISALLOW_COPY_AND_MOVE(IntRecorder);
308
309
    ~IntRecorder() override {
310
        hide();
311
        if (NULL != _sampler) {
312
            _sampler->destroy();
313
        }
314
    }
315
316
    // Note: The input type is acutally int. Use int64_t to check overflow.
317
    IntRecorder& operator<<(int64_t value) {
318
        if (BAIDU_UNLIKELY((int64_t)(int)value != value)) {
319
            const char* reason = NULL;
320
            if (value > std::numeric_limits<int>::max()) {
321
                reason = "overflows";
322
                value = std::numeric_limits<int>::max();
323
            } else {
324
                reason = "underflows";
325
                value = std::numeric_limits<int>::min();
326
            }
327
            // Truncate to be max or min of int. We're using 44 bits to store the
328
            // sum thus following aggregations are not likely to be over/underflow.
329
            if (!name().empty()) {
330
                LOG(WARNING) << "Input=" << value << " to `" << name()
331
                           << "\' " << reason;
332
            } else if (!_debug_name.empty()) {
333
                LOG(WARNING) << "Input=" << value << " to `" << _debug_name
334
                           << "\' " << reason;
335
            } else {
336
                LOG(WARNING) << "Input=" << value << " to IntRecorder("
337
                           << (void*)this << ") " << reason;
338
            }
339
        }
340
341
        _summer << value;
342
        return *this;
343
    }
344
345
    int64_t average() const {
346
        return get_value().get_average_int();
347
    }
348
349
    double average(double) const {
350
        return get_value().get_average_double();
351
    }
352
353
    value_type get_value() const {
354
        auto summary = _summer.value();
355
        return value_type{summary.sum, static_cast<ssize_t>(summary.num)};
356
    }
357
358
    value_type reset() {
359
        LOG_EVERY_SECOND(ERROR) << "IntRecorder with babylon counter should never call reset()";
360
        return get_value();
361
    }
362
363
    Op op() const { return Op(); }
364
    InvOp inv_op() const { return InvOp(); }
365
366
    void describe(::std::ostream& os, bool) const override {
367
        os << get_value();
368
    }
369
370
    bool valid() const { return true; }
371
372
    sampler_type* get_sampler() {
373
        if (NULL == _sampler) {
374
            _sampler = new sampler_type(this);
375
            _sampler->schedule();
376
        }
377
        return _sampler;
378
    }
379
380
    // This name is useful for printing overflow log in operator<< since
381
    // IntRecorder is often used as the source of data and not exposed.
382
    void set_debug_name(const butil::StringPiece& name) {
383
        _debug_name.assign(name.data(), name.size());
384
    }
385
private:
386
    babylon::ConcurrentSummer _summer;
387
    sampler_type* _sampler{NULL};
388
    std::string _debug_name;
389
};
390
#endif // WITH_BABYLON_COUNTER
391
392
}  // namespace bvar
393
394
#endif  //BVAR_RECORDER_H