forked from scylladb/scylla-rust-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata.rs
2162 lines (1943 loc) · 77 KB
/
metadata.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
//! This module holds entities that represent the cluster metadata,
//! which includes:
//! - topology metadata:
//! - [Peer],
//! - schema metadata:
//! - [Keyspace],
//! - [Strategy] - replication strategy employed by a keyspace,
//! - [Table],
//! - [Column],
//! - [ColumnKind],
//! - [MaterializedView],
//! - CQL types (re-exported from scylla-cql):
//! - [ColumnType],
//! - [NativeType],
//! - [UserDefinedType],
//! - [CollectionType],
//!
use crate::client::pager::{NextPageError, NextRowError, QueryPager};
use crate::cluster::node::resolve_contact_points;
use crate::deserialize::DeserializeOwnedRow;
use crate::errors::{
DbError, MetadataFetchError, MetadataFetchErrorKind, NewSessionError, RequestAttemptError,
};
use crate::frame::response::event::Event;
use crate::network::{Connection, ConnectionConfig, NodeConnectionPool, PoolConfig, PoolSize};
use crate::policies::host_filter::HostFilter;
use crate::routing::Token;
use crate::statement::unprepared::Statement;
use crate::utils::parse::{ParseErrorCause, ParseResult, ParserState};
use futures::future::{self, FutureExt};
use futures::stream::{self, StreamExt, TryStreamExt};
use futures::Stream;
use itertools::Itertools;
use rand::seq::{IndexedRandom, SliceRandom};
use rand::{rng, Rng};
use scylla_cql::frame::response::result::{ColumnSpec, TableSpec};
use scylla_macros::DeserializeRow;
use std::borrow::BorrowMut;
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::{self, Formatter};
use std::net::{IpAddr, SocketAddr};
use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use tokio::sync::{broadcast, mpsc};
use tracing::{debug, error, trace, warn};
use uuid::Uuid;
use crate::cluster::node::{InternalKnownNode, NodeAddr, ResolvedContactPoint};
use crate::errors::{
KeyspaceStrategyError, KeyspacesMetadataError, MetadataError, PeersMetadataError, RequestError,
TablesMetadataError, UdtMetadataError,
};
// Re-export of CQL types.
pub use scylla_cql::frame::response::result::{
CollectionType, ColumnType, NativeType, UserDefinedType,
};
type PerKeyspace<T> = HashMap<String, T>;
type PerKeyspaceResult<T, E> = PerKeyspace<Result<T, E>>;
type PerTable<T> = HashMap<String, T>;
type PerKsTable<T> = HashMap<(String, String), T>;
type PerKsTableResult<T, E> = PerKsTable<Result<T, E>>;
/// Indicates that reading metadata failed, but in a way
/// that we can handle, by throwing out data for a keyspace.
/// It is possible that some of the errors could be handled in even
/// more granular way (e.g. throwing out a single table), but keyspace
/// granularity seems like a good choice given how independent keyspaces
/// are from each other.
#[derive(Clone, Debug, Error)]
pub(crate) enum SingleKeyspaceMetadataError {
#[error(transparent)]
MissingUDT(MissingUserDefinedType),
#[error("Partition key column with position {0} is missing from metadata")]
IncompletePartitionKey(i32),
#[error("Clustering key column with position {0} is missing from metadata")]
IncompleteClusteringKey(i32),
}
/// Allows to read current metadata from the cluster
pub(crate) struct MetadataReader {
control_connection_pool_config: PoolConfig,
control_connection_endpoint: UntranslatedEndpoint,
control_connection: NodeConnectionPool,
// when control connection fails, MetadataReader tries to connect to one of known_peers
known_peers: Vec<UntranslatedEndpoint>,
keyspaces_to_fetch: Vec<String>,
fetch_schema: bool,
host_filter: Option<Arc<dyn HostFilter>>,
// When no known peer is reachable, initial known nodes are resolved once again as a fallback
// and establishing control connection to them is attempted.
initial_known_nodes: Vec<InternalKnownNode>,
// When a control connection breaks, the PoolRefiller of its pool uses the requester
// to signal ClusterWorker that an immediate metadata refresh is advisable.
control_connection_repair_requester: broadcast::Sender<()>,
}
/// Describes all metadata retrieved from the cluster
pub(crate) struct Metadata {
pub(crate) peers: Vec<Peer>,
pub(crate) keyspaces: HashMap<String, Result<Keyspace, SingleKeyspaceMetadataError>>,
}
#[non_exhaustive] // <- so that we can add more fields in a backwards-compatible way
pub struct Peer {
pub host_id: Uuid,
pub address: NodeAddr,
pub tokens: Vec<Token>,
pub datacenter: Option<String>,
pub rack: Option<String>,
}
/// An endpoint for a node that the driver is to issue connections to,
/// possibly after prior address translation.
#[derive(Clone, Debug)]
pub(crate) enum UntranslatedEndpoint {
/// Provided by user in SessionConfig (initial contact points).
ContactPoint(ResolvedContactPoint),
/// Fetched in Metadata with `query_peers()`
Peer(PeerEndpoint),
}
impl UntranslatedEndpoint {
pub(crate) fn address(&self) -> NodeAddr {
match *self {
UntranslatedEndpoint::ContactPoint(ResolvedContactPoint { address, .. }) => {
NodeAddr::Untranslatable(address)
}
UntranslatedEndpoint::Peer(PeerEndpoint { address, .. }) => address,
}
}
pub(crate) fn set_port(&mut self, port: u16) {
let inner_addr = match self {
UntranslatedEndpoint::ContactPoint(ResolvedContactPoint { address, .. }) => address,
UntranslatedEndpoint::Peer(PeerEndpoint { address, .. }) => address.inner_mut(),
};
inner_addr.set_port(port);
}
}
/// Data used to issue connections to a node.
///
/// Fetched from the cluster in Metadata.
#[non_exhaustive] // <- so that we can add more fields in a backwards-compatible way
#[derive(Clone, Debug)]
pub struct PeerEndpoint {
pub host_id: Uuid,
pub address: NodeAddr,
pub datacenter: Option<String>,
pub rack: Option<String>,
}
impl Peer {
pub(crate) fn to_peer_endpoint(&self) -> PeerEndpoint {
PeerEndpoint {
host_id: self.host_id,
address: self.address,
datacenter: self.datacenter.clone(),
rack: self.rack.clone(),
}
}
pub(crate) fn into_peer_endpoint_and_tokens(self) -> (PeerEndpoint, Vec<Token>) {
(
PeerEndpoint {
host_id: self.host_id,
address: self.address,
datacenter: self.datacenter,
rack: self.rack,
},
self.tokens,
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Keyspace {
pub strategy: Strategy,
/// Empty HashMap may as well mean that the client disabled schema fetching in SessionConfig
pub tables: HashMap<String, Table>,
/// Empty HashMap may as well mean that the client disabled schema fetching in SessionConfig
pub views: HashMap<String, MaterializedView>,
/// Empty HashMap may as well mean that the client disabled schema fetching in SessionConfig
pub user_defined_types: HashMap<String, Arc<UserDefinedType<'static>>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Table {
pub columns: HashMap<String, Column>,
/// Names of the column of partition key.
/// All of the names are guaranteed to be present in `columns` field.
pub partition_key: Vec<String>,
/// Names of the column of clustering key.
/// All of the names are guaranteed to be present in `columns` field.
pub clustering_key: Vec<String>,
pub partitioner: Option<String>,
pub(crate) pk_column_specs: Vec<ColumnSpec<'static>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MaterializedView {
pub view_metadata: Table,
pub base_table_name: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Column {
pub typ: ColumnType<'static>,
pub kind: ColumnKind,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum PreColumnType {
Native(NativeType),
Collection {
frozen: bool,
typ: PreCollectionType,
},
Tuple(Vec<PreColumnType>),
Vector {
typ: Box<PreColumnType>,
dimensions: u16,
},
UserDefinedType {
frozen: bool,
name: String,
},
}
impl PreColumnType {
pub(crate) fn into_cql_type(
self,
keyspace_name: &String,
keyspace_udts: &PerTable<Arc<UserDefinedType<'static>>>,
) -> Result<ColumnType<'static>, MissingUserDefinedType> {
match self {
PreColumnType::Native(n) => Ok(ColumnType::Native(n)),
PreColumnType::Collection { frozen, typ: type_ } => type_
.into_collection_type(keyspace_name, keyspace_udts)
.map(|inner| ColumnType::Collection { frozen, typ: inner }),
PreColumnType::Tuple(t) => t
.into_iter()
.map(|t| t.into_cql_type(keyspace_name, keyspace_udts))
.collect::<Result<Vec<ColumnType>, MissingUserDefinedType>>()
.map(ColumnType::Tuple),
PreColumnType::Vector {
typ: type_,
dimensions,
} => type_
.into_cql_type(keyspace_name, keyspace_udts)
.map(|inner| ColumnType::Vector {
typ: Box::new(inner),
dimensions,
}),
PreColumnType::UserDefinedType { frozen, name } => {
let definition = match keyspace_udts.get(&name) {
Some(def) => def.clone(),
None => {
return Err(MissingUserDefinedType {
name,
keyspace: keyspace_name.clone(),
})
}
};
Ok(ColumnType::UserDefinedType { frozen, definition })
}
}
}
}
/// Represents a user defined type whose definition is missing from the metadata.
#[derive(Clone, Debug, Error)]
#[error("Missing UDT: {keyspace}, {name}")]
pub(crate) struct MissingUserDefinedType {
name: String,
keyspace: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum PreCollectionType {
List(Box<PreColumnType>),
Map(Box<PreColumnType>, Box<PreColumnType>),
Set(Box<PreColumnType>),
}
impl PreCollectionType {
pub(crate) fn into_collection_type(
self,
keyspace_name: &String,
keyspace_udts: &PerTable<Arc<UserDefinedType<'static>>>,
) -> Result<CollectionType<'static>, MissingUserDefinedType> {
match self {
PreCollectionType::List(t) => t
.into_cql_type(keyspace_name, keyspace_udts)
.map(|inner| CollectionType::List(Box::new(inner))),
PreCollectionType::Map(tk, tv) => Ok(CollectionType::Map(
Box::new(tk.into_cql_type(keyspace_name, keyspace_udts)?),
Box::new(tv.into_cql_type(keyspace_name, keyspace_udts)?),
)),
PreCollectionType::Set(t) => t
.into_cql_type(keyspace_name, keyspace_udts)
.map(|inner| CollectionType::Set(Box::new(inner))),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ColumnKind {
Regular,
Static,
Clustering,
PartitionKey,
}
/// [ColumnKind] parse error
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColumnKindFromStrError;
impl std::str::FromStr for ColumnKind {
type Err = ColumnKindFromStrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"regular" => Ok(Self::Regular),
"static" => Ok(Self::Static),
"clustering" => Ok(Self::Clustering),
"partition_key" => Ok(Self::PartitionKey),
_ => Err(ColumnKindFromStrError),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
pub enum Strategy {
SimpleStrategy {
replication_factor: usize,
},
NetworkTopologyStrategy {
// Replication factors of datacenters with given names
datacenter_repfactors: HashMap<String, usize>,
},
LocalStrategy, // replication_factor == 1
Other {
name: String,
data: HashMap<String, String>,
},
}
#[derive(Clone, Debug)]
struct InvalidCqlType {
typ: String,
position: usize,
reason: String,
}
impl fmt::Display for InvalidCqlType {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl Metadata {
/// Creates new, dummy metadata from a given list of peers.
///
/// It can be used as a replacement for real metadata when initial
/// metadata read fails.
pub(crate) fn new_dummy(initial_peers: &[UntranslatedEndpoint]) -> Self {
let peers = initial_peers
.iter()
.enumerate()
.map(|(id, endpoint)| {
// Given N nodes, divide the ring into N roughly equal parts
// and assign them to each node.
let token = ((id as u128) << 64) / initial_peers.len() as u128;
Peer {
address: endpoint.address(),
tokens: vec![Token::new(token as i64)],
datacenter: None,
rack: None,
host_id: Uuid::new_v4(),
}
})
.collect();
Metadata {
peers,
keyspaces: HashMap::new(),
}
}
}
impl MetadataReader {
/// Creates new MetadataReader, which connects to initially_known_peers in the background
#[allow(clippy::too_many_arguments)]
pub(crate) async fn new(
initial_known_nodes: Vec<InternalKnownNode>,
control_connection_repair_requester: broadcast::Sender<()>,
mut connection_config: ConnectionConfig,
server_event_sender: mpsc::Sender<Event>,
keyspaces_to_fetch: Vec<String>,
fetch_schema: bool,
host_filter: &Option<Arc<dyn HostFilter>>,
) -> Result<Self, NewSessionError> {
let (initial_peers, resolved_hostnames) =
resolve_contact_points(&initial_known_nodes).await;
// Ensure there is at least one resolved node
if initial_peers.is_empty() {
return Err(NewSessionError::FailedToResolveAnyHostname(
resolved_hostnames,
));
}
let control_connection_endpoint = UntranslatedEndpoint::ContactPoint(
initial_peers
.choose(&mut rng())
.expect("Tried to initialize MetadataReader with empty initial_known_nodes list!")
.clone(),
);
// setting event_sender field in connection config will cause control connection to
// - send REGISTER message to receive server events
// - send received events via server_event_sender
connection_config.event_sender = Some(server_event_sender);
let control_connection_pool_config = PoolConfig {
connection_config,
// We want to have only one connection to receive events from
pool_size: PoolSize::PerHost(NonZeroUsize::new(1).unwrap()),
// The shard-aware port won't be used with PerHost pool size anyway,
// so explicitly disable it here
can_use_shard_aware_port: false,
};
let control_connection = Self::make_control_connection_pool(
control_connection_endpoint.clone(),
&control_connection_pool_config,
control_connection_repair_requester.clone(),
);
Ok(MetadataReader {
control_connection_pool_config,
control_connection_endpoint,
control_connection,
known_peers: initial_peers
.into_iter()
.map(UntranslatedEndpoint::ContactPoint)
.collect(),
keyspaces_to_fetch,
fetch_schema,
host_filter: host_filter.clone(),
initial_known_nodes,
control_connection_repair_requester,
})
}
/// Fetches current metadata from the cluster
pub(crate) async fn read_metadata(&mut self, initial: bool) -> Result<Metadata, MetadataError> {
let mut result = self.fetch_metadata(initial).await;
let prev_err = match result {
Ok(metadata) => {
debug!("Fetched new metadata");
self.update_known_peers(&metadata);
if initial {
self.handle_unaccepted_host_in_control_connection(&metadata);
}
return Ok(metadata);
}
Err(err) => err,
};
// At this point, we known that fetching metadata on currect control connection failed.
// Therefore, we try to fetch metadata from other known peers, in order.
// shuffle known_peers to iterate through them in random order later
self.known_peers.shuffle(&mut rng());
debug!("Known peers: {:?}", self.known_peers.iter().format(", "));
let address_of_failed_control_connection = self.control_connection_endpoint.address();
let filtered_known_peers = self
.known_peers
.clone()
.into_iter()
.filter(|peer| peer.address() != address_of_failed_control_connection);
// if fetching metadata on current control connection failed,
// try to fetch metadata from other known peer
result = self
.retry_fetch_metadata_on_nodes(initial, filtered_known_peers, prev_err)
.await;
if let Err(prev_err) = result {
if !initial {
// If no known peer is reachable, try falling back to initial contact points, in hope that
// there are some hostnames there which will resolve to reachable new addresses.
warn!("Failed to establish control connection and fetch metadata on all known peers. Falling back to initial contact points.");
let (initial_peers, _hostnames) =
resolve_contact_points(&self.initial_known_nodes).await;
result = self
.retry_fetch_metadata_on_nodes(
initial,
initial_peers
.into_iter()
.map(UntranslatedEndpoint::ContactPoint),
prev_err,
)
.await;
} else {
// No point in falling back as this is an initial connection attempt.
result = Err(prev_err);
}
}
match &result {
Ok(metadata) => {
self.update_known_peers(metadata);
self.handle_unaccepted_host_in_control_connection(metadata);
debug!("Fetched new metadata");
}
Err(error) => error!(
error = %error,
"Could not fetch metadata"
),
}
result
}
async fn retry_fetch_metadata_on_nodes(
&mut self,
initial: bool,
nodes: impl Iterator<Item = UntranslatedEndpoint>,
prev_err: MetadataError,
) -> Result<Metadata, MetadataError> {
let mut result = Err(prev_err);
for peer in nodes {
let err = match result {
Ok(_) => break,
Err(err) => err,
};
warn!(
control_connection_address = tracing::field::display(self
.control_connection_endpoint
.address()),
error = %err,
"Failed to fetch metadata using current control connection"
);
self.control_connection_endpoint = peer.clone();
self.control_connection = Self::make_control_connection_pool(
self.control_connection_endpoint.clone(),
&self.control_connection_pool_config,
self.control_connection_repair_requester.clone(),
);
debug!(
"Retrying to establish the control connection on {}",
self.control_connection_endpoint.address()
);
result = self.fetch_metadata(initial).await;
}
result
}
async fn fetch_metadata(&self, initial: bool) -> Result<Metadata, MetadataError> {
// TODO: Timeouts?
self.control_connection.wait_until_initialized().await;
let conn = &self.control_connection.random_connection()?;
let res = query_metadata(
conn,
self.control_connection_endpoint.address().port(),
&self.keyspaces_to_fetch,
self.fetch_schema,
)
.await;
if initial {
if let Err(err) = res {
warn!(
error = ?err,
"Initial metadata read failed, proceeding with metadata \
consisting only of the initial peer list and dummy tokens. \
This might result in suboptimal performance and schema \
information not being available."
);
return Ok(Metadata::new_dummy(&self.known_peers));
}
}
res
}
fn update_known_peers(&mut self, metadata: &Metadata) {
let host_filter = self.host_filter.as_ref();
self.known_peers = metadata
.peers
.iter()
.filter(|peer| host_filter.map_or(true, |f| f.accept(peer)))
.map(|peer| UntranslatedEndpoint::Peer(peer.to_peer_endpoint()))
.collect();
// Check if the host filter isn't accidentally too restrictive,
// and print an error message about this fact
if !metadata.peers.is_empty() && self.known_peers.is_empty() {
error!(
node_ips = tracing::field::display(
metadata.peers.iter().map(|peer| peer.address).format(", ")
),
"The host filter rejected all nodes in the cluster, \
no connections that can serve user queries have been \
established. The session cannot serve any queries!"
)
}
}
fn handle_unaccepted_host_in_control_connection(&mut self, metadata: &Metadata) {
let control_connection_peer = metadata
.peers
.iter()
.find(|peer| matches!(self.control_connection_endpoint, UntranslatedEndpoint::Peer(PeerEndpoint{address, ..}) if address == peer.address));
if let Some(peer) = control_connection_peer {
if !self.host_filter.as_ref().map_or(true, |f| f.accept(peer)) {
warn!(
filtered_node_ips = tracing::field::display(metadata
.peers
.iter()
.filter(|peer| self.host_filter.as_ref().map_or(true, |p| p.accept(peer)))
.map(|peer| peer.address)
.format(", ")
),
control_connection_address = ?self.control_connection_endpoint.address(),
"The node that the control connection is established to \
is not accepted by the host filter. Please verify that \
the nodes in your initial peers list are accepted by the \
host filter. The driver will try to re-establish the \
control connection to a different node."
);
// Assuming here that known_peers are up-to-date
if !self.known_peers.is_empty() {
self.control_connection_endpoint = self
.known_peers
.choose(&mut rng())
.expect("known_peers is empty - should be impossible")
.clone();
self.control_connection = Self::make_control_connection_pool(
self.control_connection_endpoint.clone(),
&self.control_connection_pool_config,
self.control_connection_repair_requester.clone(),
);
}
}
}
}
fn make_control_connection_pool(
endpoint: UntranslatedEndpoint,
pool_config: &PoolConfig,
refresh_requester: broadcast::Sender<()>,
) -> NodeConnectionPool {
NodeConnectionPool::new(endpoint, pool_config, None, refresh_requester)
}
}
async fn query_metadata(
conn: &Arc<Connection>,
connect_port: u16,
keyspace_to_fetch: &[String],
fetch_schema: bool,
) -> Result<Metadata, MetadataError> {
let peers_query = query_peers(conn, connect_port);
let keyspaces_query = query_keyspaces(conn, keyspace_to_fetch, fetch_schema);
let (peers, keyspaces) = tokio::try_join!(peers_query, keyspaces_query)?;
// There must be at least one peer
if peers.is_empty() {
return Err(MetadataError::Peers(PeersMetadataError::EmptyPeers));
}
// At least one peer has to have some tokens
if peers.iter().all(|peer| peer.tokens.is_empty()) {
return Err(MetadataError::Peers(PeersMetadataError::EmptyTokenLists));
}
Ok(Metadata { peers, keyspaces })
}
#[derive(DeserializeRow)]
#[scylla(crate = "scylla_cql")]
struct NodeInfoRow {
host_id: Option<Uuid>,
#[scylla(rename = "rpc_address")]
untranslated_ip_addr: IpAddr,
#[scylla(rename = "data_center")]
datacenter: Option<String>,
rack: Option<String>,
tokens: Option<Vec<String>>,
}
#[derive(Clone, Copy)]
enum NodeInfoSource {
Local,
Peer,
}
impl NodeInfoSource {
fn describe(&self) -> &'static str {
match self {
Self::Local => "local node",
Self::Peer => "peer",
}
}
}
const METADATA_QUERY_PAGE_SIZE: i32 = 1024;
async fn query_peers(
conn: &Arc<Connection>,
connect_port: u16,
) -> Result<Vec<Peer>, MetadataError> {
let mut peers_query =
Statement::new("select host_id, rpc_address, data_center, rack, tokens from system.peers");
peers_query.set_page_size(METADATA_QUERY_PAGE_SIZE);
let peers_query_stream = conn
.clone()
.query_iter(peers_query)
.map(|pager_res| {
let pager = pager_res?;
let rows_stream = pager.rows_stream::<NodeInfoRow>()?;
Ok::<_, MetadataFetchErrorKind>(rows_stream)
})
.into_stream()
.map(|result| result.map(|stream| stream.map_err(MetadataFetchErrorKind::NextRowError)))
.try_flatten()
// Add table context to the error.
.map_err(|error| MetadataFetchError {
error,
table: "system.peers",
})
.and_then(|row_result| future::ok((NodeInfoSource::Peer, row_result)));
let mut local_query =
Statement::new("select host_id, rpc_address, data_center, rack, tokens from system.local WHERE key='local'");
local_query.set_page_size(METADATA_QUERY_PAGE_SIZE);
let local_query_stream = conn
.clone()
.query_iter(local_query)
.map(|pager_res| {
let pager = pager_res?;
let rows_stream = pager.rows_stream::<NodeInfoRow>()?;
Ok::<_, MetadataFetchErrorKind>(rows_stream)
})
.into_stream()
.map(|result| result.map(|stream| stream.map_err(MetadataFetchErrorKind::NextRowError)))
.try_flatten()
// Add table context to the error.
.map_err(|error| MetadataFetchError {
error,
table: "system.local",
})
.and_then(|row_result| future::ok((NodeInfoSource::Local, row_result)));
let untranslated_rows = stream::select(peers_query_stream, local_query_stream);
let local_ip: IpAddr = conn.get_connect_address().ip();
let local_address = SocketAddr::new(local_ip, connect_port);
let translated_peers_futures = untranslated_rows.map(|row_result| async {
match row_result {
Ok((source, row)) => create_peer_from_row(source, row, local_address).await,
Err(err) => {
warn!(
"system.peers or system.local has an invalid row, skipping it: {}",
err
);
None
}
}
});
let peers = translated_peers_futures
.buffer_unordered(256)
.filter_map(std::future::ready)
.collect::<Vec<_>>()
.await;
Ok(peers)
}
async fn create_peer_from_row(
source: NodeInfoSource,
row: NodeInfoRow,
local_address: SocketAddr,
) -> Option<Peer> {
let NodeInfoRow {
host_id,
untranslated_ip_addr,
datacenter,
rack,
tokens,
} = row;
let host_id = match host_id {
Some(host_id) => host_id,
None => {
warn!("{} (untranslated ip: {}, dc: {:?}, rack: {:?}) has Host ID set to null; skipping node.", source.describe(), untranslated_ip_addr, datacenter, rack);
return None;
}
};
let connect_port = local_address.port();
let untranslated_address = SocketAddr::new(untranslated_ip_addr, connect_port);
let node_addr = match source {
NodeInfoSource::Local => {
// For the local node we should use connection's address instead of rpc_address.
// (The reason is that rpc_address in system.local can be wrong.)
// Thus, we replace address in local_rows with connection's address.
// We need to replace rpc_address with control connection address.
NodeAddr::Untranslatable(local_address)
}
NodeInfoSource::Peer => {
// The usual case - no translation.
NodeAddr::Translatable(untranslated_address)
}
};
let tokens_str: Vec<String> = tokens.unwrap_or_default();
// Parse string representation of tokens as integer values
let tokens: Vec<Token> = match tokens_str
.iter()
.map(|s| Token::from_str(s))
.collect::<Result<Vec<Token>, _>>()
{
Ok(parsed) => parsed,
Err(e) => {
// FIXME: we could allow the users to provide custom partitioning information
// in order for it to work with non-standard token sizes.
// Also, we could implement support for Cassandra's other standard partitioners
// like RandomPartitioner or ByteOrderedPartitioner.
trace!("Couldn't parse tokens as 64-bit integers: {}, proceeding with a dummy token. If you're using a partitioner with different token size, consider migrating to murmur3", e);
vec![Token::new(rand::rng().random::<i64>())]
}
};
Some(Peer {
host_id,
address: node_addr,
tokens,
datacenter,
rack,
})
}
fn query_filter_keyspace_name<'a, R>(
conn: &Arc<Connection>,
query_str: &'a str,
keyspaces_to_fetch: &'a [String],
) -> impl Stream<Item = Result<R, MetadataFetchErrorKind>> + 'a
where
R: DeserializeOwnedRow + 'static,
{
let conn = conn.clone();
// This function is extracted to reduce monomorphisation penalty:
// query_filter_keyspace_name() is going to be monomorphised into 5 distinct functions,
// so it's better to extract the common part.
async fn make_keyspace_filtered_query_pager(
conn: Arc<Connection>,
query_str: &str,
keyspaces_to_fetch: &[String],
) -> Result<QueryPager, MetadataFetchErrorKind> {
if keyspaces_to_fetch.is_empty() {
let mut query = Statement::new(query_str);
query.set_page_size(METADATA_QUERY_PAGE_SIZE);
conn.query_iter(query)
.await
.map_err(MetadataFetchErrorKind::NextRowError)
} else {
let keyspaces = &[keyspaces_to_fetch] as &[&[String]];
let query_str = format!("{query_str} where keyspace_name in ?");
let mut query = Statement::new(query_str);
query.set_page_size(METADATA_QUERY_PAGE_SIZE);
let prepared = conn.prepare(&query).await?;
let serialized_values = prepared.serialize_values(&keyspaces)?;
conn.execute_iter(prepared, serialized_values)
.await
.map_err(MetadataFetchErrorKind::NextRowError)
}
}
let fut = async move {
let pager = make_keyspace_filtered_query_pager(conn, query_str, keyspaces_to_fetch).await?;
let stream: crate::client::pager::TypedRowStream<R> = pager.rows_stream::<R>()?;
Ok::<_, MetadataFetchErrorKind>(stream)
};
fut.into_stream()
.map(|result| result.map(|stream| stream.map_err(MetadataFetchErrorKind::NextRowError)))
.try_flatten()
}
async fn query_keyspaces(
conn: &Arc<Connection>,
keyspaces_to_fetch: &[String],
fetch_schema: bool,
) -> Result<PerKeyspaceResult<Keyspace, SingleKeyspaceMetadataError>, MetadataError> {
let rows = query_filter_keyspace_name::<(String, HashMap<String, String>)>(
conn,
"select keyspace_name, replication from system_schema.keyspaces",
keyspaces_to_fetch,
)
.map_err(|error| MetadataFetchError {
error,
table: "system_schema.keyspaces",
});
let (mut all_tables, mut all_views, mut all_user_defined_types) = if fetch_schema {
let udts = query_user_defined_types(conn, keyspaces_to_fetch).await?;
let mut tables_schema = query_tables_schema(conn, keyspaces_to_fetch, &udts).await?;
(
// We pass the mutable reference to the same map to the both functions.
// First function fetches `system_schema.tables`, and removes found
// table from `tables_schema`.
// Second does the same for `system_schema.views`.
// The assumption here is that no keys (table names) can appear in both
// of those schema table.
// As far as we know this assumption is true for Scylla and Cassandra.
query_tables(conn, keyspaces_to_fetch, &mut tables_schema).await?,
query_views(conn, keyspaces_to_fetch, &mut tables_schema).await?,
udts,
)
} else {
(HashMap::new(), HashMap::new(), HashMap::new())
};
rows.map(|row_result| {
let (keyspace_name, strategy_map) = row_result?;
let strategy: Strategy = strategy_from_string_map(strategy_map).map_err(|error| {
KeyspacesMetadataError::Strategy {
keyspace: keyspace_name.clone(),
error,
}
})?;
let tables = all_tables
.remove(&keyspace_name)
.unwrap_or_else(|| Ok(HashMap::new()));
let views = all_views
.remove(&keyspace_name)
.unwrap_or_else(|| Ok(HashMap::new()));
let user_defined_types = all_user_defined_types
.remove(&keyspace_name)
.unwrap_or_else(|| Ok(HashMap::new()));
// As you can notice, in this file we generally operate on two layers of errors:
// - Outer (MetadataError) if something went wrong with querying the cluster.
// - Inner (SingleKeyspaceMetadataError) if the fetched metadata turned out to not be fully consistent.
// If there is an inner error, we want to drop metadata for the whole keyspace.
// This logic checks if either tables, views, or UDTs have such inner error, and returns it if so.
// Notice that in the error branch, return value is wrapped in `Ok` - but this is the
// outer error, so it just means there was no error while querying the cluster.
let (tables, views, user_defined_types) = match (tables, views, user_defined_types) {
(Ok(t), Ok(v), Ok(u)) => (t, v, u),
(Err(e), _, _) | (_, Err(e), _) => return Ok((keyspace_name, Err(e))),
(_, _, Err(e)) => {
return Ok((
keyspace_name,
Err(SingleKeyspaceMetadataError::MissingUDT(e)),
))
}
};
let keyspace = Keyspace {
strategy,
tables,
views,
user_defined_types,
};