common/cpp/token_bucket_rate_limiter.cpp
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 | | #include "token_bucket_rate_limiter.h" |
19 | | |
20 | | #include <bthread/bthread.h> |
21 | | #include <glog/logging.h> // IWYU pragma: export |
22 | | |
23 | | #include <atomic> |
24 | | #include <chrono> |
25 | | #include <mutex> |
26 | | #include <thread> |
27 | | |
28 | | #if defined(__APPLE__) |
29 | | #include <ctime> |
30 | | #endif |
31 | | |
32 | | namespace doris { |
33 | | // Just 10^6. |
34 | | static constexpr auto NS = 1000000000UL; |
35 | | |
36 | | bvar::Adder<int64_t> s3_get_rate_limit_sleep_ns("s3_get_rate_limit_sleep_ns"); |
37 | | bvar::Adder<int64_t> s3_get_rate_limit_sleep_count("s3_get_rate_limit_sleep_count"); |
38 | | bvar::Adder<int64_t> s3_get_rate_limit_rejected_count("s3_get_rate_limit_rejected_count"); |
39 | | bvar::Adder<int64_t> s3_put_rate_limit_sleep_ns("s3_put_rate_limit_sleep_ns"); |
40 | | bvar::Adder<int64_t> s3_put_rate_limit_sleep_count("s3_put_rate_limit_sleep_count"); |
41 | | bvar::Adder<int64_t> s3_put_rate_limit_rejected_count("s3_put_rate_limit_rejected_count"); |
42 | | |
43 | | static std::atomic<int64_t> s3_get_rate_limit_sleep_log_count {0}; |
44 | | static std::atomic<int64_t> s3_get_rate_limit_rejected_log_count {0}; |
45 | | static std::atomic<int64_t> s3_put_rate_limit_sleep_log_count {0}; |
46 | | static std::atomic<int64_t> s3_put_rate_limit_rejected_log_count {0}; |
47 | | |
48 | | class TokenBucketRateLimiter::SimpleSpinLock { |
49 | | public: |
50 | 1.65k | SimpleSpinLock() = default; |
51 | | ~SimpleSpinLock() = default; |
52 | | |
53 | 593 | void lock() { |
54 | 593 | int spin_count = 0; |
55 | 593 | static constexpr int MAX_SPIN_COUNT = 50; |
56 | 593 | while (_flag.test_and_set(std::memory_order_acq_rel)) { |
57 | 0 | spin_count++; |
58 | 0 | if (spin_count >= MAX_SPIN_COUNT) { |
59 | 0 | LOG(WARNING) << "Warning: Excessive spinning detected while acquiring lock. Spin " |
60 | 0 | "count: " |
61 | 0 | << spin_count; |
62 | 0 | spin_count = 0; |
63 | 0 | } |
64 | | // Spin until we acquire the lock |
65 | 0 | } |
66 | 593 | } |
67 | | |
68 | 593 | void unlock() { _flag.clear(std::memory_order_release); } |
69 | | |
70 | | private: |
71 | | std::atomic_flag _flag = ATOMIC_FLAG_INIT; |
72 | | }; |
73 | | |
74 | | TokenBucketRateLimiter::TokenBucketRateLimiter(size_t max_speed, size_t max_burst, size_t limit) |
75 | 1.65k | : _max_speed(max_speed), |
76 | 1.65k | _max_burst(max_burst), |
77 | 1.65k | _limit(limit), |
78 | 1.65k | _mutex(std::make_unique<TokenBucketRateLimiter::SimpleSpinLock>()), |
79 | 1.65k | _remain_tokens(max_burst) {} |
80 | | |
81 | 1.63k | TokenBucketRateLimiter::~TokenBucketRateLimiter() = default; |
82 | | |
83 | 1.56k | TokenBucketRateLimiterHolder::~TokenBucketRateLimiterHolder() = default; |
84 | | |
85 | 571 | std::pair<size_t, double> TokenBucketRateLimiter::_update_remain_token(long now, size_t amount) { |
86 | | // Values obtained under lock to be checked after release |
87 | 571 | size_t count_value; |
88 | 571 | double tokens_value; |
89 | 571 | { |
90 | 571 | std::lock_guard<SimpleSpinLock> lock(*_mutex); |
91 | 571 | now = (now < _prev_ns_count) ? _prev_ns_count : now; |
92 | 571 | if (_max_speed) { |
93 | 557 | double delta_seconds = |
94 | 557 | _prev_ns_count ? static_cast<double>(now - _prev_ns_count) / NS : 0; |
95 | 557 | _remain_tokens = std::min<double>(_remain_tokens + _max_speed * delta_seconds - amount, |
96 | 557 | _max_burst); |
97 | 557 | } |
98 | 571 | _count += amount; |
99 | 571 | count_value = _count; |
100 | 571 | if (_limit && count_value > _limit) { |
101 | | // Keep rejection side-effect free. Roll back before releasing the lock so |
102 | | // concurrent callers cannot observe debt from a request that will not run. |
103 | 14 | _count -= amount; |
104 | 14 | if (_max_speed) { |
105 | 9 | _remain_tokens = std::min<double>(_remain_tokens + amount, _max_burst); |
106 | 9 | } |
107 | 14 | } |
108 | 571 | tokens_value = _remain_tokens; |
109 | 571 | _prev_ns_count = now; |
110 | 571 | } |
111 | 571 | return {count_value, tokens_value}; |
112 | 571 | } |
113 | | |
114 | 571 | int64_t TokenBucketRateLimiter::add(size_t amount) { |
115 | | // Values obtained under lock to be checked after release |
116 | 571 | auto duration = std::chrono::steady_clock::now().time_since_epoch(); |
117 | 571 | auto time_nano_count = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count(); |
118 | 571 | auto [count_value, tokens_value] = _update_remain_token(time_nano_count, amount); |
119 | | |
120 | 571 | if (_limit && count_value > _limit) { |
121 | | // CK would throw exception |
122 | 14 | return -1; |
123 | 14 | } |
124 | | |
125 | | // Wait unless there is positive amount of remain_tokens - throttling |
126 | 557 | int64_t sleep_time_ns = 0; |
127 | 557 | if (_max_speed && tokens_value < 0) { |
128 | 281 | sleep_time_ns = static_cast<int64_t>(-tokens_value / _max_speed * NS); |
129 | 281 | bthread_usleep(sleep_time_ns / 1000); |
130 | 281 | } |
131 | | |
132 | 557 | return sleep_time_ns; |
133 | 571 | } |
134 | | |
135 | 4 | void TokenBucketRateLimiter::refund_tokens(size_t amount) { |
136 | 4 | std::lock_guard<SimpleSpinLock> lock(*_mutex); |
137 | 4 | if (_max_speed) { |
138 | 4 | _remain_tokens = std::min<double>(_remain_tokens + amount, _max_burst); |
139 | 4 | } |
140 | 4 | } |
141 | | |
142 | 18 | void TokenBucketRateLimiter::refund_count(size_t amount) { |
143 | 18 | std::lock_guard<SimpleSpinLock> lock(*_mutex); |
144 | 18 | CHECK_GE(_count, amount); |
145 | 18 | _count -= amount; |
146 | 18 | } |
147 | | |
148 | | TokenBucketRateLimiterHolder::TokenBucketRateLimiterHolder(size_t max_speed, size_t max_burst, |
149 | | size_t limit, |
150 | | std::function<void(int64_t)> metric_func) |
151 | 1.59k | : rate_limiter(std::make_shared<TokenBucketRateLimiter>(max_speed, max_burst, limit)), |
152 | 1.59k | _enabled(max_speed > 0 || limit > 0), |
153 | 1.59k | metric_func(std::move(metric_func)) {} |
154 | | |
155 | 533 | int64_t TokenBucketRateLimiterHolder::add(size_t amount) { |
156 | 533 | return add_with_config(amount).sleep_duration; |
157 | 533 | } |
158 | | |
159 | 546 | TokenBucketRateLimiterResult TokenBucketRateLimiterHolder::add_with_config(size_t amount) { |
160 | | // Snapshot the current limiter and call add() outside the read lock: add() may |
161 | | // sleep for a long time when throttled, and holding the read lock across the |
162 | | // sleep would block reset() (dynamic config update) for the whole duration. |
163 | 546 | std::shared_ptr<TokenBucketRateLimiter> limiter; |
164 | 546 | { |
165 | 546 | std::shared_lock read {rate_limiter_rw_lock}; |
166 | 546 | limiter = rate_limiter; |
167 | 546 | } |
168 | 546 | TokenBucketRateLimiterResult result = {.sleep_duration = limiter->add(amount), |
169 | 546 | .max_speed = limiter->get_max_speed(), |
170 | 546 | .max_burst = limiter->get_max_burst(), |
171 | 546 | .limit = limiter->get_limit()}; |
172 | 546 | metric_func(result.sleep_duration); |
173 | 546 | return result; |
174 | 546 | } |
175 | | |
176 | 17 | std::shared_ptr<TokenBucketRateLimiter> TokenBucketRateLimiterHolder::charge(size_t amount) { |
177 | 17 | std::shared_ptr<TokenBucketRateLimiter> limiter; |
178 | 17 | { |
179 | 17 | std::shared_lock read {rate_limiter_rw_lock}; |
180 | 17 | limiter = rate_limiter; |
181 | 17 | } |
182 | 17 | int64_t sleep_duration = limiter->add(amount); |
183 | 17 | metric_func(sleep_duration); |
184 | 17 | return sleep_duration < 0 ? nullptr : limiter; |
185 | 17 | } |
186 | | |
187 | 60 | int TokenBucketRateLimiterHolder::reset(size_t max_speed, size_t max_burst, size_t limit) { |
188 | 60 | auto new_rate_limiter = std::make_shared<TokenBucketRateLimiter>(max_speed, max_burst, limit); |
189 | 60 | { |
190 | 60 | std::unique_lock write {rate_limiter_rw_lock}; |
191 | 60 | rate_limiter = std::move(new_rate_limiter); |
192 | 60 | _enabled.store(max_speed > 0 || limit > 0, std::memory_order_release); |
193 | 60 | } |
194 | 60 | return 0; |
195 | 60 | } |
196 | | |
197 | 205 | size_t TokenBucketRateLimiterHolder::get_max_speed() const { |
198 | 205 | std::shared_lock read {rate_limiter_rw_lock}; |
199 | 205 | return rate_limiter->get_max_speed(); |
200 | 205 | } |
201 | | |
202 | 112 | size_t TokenBucketRateLimiterHolder::get_max_burst() const { |
203 | 112 | std::shared_lock read {rate_limiter_rw_lock}; |
204 | 112 | return rate_limiter->get_max_burst(); |
205 | 112 | } |
206 | | |
207 | 111 | size_t TokenBucketRateLimiterHolder::get_limit() const { |
208 | 111 | std::shared_lock read {rate_limiter_rw_lock}; |
209 | 111 | return rate_limiter->get_limit(); |
210 | 111 | } |
211 | | |
212 | 39 | std::string to_string(S3RateLimitType type) { |
213 | 39 | switch (type) { |
214 | 25 | case S3RateLimitType::GET: |
215 | 25 | return "get"; |
216 | 14 | case S3RateLimitType::PUT: |
217 | 14 | return "put"; |
218 | 0 | default: |
219 | 0 | return std::to_string(static_cast<size_t>(type)); |
220 | 39 | } |
221 | 39 | } |
222 | | |
223 | 0 | S3RateLimitType string_to_s3_rate_limit_type(std::string_view value) { |
224 | 0 | if (value == "get") { |
225 | 0 | return S3RateLimitType::GET; |
226 | 0 | } else if (value == "put") { |
227 | 0 | return S3RateLimitType::PUT; |
228 | 0 | } |
229 | 0 | return S3RateLimitType::UNKNOWN; |
230 | 0 | } |
231 | | |
232 | 2 | std::function<void(int64_t)> s3_rate_limiter_metric_func(S3RateLimitType type) { |
233 | 2 | switch (type) { |
234 | 1 | case S3RateLimitType::GET: |
235 | 1 | return metric_func_factory(s3_get_rate_limit_sleep_ns, s3_get_rate_limit_sleep_count, |
236 | 1 | &s3_get_rate_limit_rejected_count); |
237 | 1 | case S3RateLimitType::PUT: |
238 | 1 | return metric_func_factory(s3_put_rate_limit_sleep_ns, s3_put_rate_limit_sleep_count, |
239 | 1 | &s3_put_rate_limit_rejected_count); |
240 | 0 | default: |
241 | 0 | return [](int64_t) {}; |
242 | 2 | } |
243 | 2 | } |
244 | | |
245 | | int64_t apply_s3_rate_limit(S3RateLimitType type, S3RateLimiterHolder* rate_limiter, |
246 | 12 | int64_t log_interval) { |
247 | 12 | auto result = rate_limiter->add_with_config(1); |
248 | 12 | auto sleep_duration = result.sleep_duration; |
249 | 12 | if (log_interval <= 0 || sleep_duration == 0) { |
250 | 7 | return sleep_duration; |
251 | 7 | } |
252 | | |
253 | 5 | auto is_get = type == S3RateLimitType::GET; |
254 | 5 | auto* sleep_log_count = |
255 | 5 | is_get ? &s3_get_rate_limit_sleep_log_count : &s3_put_rate_limit_sleep_log_count; |
256 | 5 | auto* rejected_log_count = |
257 | 5 | is_get ? &s3_get_rate_limit_rejected_log_count : &s3_put_rate_limit_rejected_log_count; |
258 | | |
259 | 5 | if (sleep_duration > 0) { |
260 | 0 | int64_t count = sleep_log_count->fetch_add(1, std::memory_order_relaxed) + 1; |
261 | 0 | if (count == 1 || count % log_interval == 0) { |
262 | 0 | LOG(INFO) << "S3 " << to_string(type) << " request is throttled by local rate limiter" |
263 | 0 | << ", sleep_ms=" << sleep_duration / 1000000 << ", sleep_count=" << count |
264 | 0 | << ", token_per_second=" << result.max_speed |
265 | 0 | << ", bucket_tokens=" << result.max_burst << ", token_limit=" << result.limit; |
266 | 0 | } |
267 | 5 | } else { |
268 | 5 | int64_t count = rejected_log_count->fetch_add(1, std::memory_order_relaxed) + 1; |
269 | 5 | if (count == 1 || count % log_interval == 0) { |
270 | | LOG(WARNING) << "S3 " << to_string(type) << " request is rejected by local rate limiter" |
271 | 2 | << ", rejected_count=" << count |
272 | 2 | << ", token_per_second=" << result.max_speed |
273 | 2 | << ", bucket_tokens=" << result.max_burst |
274 | 2 | << ", token_limit=" << result.limit; |
275 | 2 | } |
276 | 5 | } |
277 | 5 | return sleep_duration; |
278 | 12 | } |
279 | | } // namespace doris |