-
Notifications
You must be signed in to change notification settings - Fork 8.4k
Expand file tree
/
Copy pathConcurrencyControl.cpp
More file actions
634 lines (556 loc) · 21.2 KB
/
ConcurrencyControl.cpp
File metadata and controls
634 lines (556 loc) · 21.2 KB
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
#include <Common/ISlotControl.h>
#include <Common/ConcurrencyControl.h>
#include <Common/Exception.h>
#include <Common/ProfileEvents.h>
namespace ProfileEvents
{
extern const Event ConcurrencyControlSlotsGranted;
extern const Event ConcurrencyControlSlotsDelayed;
extern const Event ConcurrencyControlSlotsAcquired;
extern const Event ConcurrencyControlSlotsAcquiredNonCompeting;
extern const Event ConcurrencyControlQueriesDelayed;
}
namespace CurrentMetrics
{
extern const Metric ConcurrencyControlAcquired;
extern const Metric ConcurrencyControlAcquiredNonCompeting;
extern const Metric ConcurrencyControlSoftLimit;
}
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
ConcurrencyControlState::ConcurrencyControlState()
: max_concurrency_metric(CurrentMetrics::ConcurrencyControlSoftLimit, 0)
{
}
SlotCount ConcurrencyControlState::available(std::unique_lock<std::mutex> &) const
{
if (cur_concurrency < max_concurrency)
return max_concurrency - cur_concurrency;
return 0;
}
ConcurrencyControlRoundRobinScheduler::Slot::Slot(SlotAllocationPtr && allocation_, size_t slot_id_)
: IAcquiredSlot(slot_id_)
, allocation(std::move(allocation_))
, acquired_slot_increment(CurrentMetrics::ConcurrencyControlAcquired)
{
}
ConcurrencyControlRoundRobinScheduler::Slot::~Slot()
{
static_cast<ConcurrencyControlRoundRobinScheduler::Allocation&>(*allocation).release();
}
ConcurrencyControlRoundRobinScheduler::Allocation::Allocation(ConcurrencyControlRoundRobinScheduler & parent_, SlotCount limit_, SlotCount granted_, Waiters::iterator waiter_)
: parent(parent_)
, limit(limit_)
, allocated(granted_)
, granted(granted_)
, waiter(waiter_)
{
if (allocated < limit)
*waiter = this;
}
ConcurrencyControlRoundRobinScheduler::Allocation::~Allocation()
{
// We have to lock parent's mutex to avoid race with grant()
// NOTE: shortcut can be added, but it requires Allocation::mutex lock even to check if shortcut is possible
parent.free(this);
}
[[nodiscard]] AcquiredSlotPtr ConcurrencyControlRoundRobinScheduler::Allocation::tryAcquire()
{
SlotCount value = granted.load();
while (value)
{
if (granted.compare_exchange_strong(value, value - 1))
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsAcquired, 1);
std::unique_lock lock{mutex};
return AcquiredSlotPtr(new Slot(shared_from_this(), last_slot_id++)); // can't use std::make_shared due to private ctor
}
}
return {}; // avoid unnecessary locking
}
[[nodiscard]] AcquiredSlotPtr ConcurrencyControlRoundRobinScheduler::Allocation::acquire()
{
auto result = tryAcquire();
chassert(result);
return result;
}
// Grant single slot to allocation returns true iff more slot(s) are required
bool ConcurrencyControlRoundRobinScheduler::Allocation::grant()
{
std::unique_lock lock{mutex};
granted++;
allocated++;
return allocated < limit;
}
// Release one slot and grant it to other allocation if required
void ConcurrencyControlRoundRobinScheduler::Allocation::release()
{
parent.release(1);
std::unique_lock lock{mutex};
released++;
if (released > allocated)
abort();
}
ConcurrencyControlRoundRobinScheduler::ConcurrencyControlRoundRobinScheduler(ConcurrencyControl & parent_, ConcurrencyControlState & state_)
: parent(parent_)
, state(state_)
, cur_waiter(waiters.end())
{
}
ConcurrencyControlRoundRobinScheduler::~ConcurrencyControlRoundRobinScheduler()
{
if (!waiters.empty())
abort();
}
SlotAllocationPtr ConcurrencyControlRoundRobinScheduler::allocate(std::unique_lock<std::mutex> & lock, SlotCount min, SlotCount max)
{
// Try allocate slots up to requested `max` (as availability allows)
SlotCount granted = std::max(min, std::min(max, state.available(lock)));
state.cur_concurrency += granted;
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsGranted, min);
// Create allocation and start waiting if more slots are required
if (granted < max)
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsDelayed, max - granted);
ProfileEvents::increment(ProfileEvents::ConcurrencyControlQueriesDelayed);
return SlotAllocationPtr(new Allocation(*this, max, granted,
waiters.insert(cur_waiter, nullptr /* pointer is set by Allocation ctor */)));
}
else
{
return SlotAllocationPtr(new Allocation(*this, max, granted));
}
}
void ConcurrencyControlRoundRobinScheduler::free(Allocation * allocation)
{
// Allocation is allowed to be canceled even if there are:
// - `amount`: granted slots (acquired slots are not possible, because Slot holds AllocationPtr)
// - `waiter`: active waiting for more slots to be allocated
// Thus Allocation destruction may require the following lock, to avoid race conditions
std::unique_lock lock{state.mutex};
auto [amount, waiter] = allocation->cancel();
state.cur_concurrency -= amount;
if (waiter)
{
if (cur_waiter == *waiter)
cur_waiter = waiters.erase(*waiter);
else
waiters.erase(*waiter);
}
parent.schedule(lock);
}
void ConcurrencyControlRoundRobinScheduler::release(SlotCount amount)
{
std::unique_lock lock{state.mutex};
state.cur_concurrency -= amount;
parent.schedule(lock);
}
// Round-robin scheduling of available slots among waiting allocations
void ConcurrencyControlRoundRobinScheduler::schedule(std::unique_lock<std::mutex> &)
{
while (!waiters.empty() && state.cur_concurrency < state.max_concurrency)
{
state.cur_concurrency++;
if (cur_waiter == waiters.end())
cur_waiter = waiters.begin();
Allocation * allocation = *cur_waiter;
if (allocation->grant())
++cur_waiter;
else
cur_waiter = waiters.erase(cur_waiter); // last required slot has just been granted -- stop waiting
}
}
ConcurrencyControlFairRoundRobinScheduler::Slot::Slot(SlotAllocationPtr && allocation_, bool competing_, size_t slot_id_)
: IAcquiredSlot(slot_id_)
, allocation(std::move(allocation_))
, competing(competing_)
, acquired_slot_increment(competing ? CurrentMetrics::ConcurrencyControlAcquired : CurrentMetrics::ConcurrencyControlAcquiredNonCompeting)
{
}
ConcurrencyControlFairRoundRobinScheduler::Slot::~Slot()
{
if (competing)
static_cast<ConcurrencyControlFairRoundRobinScheduler::Allocation&>(*allocation).release();
}
ConcurrencyControlFairRoundRobinScheduler::Allocation::Allocation(ConcurrencyControlFairRoundRobinScheduler & parent_, SlotCount min_, SlotCount max, SlotCount granted_, Waiters::iterator waiter_)
: parent(parent_)
, min(min_)
, limit(max - min)
, allocated(granted_)
, noncompeting(min)
, granted(granted_)
, waiter(waiter_)
{
if (allocated < limit)
*waiter = this;
}
ConcurrencyControlFairRoundRobinScheduler::Allocation::~Allocation()
{
// We have to lock parent's mutex to avoid race with grant()
// NOTE: shortcut can be added, but it requires Allocation::mutex lock even to check if shortcut is possible
parent.free(this);
}
[[nodiscard]] AcquiredSlotPtr ConcurrencyControlFairRoundRobinScheduler::Allocation::tryAcquire()
{
// First try acquire non-competing slot (if any)
SlotCount value = noncompeting.load();
while (value)
{
if (noncompeting.compare_exchange_strong(value, value - 1))
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsAcquiredNonCompeting, 1);
std::unique_lock lock{mutex};
return AcquiredSlotPtr(new Slot(shared_from_this(), false, last_slot_id++)); // can't use std::make_shared due to private ctor
}
}
// If all non-competing slots are already acquired - try acquire granted (competing) slot
value = granted.load();
while (value)
{
if (granted.compare_exchange_strong(value, value - 1))
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsAcquired, 1);
std::unique_lock lock{mutex};
return AcquiredSlotPtr(new Slot(shared_from_this(), true, last_slot_id++)); // can't use std::make_shared due to private ctor
}
}
return {}; // avoid unnecessary locking
}
[[nodiscard]] AcquiredSlotPtr ConcurrencyControlFairRoundRobinScheduler::Allocation::acquire()
{
auto result = tryAcquire();
chassert(result);
return result;
}
// Grant single slot to allocation returns true iff more slot(s) are required
bool ConcurrencyControlFairRoundRobinScheduler::Allocation::grant()
{
std::unique_lock lock{mutex};
granted++;
allocated++;
return allocated < limit;
}
// Release one slot and grant it to other allocation if required
void ConcurrencyControlFairRoundRobinScheduler::Allocation::release()
{
parent.release(1);
std::unique_lock lock{mutex};
released++;
if (released > allocated)
abort();
}
ConcurrencyControlFairRoundRobinScheduler::ConcurrencyControlFairRoundRobinScheduler(ConcurrencyControl & parent_, ConcurrencyControlState & state_)
: parent(parent_)
, state(state_)
, cur_waiter(waiters.end())
{
}
ConcurrencyControlFairRoundRobinScheduler::~ConcurrencyControlFairRoundRobinScheduler()
{
if (!waiters.empty())
abort();
}
SlotAllocationPtr ConcurrencyControlFairRoundRobinScheduler::allocate(std::unique_lock<std::mutex> & lock, SlotCount min, SlotCount max)
{
// Try allocate slots up to requested `max - min` (as availability allows).
// Do not count `min` slots towards the limit. They are NOT considered as taking part in competition.
SlotCount limit = max - min;
SlotCount granted = std::min(limit, state.available(lock));
state.cur_concurrency += granted;
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsGranted, min);
// Create allocation and start waiting if more slots are required
if (granted < limit)
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsDelayed, limit - granted);
ProfileEvents::increment(ProfileEvents::ConcurrencyControlQueriesDelayed);
return SlotAllocationPtr(new Allocation(*this, min, max, granted,
waiters.insert(cur_waiter, nullptr /* pointer is set by Allocation ctor */)));
}
else
{
return SlotAllocationPtr(new Allocation(*this, min, max, granted));
}
}
void ConcurrencyControlFairRoundRobinScheduler::free(Allocation * allocation)
{
// Allocation is allowed to be canceled even if there are:
// - `amount`: granted slots (acquired slots are not possible, because Slot holds AllocationPtr)
// - `waiter`: active waiting for more slots to be allocated
// Thus Allocation destruction may require the following lock, to avoid race conditions
std::unique_lock lock{state.mutex};
auto [amount, waiter] = allocation->cancel();
state.cur_concurrency -= amount;
if (waiter)
{
if (cur_waiter == *waiter)
cur_waiter = waiters.erase(*waiter);
else
waiters.erase(*waiter);
}
parent.schedule(lock);
}
void ConcurrencyControlFairRoundRobinScheduler::release(SlotCount amount)
{
std::unique_lock lock{state.mutex};
state.cur_concurrency -= amount;
parent.schedule(lock);
}
// Round-robin scheduling of available slots among waiting allocations
void ConcurrencyControlFairRoundRobinScheduler::schedule(std::unique_lock<std::mutex> &)
{
while (!waiters.empty() && state.cur_concurrency < state.max_concurrency)
{
state.cur_concurrency++;
if (cur_waiter == waiters.end())
cur_waiter = waiters.begin();
Allocation * allocation = *cur_waiter;
if (allocation->grant())
++cur_waiter;
else
cur_waiter = waiters.erase(cur_waiter); // last required slot has just been granted -- stop waiting
}
}
bool ConcurrencyControlMaxMinFairScheduler::AllocationCompare::operator()(const Allocation & lhs, const Allocation & rhs) const
{
// Primary: sort by allocated count (minimum first for max-min fairness)
// Secondary: sort by sequence_number for FIFO ordering when allocated counts are equal
if (lhs.allocated != rhs.allocated)
return lhs.allocated < rhs.allocated;
return lhs.sequence_number < rhs.sequence_number;
}
ConcurrencyControlMaxMinFairScheduler::Slot::Slot(SlotAllocationPtr && allocation_, bool competing_, size_t slot_id_)
: IAcquiredSlot(slot_id_)
, allocation(std::move(allocation_))
, competing(competing_)
, acquired_slot_increment(competing ? CurrentMetrics::ConcurrencyControlAcquired : CurrentMetrics::ConcurrencyControlAcquiredNonCompeting)
{
}
ConcurrencyControlMaxMinFairScheduler::Slot::~Slot()
{
if (competing)
static_cast<ConcurrencyControlMaxMinFairScheduler::Allocation&>(*allocation).release();
}
ConcurrencyControlMaxMinFairScheduler::Allocation::Allocation(ConcurrencyControlMaxMinFairScheduler & parent_, SlotCount min_, SlotCount max, SlotCount granted_, UInt64 sequence_number_)
: parent(parent_)
, min(min_)
, limit(max - min)
, allocated(granted_)
, noncompeting(min)
, granted(granted_)
, sequence_number(sequence_number_)
{
}
ConcurrencyControlMaxMinFairScheduler::Allocation::~Allocation()
{
// We have to lock parent's mutex to avoid race with grant()
// NOTE: shortcut can be added, but it requires Allocation::mutex lock even to check if shortcut is possible
parent.free(this);
}
[[nodiscard]] AcquiredSlotPtr ConcurrencyControlMaxMinFairScheduler::Allocation::tryAcquire()
{
// First try acquire non-competing slot (if any)
SlotCount value = noncompeting.load();
while (value)
{
if (noncompeting.compare_exchange_strong(value, value - 1))
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsAcquiredNonCompeting, 1);
std::unique_lock lock{mutex};
return AcquiredSlotPtr(new Slot(shared_from_this(), false, last_slot_id++)); // can't use std::make_shared due to private ctor
}
}
// If all non-competing slots are already acquired - try acquire granted (competing) slot
value = granted.load();
while (value)
{
if (granted.compare_exchange_strong(value, value - 1))
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsAcquired, 1);
std::unique_lock lock{mutex};
return AcquiredSlotPtr(new Slot(shared_from_this(), true, last_slot_id++)); // can't use std::make_shared due to private ctor
}
}
return {}; // avoid unnecessary locking
}
[[nodiscard]] AcquiredSlotPtr ConcurrencyControlMaxMinFairScheduler::Allocation::acquire()
{
auto result = tryAcquire();
chassert(result);
return result;
}
// Grant single slot to allocation returns true iff more slot(s) are required
bool ConcurrencyControlMaxMinFairScheduler::Allocation::grant()
{
std::unique_lock lock{mutex};
granted++;
allocated++;
return allocated < limit;
}
// Release one slot and grant it to other allocation if required
void ConcurrencyControlMaxMinFairScheduler::Allocation::release()
{
parent.release(1);
std::unique_lock lock{mutex};
released++;
if (released > allocated)
abort();
}
ConcurrencyControlMaxMinFairScheduler::ConcurrencyControlMaxMinFairScheduler(ConcurrencyControl & parent_, ConcurrencyControlState & state_)
: parent(parent_)
, state(state_)
{
}
ConcurrencyControlMaxMinFairScheduler::~ConcurrencyControlMaxMinFairScheduler()
{
if (!waiters.empty())
abort();
}
SlotAllocationPtr ConcurrencyControlMaxMinFairScheduler::allocate(std::unique_lock<std::mutex> & lock, SlotCount min, SlotCount max)
{
// Try allocate slots up to requested `max - min` (as availability allows).
// Do not count `min` slots towards the limit. They are NOT considered as taking part in competition.
SlotCount limit = max - min;
SlotCount granted = std::min(limit, state.available(lock));
state.cur_concurrency += granted;
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsGranted, min);
// Create allocation with monotonically increasing sequence number for FIFO ordering
auto allocation = SlotAllocationPtr(new Allocation(*this, min, max, granted, next_sequence_number++));
// Start waiting if more slots are required
if (granted < limit)
{
ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsDelayed, limit - granted);
ProfileEvents::increment(ProfileEvents::ConcurrencyControlQueriesDelayed);
// Insert into waiters set (sorted by allocated count, then by sequence number)
// The hook's is_linked() will return true after insertion
waiters.insert(*static_cast<Allocation*>(allocation.get()));
}
return allocation;
}
void ConcurrencyControlMaxMinFairScheduler::free(Allocation * allocation)
{
// Allocation is allowed to be canceled even if there are:
// - `amount`: granted slots (acquired slots are not possible, because Slot holds AllocationPtr)
// - `waiter`: active waiting for more slots to be allocated
// Thus Allocation destruction may require the following lock, to avoid race conditions
std::unique_lock lock{state.mutex};
auto [amount, is_waiting] = allocation->cancel();
state.cur_concurrency -= amount;
if (is_waiting)
waiters.erase(waiters.iterator_to(*allocation));
parent.schedule(lock);
}
void ConcurrencyControlMaxMinFairScheduler::release(SlotCount amount)
{
std::unique_lock lock{state.mutex};
state.cur_concurrency -= amount;
parent.schedule(lock);
}
// Max-min fair scheduling of available slots among waiting allocations
// Always grant to the allocation with the minimum number of currently allocated slots
void ConcurrencyControlMaxMinFairScheduler::schedule(std::unique_lock<std::mutex> &)
{
while (!waiters.empty() && state.cur_concurrency < state.max_concurrency)
{
state.cur_concurrency++;
// Get the allocation with minimum allocated count (first element in the sorted set)
auto it = waiters.begin();
Allocation & allocation = *it;
// Remove from set before granting (as allocated count will change)
waiters.erase(it);
if (allocation.grant())
{
// Still needs more slots - reinsert with updated allocated count
waiters.insert(allocation);
}
// When not reinserted, the hook remains unlinked (is_linked() returns false)
}
}
ConcurrencyControl::ConcurrencyControl()
: round_robin(*this, state)
, fair_round_robin(*this, state)
, max_min_fair(*this, state)
{
}
ConcurrencyControl & ConcurrencyControl::instance()
{
static ConcurrencyControl result;
return result;
}
[[nodiscard]] SlotAllocationPtr ConcurrencyControl::allocate(SlotCount min, SlotCount max)
{
if (min > max)
throw Exception(ErrorCodes::LOGICAL_ERROR, "ConcurrencyControl: invalid allocation requirements");
std::unique_lock lock{state.mutex};
switch (scheduler)
{
case Scheduler::RoundRobin:
return round_robin.allocate(lock, min, max);
case Scheduler::FairRoundRobin:
return fair_round_robin.allocate(lock, min, max);
case Scheduler::MaxMinFair:
return max_min_fair.allocate(lock, min, max);
}
}
void ConcurrencyControl::setMaxConcurrency(SlotCount value)
{
std::unique_lock lock{state.mutex};
state.max_concurrency = std::max<SlotCount>(1, value); // never allow max_concurrency to be zero
state.max_concurrency_metric.changeTo(state.max_concurrency == UnlimitedSlots ? 0 : state.max_concurrency);
schedule(lock);
}
bool ConcurrencyControl::setScheduler(const String & value)
{
std::unique_lock lock{state.mutex};
if (value == "fair_round_robin")
{
scheduler = Scheduler::FairRoundRobin;
return true;
}
if (value == "round_robin")
{
scheduler = Scheduler::RoundRobin;
return true;
}
if (value == "max_min_fair")
{
scheduler = Scheduler::MaxMinFair;
return true;
}
return false; // invalid value - stick to the current scheduler
}
String ConcurrencyControl::getScheduler() const
{
std::unique_lock lock{state.mutex};
switch (scheduler)
{
case Scheduler::RoundRobin: return "round_robin";
case Scheduler::FairRoundRobin: return "fair_round_robin";
case Scheduler::MaxMinFair: return "max_min_fair";
}
}
void ConcurrencyControl::schedule(std::unique_lock<std::mutex> & lock)
{
switch (scheduler)
{
case Scheduler::RoundRobin:
fair_round_robin.schedule(lock); // first schedule from old scheduler (works only during transition period)
max_min_fair.schedule(lock);
round_robin.schedule(lock);
return;
case Scheduler::FairRoundRobin:
round_robin.schedule(lock); // first schedule from old scheduler (works only during transition period)
max_min_fair.schedule(lock);
fair_round_robin.schedule(lock);
return;
case Scheduler::MaxMinFair:
round_robin.schedule(lock); // first schedule from old scheduler (works only during transition period)
fair_round_robin.schedule(lock);
max_min_fair.schedule(lock);
return;
}
}
}