-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathdefault.rs
3879 lines (3603 loc) · 162 KB
/
default.rs
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
use self::latency_awareness::LatencyAwareness;
pub use self::latency_awareness::LatencyAwarenessBuilder;
use super::{FallbackPlan, LoadBalancingPolicy, NodeRef, RoutingInfo};
use crate::cluster::ClusterState;
use crate::{
cluster::metadata::Strategy,
cluster::node::Node,
errors::RequestAttemptError,
routing::locator::ReplicaSet,
routing::{Shard, Token},
};
use itertools::{Either, Itertools};
use rand::{prelude::SliceRandom, rng, Rng};
use rand_pcg::Pcg32;
use scylla_cql::frame::response::result::TableSpec;
use scylla_cql::frame::types::SerialConsistency;
use scylla_cql::Consistency;
use std::hash::{Hash, Hasher};
use std::{fmt, sync::Arc, time::Duration};
use tracing::{debug, warn};
use uuid::Uuid;
#[derive(Clone, Copy)]
enum NodeLocationCriteria<'a> {
Any,
Datacenter(&'a str),
DatacenterAndRack(&'a str, &'a str),
}
impl<'a> NodeLocationCriteria<'a> {
fn datacenter(&self) -> Option<&'a str> {
match self {
Self::Any => None,
Self::Datacenter(dc) | Self::DatacenterAndRack(dc, _) => Some(dc),
}
}
}
#[derive(Debug, Clone)]
enum NodeLocationPreference {
Any,
Datacenter(String),
DatacenterAndRack(String, String),
}
impl NodeLocationPreference {
fn datacenter(&self) -> Option<&str> {
match self {
Self::Any => None,
Self::Datacenter(dc) | Self::DatacenterAndRack(dc, _) => Some(dc),
}
}
#[allow(unused)]
fn rack(&self) -> Option<&str> {
match self {
Self::Any | Self::Datacenter(_) => None,
Self::DatacenterAndRack(_, rack) => Some(rack),
}
}
}
/// An ordering requirement for replicas.
#[derive(Clone, Copy)]
enum ReplicaOrder {
/// No requirement. Replicas can be returned in arbitrary order.
Arbitrary,
/// A requirement for the order to be deterministic, not only across statement executions
/// but also across drivers. This is used for LWT optimisation, to avoid Paxos conflicts.
Deterministic,
}
/// Statement kind, used to enable specific load balancing patterns for certain cases.
///
/// Currently, there is a distinguished case of LWT statements, which should always be routed
/// to replicas in a deterministic order to avoid Paxos conflicts. Other statements
/// are routed to random replicas to balance the load.
#[derive(Clone, Copy)]
enum StatementType {
/// The statement is a confirmed LWT. It's to be routed specifically.
Lwt,
/// The statement is not a confirmed LWT. It's to be routed in a default way.
NonLwt,
}
/// A result of `pick_replica`.
enum PickedReplica<'a> {
/// A replica that could be computed cheaply.
Computed((NodeRef<'a>, Shard)),
/// A replica that could not be computed cheaply. `pick` should therefore return None
/// and `fallback` will then return that replica as the first in the iterator.
ToBeComputedInFallback,
}
/// The default load balancing policy.
///
/// It can be configured to be datacenter-aware, rack-aware and token-aware.
/// Datacenter failover (sending query to a node from a remote datacenter)
/// for queries with non local consistency mode is also supported.
///
/// Latency awareness is available, although **not recommended**:
/// the penalisation mechanism it involves may interact badly with other
/// mechanisms, such as LWT optimisation. Also, the very tactics of penalising
/// nodes for recently measures latencies is believed to not be very stable
/// and beneficial. The number of in-flight requests, for instance, seems
/// to be a better metric showing how (over)loaded a target node/shard is.
/// For now, however, we don't have an implementation of the
/// in-flight-requests-aware policy.
#[allow(clippy::type_complexity)]
pub struct DefaultPolicy {
/// Preferences regarding node location. One of: rack and DC, DC, or no preference.
preferences: NodeLocationPreference,
/// Configures whether the policy takes token into consideration when creating plans.
/// If this is set to `true` AND token, keyspace and table are available,
/// then policy prefers replicas and puts them earlier in the query plan.
is_token_aware: bool,
/// Whether to permit remote nodes (those not located in the preferred DC) in plans.
/// If no preferred DC is set, this has no effect.
permit_dc_failover: bool,
/// A predicate that a target (node + shard) must satisfy in order to be picked.
/// This was introduced to make latency awareness cleaner.
/// - if latency awareness is disabled, then `pick_predicate` is just `Self::is_alive()`;
/// - if latency awareness is enabled, then it is `Self::is_alive() && latency_predicate()`,
/// which checks that the target is not penalised due to high latencies.
pick_predicate: Box<dyn Fn(NodeRef<'_>, Option<Shard>) -> bool + Send + Sync>,
/// Additional layer that penalises targets that are too slow compared to others
/// in terms of latency. It works in the following way:
/// - for `pick`, it uses `latency_predicate` to filter out penalised nodes,
/// so that a penalised node will never be `pick`ed;
/// - for `fallback`, it wraps the returned iterator, moving all penalised nodes
/// to the end, in a stable way.
///
/// Penalisation is done based on collected and updated latencies.
latency_awareness: Option<LatencyAwareness>,
/// The policy chooses (in `pick`) and shuffles (in `fallback`) replicas and nodes
/// based on random number generator. For sake of deterministic testing,
/// a fixed seed can be used.
fixed_seed: Option<u64>,
}
impl fmt::Debug for DefaultPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DefaultPolicy")
.field("preferences", &self.preferences)
.field("is_token_aware", &self.is_token_aware)
.field("permit_dc_failover", &self.permit_dc_failover)
.field("latency_awareness", &self.latency_awareness)
.field("fixed_seed", &self.fixed_seed)
.finish_non_exhaustive()
}
}
impl LoadBalancingPolicy for DefaultPolicy {
fn pick<'a>(
&'a self,
query: &'a RoutingInfo,
cluster: &'a ClusterState,
) -> Option<(NodeRef<'a>, Option<Shard>)> {
/* For prepared statements, token-aware logic is available, we know what are the replicas
* for the statement, so that we can pick one of them. */
let routing_info = self.routing_info(query, cluster);
if let Some(ref token_with_strategy) = routing_info.token_with_strategy {
if self.preferences.datacenter().is_some()
&& !self.permit_dc_failover
&& matches!(
token_with_strategy.strategy,
Strategy::SimpleStrategy { .. }
)
{
warn!("\
Combining SimpleStrategy with preferred_datacenter set to Some and disabled datacenter failover may lead to empty query plans for some tokens.\
It is better to give up using one of them: either operate in a keyspace with NetworkTopologyStrategy, which explicitly states\
how many replicas there are in each datacenter (you probably want at least 1 to avoid empty plans while preferring that datacenter), \
or refrain from preferring datacenters (which may ban all other datacenters, if datacenter failover happens to be not possible)."
);
}
}
/* LWT statements need to be routed differently: always to the same replica, to avoid Paxos contention. */
let statement_type = if query.is_confirmed_lwt {
StatementType::Lwt
} else {
StatementType::NonLwt
};
/* Token-aware logic - if routing info is available, we know what are the replicas
* for the statement. Try to pick one of them. */
if let (Some(ts), Some(table_spec)) = (&routing_info.token_with_strategy, query.table) {
if let NodeLocationPreference::DatacenterAndRack(dc, rack) = &self.preferences {
// Try to pick some alive local rack random replica.
let local_rack_picked = self.pick_replica(
ts,
NodeLocationCriteria::DatacenterAndRack(dc, rack),
|node, shard| (self.pick_predicate)(node, Some(shard)),
cluster,
statement_type,
table_spec,
);
if let Some(picked) = local_rack_picked {
return match picked {
PickedReplica::Computed((alive_local_rack_replica, shard)) => {
Some((alive_local_rack_replica, Some(shard)))
}
// Let call to fallback() compute the replica, because it requires allocation.
PickedReplica::ToBeComputedInFallback => None,
};
}
}
if let NodeLocationPreference::DatacenterAndRack(dc, _)
| NodeLocationPreference::Datacenter(dc) = &self.preferences
{
// Try to pick some alive local random replica.
let picked = self.pick_replica(
ts,
NodeLocationCriteria::Datacenter(dc),
|node, shard| (self.pick_predicate)(node, Some(shard)),
cluster,
statement_type,
table_spec,
);
if let Some(picked) = picked {
return match picked {
PickedReplica::Computed((alive_local_replica, shard)) => {
Some((alive_local_replica, Some(shard)))
}
// Let call to fallback() compute the replica, because it requires allocation.
PickedReplica::ToBeComputedInFallback => None,
};
}
}
// If preferred datacenter is not specified, or if datacenter failover is possible, loosen restriction about locality.
if self.preferences.datacenter().is_none()
|| self.is_datacenter_failover_possible(&routing_info)
{
// Try to pick some alive random replica.
let picked = self.pick_replica(
ts,
NodeLocationCriteria::Any,
|node, shard| (self.pick_predicate)(node, Some(shard)),
cluster,
statement_type,
table_spec,
);
if let Some(picked) = picked {
return match picked {
PickedReplica::Computed((alive_remote_replica, shard)) => {
Some((alive_remote_replica, Some(shard)))
}
// Let call to fallback() compute the replica, because it requires allocation.
PickedReplica::ToBeComputedInFallback => None,
};
}
}
};
/* Token-unaware logic - if routing info is not available (e.g. for unprepared statements),
* or no replica was suitable for targeting it (e.g. disabled or down), try to choose
* a random node, not necessarily a replica. */
/* We start having not alive nodes filtered out. This is done by `pick_predicate`,
* which always contains `Self::is_alive()`. */
// Let's start with local nodes, i.e. those in the preferred datacenter.
// If there was no preferred datacenter specified, all nodes are treated as local.
let local_nodes = self.preferred_node_set(cluster);
if let NodeLocationPreference::DatacenterAndRack(dc, rack) = &self.preferences {
// Try to pick some alive random local rack node.
let rack_predicate = Self::make_rack_predicate(
|node| (self.pick_predicate)(node, None),
NodeLocationCriteria::DatacenterAndRack(dc, rack),
);
let local_rack_node_picked = self.pick_node(local_nodes, rack_predicate);
if let Some(alive_local_rack_node) = local_rack_node_picked {
return Some((alive_local_rack_node, None));
}
}
// Try to pick some alive random local node.
let local_node_picked =
self.pick_node(local_nodes, |node| (self.pick_predicate)(node, None));
if let Some(alive_local_node) = local_node_picked {
return Some((alive_local_node, None));
}
let all_nodes = cluster.replica_locator().unique_nodes_in_global_ring();
// If a datacenter failover is possible, loosen restriction about locality.
if self.is_datacenter_failover_possible(&routing_info) {
let maybe_remote_node_picked =
self.pick_node(all_nodes, |node| (self.pick_predicate)(node, None));
if let Some(alive_maybe_remote_node) = maybe_remote_node_picked {
return Some((alive_maybe_remote_node, None));
}
}
/* As we are here, we failed to pick any alive node. Now let's consider even down nodes. */
// Previous checks imply that every node we could have selected is down.
// Let's try to return a down node that wasn't disabled.
let maybe_down_local_node_picked = self.pick_node(local_nodes, |node| node.is_enabled());
if let Some(down_but_enabled_local_node) = maybe_down_local_node_picked {
return Some((down_but_enabled_local_node, None));
}
// If a datacenter failover is possible, loosen restriction about locality.
if self.is_datacenter_failover_possible(&routing_info) {
let maybe_down_maybe_remote_node_picked =
self.pick_node(all_nodes, |node| node.is_enabled());
if let Some(down_but_enabled_maybe_remote_node) = maybe_down_maybe_remote_node_picked {
return Some((down_but_enabled_maybe_remote_node, None));
}
}
// Every node is disabled. This could be due to a bad host filter - configuration error.
// It makes no sense to return disabled nodes (there are no open connections to them anyway),
// so let's return None. `fallback()` will return empty iterator, and so the whole plan
// will be empty.
None
}
fn fallback<'a>(
&'a self,
query: &'a RoutingInfo,
cluster: &'a ClusterState,
) -> FallbackPlan<'a> {
/* For prepared statements, token-aware logic is available, we know what are the replicas
* for the statement, so that we can pick one of them. */
let routing_info = self.routing_info(query, cluster);
/* LWT statements need to be routed differently: always to the same replica, to avoid Paxos contention. */
let statement_type = if query.is_confirmed_lwt {
StatementType::Lwt
} else {
StatementType::NonLwt
};
/* Token-aware logic - if routing info is available, we know what are the replicas for the statement.
* Get a list of alive replicas:
* - shuffled list in case of non-LWTs,
* - deterministically ordered in case of LWTs. */
let maybe_replicas = if let (Some(ts), Some(table_spec)) =
(&routing_info.token_with_strategy, query.table)
{
// Iterator over alive local rack replicas (shuffled or deterministically ordered,
// depending on the statement being LWT or not).
let maybe_local_rack_replicas =
if let NodeLocationPreference::DatacenterAndRack(dc, rack) = &self.preferences {
let local_rack_replicas = self.maybe_shuffled_replicas(
ts,
NodeLocationCriteria::DatacenterAndRack(dc, rack),
|node, shard| Self::is_alive(node, Some(shard)),
cluster,
statement_type,
table_spec,
);
Either::Left(local_rack_replicas)
} else {
Either::Right(std::iter::empty())
};
// Iterator over alive local datacenter replicas (shuffled or deterministically ordered,
// depending on the statement being LWT or not).
let maybe_local_replicas = if let NodeLocationPreference::DatacenterAndRack(dc, _)
| NodeLocationPreference::Datacenter(dc) =
&self.preferences
{
let local_replicas = self.maybe_shuffled_replicas(
ts,
NodeLocationCriteria::Datacenter(dc),
|node, shard| Self::is_alive(node, Some(shard)),
cluster,
statement_type,
table_spec,
);
Either::Left(local_replicas)
} else {
Either::Right(std::iter::empty())
};
// If no datacenter is preferred, or datacenter failover is possible, loosen restriction about locality.
let maybe_remote_replicas = if self.preferences.datacenter().is_none()
|| self.is_datacenter_failover_possible(&routing_info)
{
// Iterator over alive replicas (shuffled or deterministically ordered,
// depending on the statement being LWT or not).
let remote_replicas = self.maybe_shuffled_replicas(
ts,
NodeLocationCriteria::Any,
|node, shard| Self::is_alive(node, Some(shard)),
cluster,
statement_type,
table_spec,
);
Either::Left(remote_replicas)
} else {
Either::Right(std::iter::empty())
};
// Produce an iterator, prioritizing local replicas.
// If preferred datacenter is not specified, every replica is treated as a remote one.
Either::Left(
maybe_local_rack_replicas
.chain(maybe_local_replicas)
.chain(maybe_remote_replicas)
.map(|(node, shard)| (node, Some(shard))),
)
} else {
Either::Right(std::iter::empty::<(NodeRef<'a>, Option<Shard>)>())
};
/* Token-unaware logic - if routing info is not available (e.g. for unprepared statements),
* or no replica is suitable for targeting it (e.g. disabled or down), try targetting nodes
* that are not necessarily replicas. */
/* We start having not alive nodes filtered out. */
// All nodes in the local datacenter (if one is given).
let local_nodes = self.preferred_node_set(cluster);
let robinned_local_rack_nodes =
if let NodeLocationPreference::DatacenterAndRack(dc, rack) = &self.preferences {
let rack_predicate = Self::make_rack_predicate(
|node| Self::is_alive(node, None),
NodeLocationCriteria::DatacenterAndRack(dc, rack),
);
Either::Left(
self.round_robin_nodes(local_nodes, rack_predicate)
.map(|node| (node, None)),
)
} else {
Either::Right(std::iter::empty::<(NodeRef<'a>, Option<Shard>)>())
};
let robinned_local_nodes = self
.round_robin_nodes(local_nodes, |node| Self::is_alive(node, None))
.map(|node| (node, None));
// All nodes in the cluster.
let all_nodes = cluster.replica_locator().unique_nodes_in_global_ring();
// If a datacenter failover is possible, loosen restriction about locality.
let maybe_remote_nodes = if self.is_datacenter_failover_possible(&routing_info) {
let robinned_all_nodes =
self.round_robin_nodes(all_nodes, |node| Self::is_alive(node, None));
Either::Left(robinned_all_nodes.map(|node| (node, None)))
} else {
Either::Right(std::iter::empty::<(NodeRef<'a>, Option<Shard>)>())
};
// Even if we consider some enabled nodes to be down, we should try contacting them in the last resort.
let maybe_down_local_nodes = local_nodes
.iter()
.filter(|node| node.is_enabled())
.map(|node| (node, None));
// If a datacenter failover is possible, loosen restriction about locality.
let maybe_down_nodes = if self.is_datacenter_failover_possible(&routing_info) {
Either::Left(
all_nodes
.iter()
.filter(|node| node.is_enabled())
.map(|node| (node, None)),
)
} else {
Either::Right(std::iter::empty())
};
/// *Plan* should return unique elements. It is not however obvious what it means,
/// because some nodes in the plan may have shards and some may not.
///
/// This helper structure defines equality of plan elements.
/// How the comparison works:
/// - If at least one of elements is shard-less, then compare just nodes.
/// - If both elements have shards, then compare both nodes and shards.
///
/// Why is it implemented this way?
/// Driver should not attempt to send a request to the same destination twice.
/// If a plan element doesn't have shard specified, then a random shard will be
/// chosen by the driver. If the plan also contains the same node but with
/// a shard present, and we randomly choose the same shard for the shard-less element,
/// then we have duplication.
///
/// Example: plan is `[(Node1, Some(1)), (Node1, None)]` - if the driver uses
/// the second element and randomly chooses shard 1, then we have duplication.
///
/// On the other hand, if a plan has a duplicate node, but with different shards,
/// then we want to use both elements - so we can't just make the list unique by node,
/// and so this struct was created.
struct DefaultPolicyTargetComparator {
host_id: Uuid,
shard: Option<Shard>,
}
impl PartialEq for DefaultPolicyTargetComparator {
fn eq(&self, other: &Self) -> bool {
match (self.shard, other.shard) {
(_, None) | (None, _) => self.host_id.eq(&other.host_id),
(Some(shard_left), Some(shard_right)) => {
self.host_id.eq(&other.host_id) && shard_left.eq(&shard_right)
}
}
}
}
impl Eq for DefaultPolicyTargetComparator {}
impl Hash for DefaultPolicyTargetComparator {
fn hash<H: Hasher>(&self, state: &mut H) {
self.host_id.hash(state);
}
}
// Construct a fallback plan as a composition of:
// - local rack alive replicas,
// - local datacenter alive replicas (or all alive replicas is no DC is preferred),
// - remote alive replicas (if DC failover is enabled),
// - local rack alive nodes,
// - local datacenter alive nodes (or all alive nodes is no DC is preferred),
// - remote alive nodes (if DC failover is enabled),
// - local datacenter nodes,
// - remote nodes (if DC failover is enabled).
let plan = maybe_replicas
.chain(robinned_local_rack_nodes)
.chain(robinned_local_nodes)
.chain(maybe_remote_nodes)
.chain(maybe_down_local_nodes)
.chain(maybe_down_nodes)
.unique_by(|(node, shard)| DefaultPolicyTargetComparator {
host_id: node.host_id,
shard: *shard,
});
// If latency awareness is enabled, wrap the plan by applying latency penalisation:
// all penalised nodes are moved behind non-penalised nodes, in a stable fashion.
if let Some(latency_awareness) = self.latency_awareness.as_ref() {
Box::new(latency_awareness.wrap(plan))
} else {
Box::new(plan)
}
}
fn name(&self) -> String {
"DefaultPolicy".to_string()
}
fn on_request_success(
&self,
_routing_info: &RoutingInfo,
latency: Duration,
node: NodeRef<'_>,
) {
if let Some(latency_awareness) = self.latency_awareness.as_ref() {
latency_awareness.report_request(node, latency);
}
}
fn on_request_failure(
&self,
_routing_info: &RoutingInfo,
latency: Duration,
node: NodeRef<'_>,
error: &RequestAttemptError,
) {
if let Some(latency_awareness) = self.latency_awareness.as_ref() {
if LatencyAwareness::reliable_latency_measure(error) {
latency_awareness.report_request(node, latency);
}
}
}
}
impl DefaultPolicy {
/// Creates a builder used to customise configuration of a new DefaultPolicy.
pub fn builder() -> DefaultPolicyBuilder {
DefaultPolicyBuilder::new()
}
/// Returns the given routing info processed based on given cluster state.
fn routing_info<'a>(
&'a self,
query: &'a RoutingInfo,
cluster: &'a ClusterState,
) -> ProcessedRoutingInfo<'a> {
let mut routing_info = ProcessedRoutingInfo::new(query, cluster);
if !self.is_token_aware {
routing_info.token_with_strategy = None;
}
routing_info
}
/// Returns all nodes in the local datacenter if one is given,
/// or else all nodes in the cluster.
fn preferred_node_set<'a>(&'a self, cluster: &'a ClusterState) -> &'a [Arc<Node>] {
if let Some(preferred_datacenter) = self.preferences.datacenter() {
if let Some(nodes) = cluster
.replica_locator()
.unique_nodes_in_datacenter_ring(preferred_datacenter)
{
nodes
} else {
tracing::warn!(
"Datacenter specified as the preferred one ({}) does not exist!",
preferred_datacenter
);
// We won't guess any DC, as it could lead to possible violation of dc failover ban.
&[]
}
} else {
cluster.replica_locator().unique_nodes_in_global_ring()
}
}
/// Returns a full replica set for given datacenter (if given, else for all DCs),
/// cluster state and table spec.
fn nonfiltered_replica_set<'a>(
&'a self,
ts: &TokenWithStrategy<'a>,
replica_location: NodeLocationCriteria<'a>,
cluster: &'a ClusterState,
table_spec: &TableSpec,
) -> ReplicaSet<'a> {
let datacenter = replica_location.datacenter();
cluster
.replica_locator()
.replicas_for_token(ts.token, ts.strategy, datacenter, table_spec)
}
/// Wraps the provided predicate, adding the requirement for rack to match.
fn make_rack_predicate<'a>(
predicate: impl Fn(NodeRef<'a>) -> bool + 'a,
replica_location: NodeLocationCriteria<'a>,
) -> impl Fn(NodeRef<'a>) -> bool {
move |node| match replica_location {
NodeLocationCriteria::Any | NodeLocationCriteria::Datacenter(_) => predicate(node),
NodeLocationCriteria::DatacenterAndRack(_, rack) => {
predicate(node) && node.rack.as_deref() == Some(rack)
}
}
}
/// Wraps the provided predicate, adding the requirement for rack to match.
fn make_sharded_rack_predicate<'a>(
predicate: impl Fn(NodeRef<'a>, Shard) -> bool + 'a,
replica_location: NodeLocationCriteria<'a>,
) -> impl Fn(NodeRef<'a>, Shard) -> bool {
move |node, shard| match replica_location {
NodeLocationCriteria::Any | NodeLocationCriteria::Datacenter(_) => {
predicate(node, shard)
}
NodeLocationCriteria::DatacenterAndRack(_, rack) => {
predicate(node, shard) && node.rack.as_deref() == Some(rack)
}
}
}
/// Returns iterator over replicas for given token and table spec, filtered
/// by provided location criteria and predicate.
/// Respects requested replica order, i.e. if requested, returns replicas ordered
/// deterministically (i.e. by token ring order or by tablet definition order),
/// else returns replicas in arbitrary order.
fn filtered_replicas<'a>(
&'a self,
ts: &TokenWithStrategy<'a>,
replica_location: NodeLocationCriteria<'a>,
predicate: impl Fn(NodeRef<'a>, Shard) -> bool + 'a,
cluster: &'a ClusterState,
order: ReplicaOrder,
table_spec: &TableSpec,
) -> impl Iterator<Item = (NodeRef<'a>, Shard)> {
let predicate = Self::make_sharded_rack_predicate(predicate, replica_location);
let replica_iter = match order {
ReplicaOrder::Arbitrary => Either::Left(
self.nonfiltered_replica_set(ts, replica_location, cluster, table_spec)
.into_iter(),
),
ReplicaOrder::Deterministic => Either::Right(
self.nonfiltered_replica_set(ts, replica_location, cluster, table_spec)
.into_replicas_ordered()
.into_iter(),
),
};
replica_iter.filter(move |(node, shard): &(NodeRef<'a>, Shard)| predicate(node, *shard))
}
/// Picks a replica for given token and table spec which meets the provided location criteria
/// and the predicate.
/// The replica is chosen randomly over all candidates that meet the criteria
/// unless the query is LWT; if so, the first replica meeting the criteria is chosen
/// to avoid Paxos contention.
fn pick_replica<'a>(
&'a self,
ts: &TokenWithStrategy<'a>,
replica_location: NodeLocationCriteria<'a>,
predicate: impl Fn(NodeRef<'a>, Shard) -> bool + 'a,
cluster: &'a ClusterState,
statement_type: StatementType,
table_spec: &TableSpec,
) -> Option<PickedReplica<'a>> {
match statement_type {
StatementType::Lwt => {
self.pick_first_replica(ts, replica_location, predicate, cluster, table_spec)
}
StatementType::NonLwt => self
.pick_random_replica(ts, replica_location, predicate, cluster, table_spec)
.map(PickedReplica::Computed),
}
}
/// Picks the first (wrt the deterministic order imposed on the keyspace, see comment below)
/// replica for given token and table spec which meets the provided location criteria
/// and the predicate.
// This is to be used for LWT optimisation: in order to reduce contention
// caused by Paxos conflicts, we always try to query replicas in the same,
// deterministic order:
// - ring order for token ring keyspaces,
// - tablet definition order for tablet keyspaces.
//
// If preferred rack and DC are set, then the first (encountered on the ring) replica
// that resides in that rack in that DC **and** satisfies the `predicate` is returned.
//
// If preferred DC is set, then the first (encountered on the ring) replica
// that resides in that DC **and** satisfies the `predicate` is returned.
//
// If no DC/rack preferences are set, then the only possible replica to be returned
// (due to expensive computation of the others, and we avoid expensive computation in `pick()`)
// is the primary replica. If it exists, Some is returned, with either Computed(primary_replica)
// **iff** it satisfies the predicate or ToBeComputedInFallback otherwise.
fn pick_first_replica<'a>(
&'a self,
ts: &TokenWithStrategy<'a>,
replica_location: NodeLocationCriteria<'a>,
predicate: impl Fn(NodeRef<'a>, Shard) -> bool + 'a,
cluster: &'a ClusterState,
table_spec: &TableSpec,
) -> Option<PickedReplica<'a>> {
match replica_location {
NodeLocationCriteria::Any => {
// ReplicaSet returned by ReplicaLocator for this case:
// 1) can be precomputed and later used cheaply,
// 2) returns replicas in the **non-ring order** (this because ReplicaSet chains
// ring-ordered replicas sequences from different DCs, thus not preserving
// the global ring order).
// Because of 2), we can't use a precomputed ReplicaSet, but instead we need ReplicasOrdered.
// As ReplicasOrdered can compute cheaply only the primary global replica
// (computation of the remaining ones is expensive), in case that the primary replica
// does not satisfy the `predicate`, ToBeComputedInFallback is returned.
// All expensive computation is to be done only when `fallback()` is called.
self.nonfiltered_replica_set(ts, replica_location, cluster, table_spec)
.into_replicas_ordered()
.into_iter()
.next()
.map(|(primary_replica, shard)| {
if predicate(primary_replica, shard) {
PickedReplica::Computed((primary_replica, shard))
} else {
PickedReplica::ToBeComputedInFallback
}
})
}
NodeLocationCriteria::Datacenter(_) | NodeLocationCriteria::DatacenterAndRack(_, _) => {
// ReplicaSet returned by ReplicaLocator for this case:
// 1) can be precomputed and later used cheaply,
// 2) returns replicas in the ring order (this is not true for the case
// when multiple DCs are allowed, because ReplicaSet chains replicas sequences
// from different DCs, thus not preserving the global ring order)
self.filtered_replicas(
ts,
replica_location,
predicate,
cluster,
ReplicaOrder::Deterministic,
table_spec,
)
.next()
.map(PickedReplica::Computed)
}
}
}
/// Picks a random replica for given token and table spec which meets the provided
/// location criteria and the predicate.
fn pick_random_replica<'a>(
&'a self,
ts: &TokenWithStrategy<'a>,
replica_location: NodeLocationCriteria<'a>,
predicate: impl Fn(NodeRef<'a>, Shard) -> bool + 'a,
cluster: &'a ClusterState,
table_spec: &TableSpec,
) -> Option<(NodeRef<'a>, Shard)> {
let predicate = Self::make_sharded_rack_predicate(predicate, replica_location);
let replica_set = self.nonfiltered_replica_set(ts, replica_location, cluster, table_spec);
if let Some(fixed) = self.fixed_seed {
let mut gen = Pcg32::new(fixed, 0);
replica_set.choose_filtered(&mut gen, |(node, shard)| predicate(node, *shard))
} else {
replica_set.choose_filtered(&mut rng(), |(node, shard)| predicate(node, *shard))
}
}
/// Returns iterator over replicas for given token and table spec, filtered
/// by provided location criteria and predicate.
/// By default, the replicas are shuffled.
/// For LWTs, though, the replicas are instead returned in a deterministic order.
fn maybe_shuffled_replicas<'a>(
&'a self,
ts: &TokenWithStrategy<'a>,
replica_location: NodeLocationCriteria<'a>,
predicate: impl Fn(NodeRef<'a>, Shard) -> bool + 'a,
cluster: &'a ClusterState,
statement_type: StatementType,
table_spec: &TableSpec,
) -> impl Iterator<Item = (NodeRef<'a>, Shard)> {
let order = match statement_type {
StatementType::Lwt => ReplicaOrder::Deterministic,
StatementType::NonLwt => ReplicaOrder::Arbitrary,
};
let replicas =
self.filtered_replicas(ts, replica_location, predicate, cluster, order, table_spec);
match statement_type {
// As an LWT optimisation: in order to reduce contention caused by Paxos conflicts,
// we always try to query replicas in the same order.
StatementType::Lwt => Either::Left(replicas),
StatementType::NonLwt => Either::Right(self.shuffle(replicas)),
}
}
/// Returns an iterator over the given slice of nodes, rotated by a random shift.
fn randomly_rotated_nodes(nodes: &[Arc<Node>]) -> impl Iterator<Item = NodeRef<'_>> {
// Create a randomly rotated slice view
let nodes_len = nodes.len();
if nodes_len > 0 {
let index = rng().random_range(0..nodes_len); // gen_range() panics when range is empty!
Either::Left(
nodes[index..]
.iter()
.chain(nodes[..index].iter())
.take(nodes.len()),
)
} else {
Either::Right(std::iter::empty())
}
}
/// Picks a random node from the slice of nodes. The node must satisfy the given predicate.
fn pick_node<'a>(
&'a self,
nodes: &'a [Arc<Node>],
predicate: impl Fn(NodeRef<'a>) -> bool,
) -> Option<NodeRef<'a>> {
// Select the first node that matches the predicate
Self::randomly_rotated_nodes(nodes).find(|&node| predicate(node))
}
/// Returns an iterator over the given slice of nodes, rotated by a random shift
/// and filtered by given predicate.
fn round_robin_nodes<'a>(
&'a self,
nodes: &'a [Arc<Node>],
predicate: impl Fn(NodeRef<'a>) -> bool,
) -> impl Iterator<Item = NodeRef<'a>> {
Self::randomly_rotated_nodes(nodes).filter(move |node| predicate(node))
}
/// Wraps a given iterator by shuffling its contents.
fn shuffle<'a>(
&self,
iter: impl Iterator<Item = (NodeRef<'a>, Shard)>,
) -> impl Iterator<Item = (NodeRef<'a>, Shard)> {
let mut vec: Vec<(NodeRef<'_>, Shard)> = iter.collect();
if let Some(fixed) = self.fixed_seed {
let mut gen = Pcg32::new(fixed, 0);
vec.shuffle(&mut gen);
} else {
vec.shuffle(&mut rng());
}
vec.into_iter()
}
/// Returns true iff the node should be considered to be alive.
fn is_alive(node: NodeRef, _shard: Option<Shard>) -> bool {
// For now, we leave this as stub, until we have time to improve node events.
// node.is_enabled() && !node.is_down()
node.is_enabled()
}
/// Returns true iff the datacenter failover is permitted for the statement being executed.
fn is_datacenter_failover_possible(&self, routing_info: &ProcessedRoutingInfo) -> bool {
self.preferences.datacenter().is_some()
&& self.permit_dc_failover
&& !routing_info.local_consistency
}
}
impl Default for DefaultPolicy {
fn default() -> Self {
Self {
preferences: NodeLocationPreference::Any,
is_token_aware: true,
permit_dc_failover: false,
pick_predicate: Box::new(Self::is_alive),
latency_awareness: None,
fixed_seed: None,
}
}
}
/// The intended way to instantiate the DefaultPolicy.
///
/// # Example
/// ```
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use scylla::policies::load_balancing::DefaultPolicy;
///
/// let default_policy = DefaultPolicy::builder()
/// .prefer_datacenter("dc1".to_string())
/// .token_aware(true)
/// .permit_dc_failover(true)
/// .build();
/// # Ok(())
/// # }
#[derive(Clone, Debug)]
pub struct DefaultPolicyBuilder {
preferences: NodeLocationPreference,
is_token_aware: bool,
permit_dc_failover: bool,
latency_awareness: Option<LatencyAwarenessBuilder>,
enable_replica_shuffle: bool,
}
impl DefaultPolicyBuilder {
/// Creates a builder used to customise configuration of a new DefaultPolicy.
pub fn new() -> Self {
Self {
preferences: NodeLocationPreference::Any,
is_token_aware: true,
permit_dc_failover: false,
latency_awareness: None,
enable_replica_shuffle: true,
}
}
/// Builds a new DefaultPolicy with the previously set configuration.
pub fn build(self) -> Arc<dyn LoadBalancingPolicy> {
let latency_awareness = self.latency_awareness.map(|builder| builder.build());
let pick_predicate = if let Some(ref latency_awareness) = latency_awareness {
let latency_predicate = latency_awareness.generate_predicate();
Box::new(move |node: NodeRef<'_>, shard| {
DefaultPolicy::is_alive(node, shard) && latency_predicate(node)
})
as Box<dyn Fn(NodeRef<'_>, Option<Shard>) -> bool + Send + Sync + 'static>
} else {
Box::new(DefaultPolicy::is_alive)
};
Arc::new(DefaultPolicy {
preferences: self.preferences,
is_token_aware: self.is_token_aware,
permit_dc_failover: self.permit_dc_failover,
pick_predicate,
latency_awareness,
fixed_seed: (!self.enable_replica_shuffle).then(|| {
let seed = rand::random();
debug!("DefaultPolicy: setting fixed seed to {}", seed);
seed
}),
})
}
/// Sets the datacenter to be preferred by this policy.
///
/// Allows the load balancing policy to prioritize nodes based on their location.
/// When a preferred datacenter is set, the policy will treat nodes in that
/// datacenter as "local" nodes, and nodes in other datacenters as "remote" nodes.
/// This affects the order in which nodes are returned by the policy when