]> granicus.if.org Git - icinga2/blob - lib/base/ringbuffer.cpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / ringbuffer.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #include "base/ringbuffer.hpp"
4 #include "base/objectlock.hpp"
5 #include "base/utility.hpp"
6 #include <algorithm>
7
8 using namespace icinga;
9
10 RingBuffer::RingBuffer(RingBuffer::SizeType slots)
11         : m_Slots(slots, 0), m_TimeValue(0), m_InsertedValues(0)
12 { }
13
14 RingBuffer::SizeType RingBuffer::GetLength() const
15 {
16         boost::mutex::scoped_lock lock(m_Mutex);
17         return m_Slots.size();
18 }
19
20 void RingBuffer::InsertValue(RingBuffer::SizeType tv, int num)
21 {
22         boost::mutex::scoped_lock lock(m_Mutex);
23
24         InsertValueUnlocked(tv, num);
25 }
26
27 void RingBuffer::InsertValueUnlocked(RingBuffer::SizeType tv, int num)
28 {
29         RingBuffer::SizeType offsetTarget = tv % m_Slots.size();
30
31         if (m_TimeValue == 0)
32                 m_InsertedValues = 1;
33
34         if (tv > m_TimeValue) {
35                 RingBuffer::SizeType offset = m_TimeValue % m_Slots.size();
36
37                 /* walk towards the target offset, resetting slots to 0 */
38                 while (offset != offsetTarget) {
39                         offset++;
40
41                         if (offset >= m_Slots.size())
42                                 offset = 0;
43
44                         m_Slots[offset] = 0;
45
46                         if (m_TimeValue != 0 && m_InsertedValues < m_Slots.size())
47                                 m_InsertedValues++;
48                 }
49
50                 m_TimeValue = tv;
51         }
52
53         m_Slots[offsetTarget] += num;
54 }
55
56 int RingBuffer::UpdateAndGetValues(RingBuffer::SizeType tv, RingBuffer::SizeType span)
57 {
58         boost::mutex::scoped_lock lock(m_Mutex);
59
60         return UpdateAndGetValuesUnlocked(tv, span);
61 }
62
63 int RingBuffer::UpdateAndGetValuesUnlocked(RingBuffer::SizeType tv, RingBuffer::SizeType span)
64 {
65         InsertValueUnlocked(tv, 0);
66
67         if (span > m_Slots.size())
68                 span = m_Slots.size();
69
70         int off = m_TimeValue % m_Slots.size();
71         int sum = 0;
72         while (span > 0) {
73                 sum += m_Slots[off];
74
75                 if (off == 0)
76                         off = m_Slots.size();
77
78                 off--;
79                 span--;
80         }
81
82         return sum;
83 }
84
85 double RingBuffer::CalculateRate(RingBuffer::SizeType tv, RingBuffer::SizeType span)
86 {
87         boost::mutex::scoped_lock lock(m_Mutex);
88
89         int sum = UpdateAndGetValuesUnlocked(tv, span);
90         return sum / static_cast<double>(std::min(span, m_InsertedValues));
91 }