forked from shotover/shotover-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
4133 lines (3878 loc) · 186 KB
/
mod.rs
File metadata and controls
4133 lines (3878 loc) · 186 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
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 crate::frame::kafka::{KafkaFrame, RequestBody, ResponseBody};
use crate::frame::{Frame, MessageType};
use crate::message::{Message, Messages};
use crate::tls::{TlsConnector, TlsConnectorConfig};
use crate::transforms::kafka::sink_cluster::shotover_node::start_shotover_peers_check;
use crate::transforms::{
ChainState, DownChainProtocol, Transform, TransformBuilder, TransformContextBuilder,
UpChainProtocol,
};
use crate::transforms::{TransformConfig, TransformContextConfig};
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
use connections::{Connections, Destination};
use dashmap::DashMap;
use kafka_node::{ConnectionFactory, KafkaAddress, KafkaNode, KafkaNodeState};
use kafka_protocol::ResponseError;
use kafka_protocol::messages::add_partitions_to_txn_request::AddPartitionsToTxnTransaction;
use kafka_protocol::messages::delete_records_request::DeleteRecordsTopic;
use kafka_protocol::messages::delete_records_response::DeleteRecordsTopicResult;
use kafka_protocol::messages::describe_cluster_response::DescribeClusterBroker;
use kafka_protocol::messages::describe_producers_request::TopicRequest;
use kafka_protocol::messages::describe_producers_response::TopicResponse;
use kafka_protocol::messages::fetch_request::FetchTopic;
use kafka_protocol::messages::fetch_response::LeaderIdAndEpoch as FetchResponseLeaderIdAndEpoch;
use kafka_protocol::messages::list_offsets_request::ListOffsetsTopic;
use kafka_protocol::messages::metadata_request::MetadataRequestTopic;
use kafka_protocol::messages::metadata_response::MetadataResponseBroker;
use kafka_protocol::messages::offset_fetch_request::OffsetFetchRequestGroup;
use kafka_protocol::messages::offset_for_leader_epoch_request::OffsetForLeaderTopic;
use kafka_protocol::messages::produce_request::TopicProduceData;
use kafka_protocol::messages::produce_response::{
LeaderIdAndEpoch as ProduceResponseLeaderIdAndEpoch, TopicProduceResponse,
};
use kafka_protocol::messages::{
AddOffsetsToTxnRequest, AddPartitionsToTxnRequest, AddPartitionsToTxnResponse, ApiKey,
BrokerId, ConsumerGroupDescribeRequest, ConsumerGroupDescribeResponse,
ConsumerGroupHeartbeatRequest, DeleteGroupsRequest, DeleteGroupsResponse, DeleteRecordsRequest,
DeleteRecordsResponse, DescribeClusterResponse, DescribeGroupsRequest, DescribeGroupsResponse,
DescribeLogDirsResponse, DescribeProducersRequest, DescribeProducersResponse,
DescribeTransactionsRequest, DescribeTransactionsResponse, EndTxnRequest, FetchRequest,
FetchResponse, FindCoordinatorRequest, FindCoordinatorResponse, GroupId, HeartbeatRequest,
InitProducerIdRequest, JoinGroupRequest, LeaveGroupRequest, ListGroupsResponse,
ListOffsetsRequest, ListOffsetsResponse, ListTransactionsResponse, MetadataRequest,
MetadataResponse, OffsetFetchRequest, OffsetFetchResponse, OffsetForLeaderEpochRequest,
OffsetForLeaderEpochResponse, ProduceRequest, ProduceResponse, RequestHeader,
SaslAuthenticateRequest, SaslAuthenticateResponse, SaslHandshakeRequest, SyncGroupRequest,
TopicName, TransactionalId, TxnOffsetCommitRequest,
};
use kafka_protocol::protocol::StrBytes;
use metrics::{Counter, counter};
use rand::SeedableRng;
use rand::rngs::SmallRng;
use rand::seq::{IndexedRandom, IteratorRandom};
use scram_over_mtls::{
AuthorizeScramOverMtls, AuthorizeScramOverMtlsBuilder, AuthorizeScramOverMtlsConfig,
OriginalScramState,
};
use serde::{Deserialize, Serialize};
use shotover_node::{ShotoverNode, ShotoverNodeConfig};
use split::{
AddPartitionsToTxnRequestSplitAndRouter, ConsumerGroupDescribeSplitAndRouter,
DeleteGroupsSplitAndRouter, DeleteRecordsRequestSplitAndRouter, DescribeGroupsSplitAndRouter,
DescribeLogDirsSplitAndRouter, DescribeProducersRequestSplitAndRouter,
DescribeTransactionsSplitAndRouter, ListGroupsSplitAndRouter, ListOffsetsRequestSplitAndRouter,
ListTransactionsSplitAndRouter, OffsetFetchSplitAndRouter,
OffsetForLeaderEpochRequestSplitAndRouter, ProduceRequestSplitAndRouter, RequestSplitAndRouter,
};
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hasher;
use std::sync::Arc;
use std::sync::atomic::AtomicI64;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use uuid::Uuid;
mod api_versions;
mod connections;
mod kafka_node;
mod scram_over_mtls;
pub mod shotover_node;
pub(crate) mod split;
const SASL_SCRAM_MECHANISMS: [&str; 2] = ["SCRAM-SHA-256", "SCRAM-SHA-512"];
#[derive(thiserror::Error, Debug)]
enum FindCoordinatorError {
#[error("Coordinator not available")]
CoordinatorNotAvailable,
#[error("{0:?}")]
Unrecoverable(#[from] anyhow::Error),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct KafkaSinkClusterConfig {
pub first_contact_points: Vec<String>,
pub shotover_nodes: Vec<ShotoverNodeConfig>,
pub local_shotover_broker_id: i32,
pub connect_timeout_ms: u64,
pub read_timeout: Option<u64>,
pub check_shotover_peers_delay_ms: Option<u64>,
pub tls: Option<TlsConnectorConfig>,
pub authorize_scram_over_mtls: Option<AuthorizeScramOverMtlsConfig>,
}
const NAME: &str = "KafkaSinkCluster";
#[typetag::serde(name = "KafkaSinkCluster")]
#[async_trait(?Send)]
impl TransformConfig for KafkaSinkClusterConfig {
async fn get_builder(
&self,
transform_context: TransformContextConfig,
) -> Result<Box<dyn TransformBuilder>> {
let tls = self.tls.as_ref().map(TlsConnector::new).transpose()?;
let shotover_nodes: Result<Vec<_>> = self
.shotover_nodes
.iter()
.cloned()
.map(ShotoverNodeConfig::build)
.collect();
let mut shotover_nodes = shotover_nodes?;
// All shotover nodes should have unique broker ids
let mut unique_broker_ids = HashSet::new();
for node in &shotover_nodes {
if !unique_broker_ids.insert(node.broker_id) {
return Err(anyhow::anyhow!(
"Duplicate broker_id found in shotover node {}",
node.address_for_clients
));
}
}
let rack = shotover_nodes
.iter()
.find(|x| x.broker_id.0 == self.local_shotover_broker_id)
.map(|x| x.rack.clone())
.ok_or_else(|| {
anyhow!(
"local_shotover_broker_id {} was missing in shotover_nodes",
self.local_shotover_broker_id
)
})?;
shotover_nodes.sort_by_key(|x| x.broker_id);
let first_contact_points: Result<Vec<_>> = self
.first_contact_points
.iter()
.map(|x| KafkaAddress::from_str(x))
.collect();
Ok(Box::new(KafkaSinkClusterBuilder::new(
transform_context.chain_name,
first_contact_points?,
&self.authorize_scram_over_mtls,
shotover_nodes,
self.local_shotover_broker_id,
rack,
self.connect_timeout_ms,
self.read_timeout,
self.check_shotover_peers_delay_ms,
tls,
)?))
}
fn up_chain_protocol(&self) -> UpChainProtocol {
UpChainProtocol::MustBeOneOf(vec![MessageType::Kafka])
}
fn down_chain_protocol(&self) -> DownChainProtocol {
DownChainProtocol::Terminating
}
}
struct KafkaSinkClusterBuilder {
// contains address and port
first_contact_points: Vec<KafkaAddress>,
shotover_nodes: Vec<ShotoverNode>,
rack: StrBytes,
broker_id: BrokerId,
connect_timeout: Duration,
read_timeout: Option<Duration>,
controller_broker: Arc<AtomicBrokerId>,
group_to_coordinator_broker: Arc<DashMap<GroupId, BrokerId>>,
transaction_to_coordinator_broker: Arc<DashMap<TransactionalId, BrokerId>>,
topic_by_name: Arc<DashMap<TopicName, Topic>>,
topic_by_id: Arc<DashMap<Uuid, Topic>>,
nodes_shared: Arc<RwLock<Vec<KafkaNode>>>,
authorize_scram_over_mtls: Option<AuthorizeScramOverMtlsBuilder>,
tls: Option<TlsConnector>,
out_of_rack_requests: Counter,
}
impl KafkaSinkClusterBuilder {
#[expect(clippy::too_many_arguments)]
pub fn new(
chain_name: String,
first_contact_points: Vec<KafkaAddress>,
authorize_scram_over_mtls: &Option<AuthorizeScramOverMtlsConfig>,
shotover_nodes: Vec<ShotoverNode>,
local_shotover_broker_id: i32,
rack: StrBytes,
connect_timeout_ms: u64,
timeout: Option<u64>,
check_shotover_peers_delay_ms: Option<u64>,
tls: Option<TlsConnector>,
) -> Result<KafkaSinkClusterBuilder> {
let read_timeout = timeout.map(Duration::from_secs);
let connect_timeout = Duration::from_millis(connect_timeout_ms);
let shotover_peers = shotover_nodes
.iter()
.filter(|x| x.broker_id.0 != local_shotover_broker_id)
.cloned()
.collect();
if let Some(check_shotover_peers_delay_ms) = check_shotover_peers_delay_ms {
start_shotover_peers_check(
shotover_peers,
check_shotover_peers_delay_ms,
connect_timeout,
&chain_name,
);
}
Ok(KafkaSinkClusterBuilder {
first_contact_points,
authorize_scram_over_mtls: authorize_scram_over_mtls
.as_ref()
.map(|x| x.get_builder(connect_timeout, read_timeout, &chain_name))
.transpose()?,
shotover_nodes,
broker_id: BrokerId(local_shotover_broker_id),
rack,
connect_timeout,
read_timeout,
controller_broker: Arc::new(AtomicBrokerId::new()),
group_to_coordinator_broker: Arc::new(DashMap::new()),
transaction_to_coordinator_broker: Arc::new(DashMap::new()),
topic_by_name: Arc::new(DashMap::new()),
topic_by_id: Arc::new(DashMap::new()),
nodes_shared: Arc::new(RwLock::new(vec![])),
out_of_rack_requests: counter!("shotover_out_of_rack_requests_count", "chain" => chain_name, "transform" => NAME),
tls,
})
}
}
impl TransformBuilder for KafkaSinkClusterBuilder {
fn build(&self, transform_context: TransformContextBuilder) -> Box<dyn Transform> {
Box::new(KafkaSinkCluster {
connections: Connections::new(self.out_of_rack_requests.clone()),
first_contact_points: self.first_contact_points.clone(),
shotover_nodes: self.shotover_nodes.clone(),
rack: self.rack.clone(),
broker_id: self.broker_id,
nodes: vec![],
nodes_shared: self.nodes_shared.clone(),
controller_broker: self.controller_broker.clone(),
group_to_coordinator_broker: self.group_to_coordinator_broker.clone(),
transaction_to_coordinator_broker: self.transaction_to_coordinator_broker.clone(),
topic_by_name: self.topic_by_name.clone(),
topic_by_id: self.topic_by_id.clone(),
rng: SmallRng::from_rng(&mut rand::rng()),
auth_complete: false,
connection_factory: ConnectionFactory::new(
self.tls.clone(),
self.connect_timeout,
self.read_timeout,
transform_context.force_run_chain,
),
pending_requests: Default::default(),
temp_responses_buffer: Default::default(),
sasl_mechanism: None,
authorize_scram_over_mtls: self.authorize_scram_over_mtls.as_ref().map(|x| x.build()),
refetch_backoff: Duration::from_millis(1),
})
}
fn get_name(&self) -> &'static str {
NAME
}
fn is_terminating(&self) -> bool {
true
}
}
struct AtomicBrokerId(AtomicI64);
impl AtomicBrokerId {
fn new() -> Self {
AtomicBrokerId(i64::MAX.into())
}
fn set(&self, value: BrokerId) {
if value != -1 {
self.0
.store(value.0.into(), std::sync::atomic::Ordering::Relaxed)
}
}
fn clear(&self) {
self.0.store(i64::MAX, std::sync::atomic::Ordering::Relaxed)
}
/// Returns `None` when set has never been called.
/// Otherwise returns `Some` containing the latest set value.
fn get(&self) -> Option<BrokerId> {
match self.0.load(std::sync::atomic::Ordering::Relaxed) {
i64::MAX => None,
other => Some(BrokerId(other as i32)),
}
}
}
pub(crate) struct KafkaSinkCluster {
first_contact_points: Vec<KafkaAddress>,
shotover_nodes: Vec<ShotoverNode>,
rack: StrBytes,
broker_id: BrokerId,
nodes: Vec<KafkaNode>,
nodes_shared: Arc<RwLock<Vec<KafkaNode>>>,
controller_broker: Arc<AtomicBrokerId>,
group_to_coordinator_broker: Arc<DashMap<GroupId, BrokerId>>,
transaction_to_coordinator_broker: Arc<DashMap<TransactionalId, BrokerId>>,
topic_by_name: Arc<DashMap<TopicName, Topic>>,
topic_by_id: Arc<DashMap<Uuid, Topic>>,
rng: SmallRng,
auth_complete: bool,
connection_factory: ConnectionFactory,
/// Maintains the state of each request/response pair.
/// Ordering must be maintained to ensure responses match up with their request.
pending_requests: VecDeque<PendingRequest>,
/// A temporary buffer used when receiving responses, only held onto in order to avoid reallocating.
temp_responses_buffer: Vec<Message>,
sasl_mechanism: Option<String>,
authorize_scram_over_mtls: Option<AuthorizeScramOverMtls>,
connections: Connections,
refetch_backoff: Duration,
}
/// State of a Request/Response is maintained by this enum.
/// The state progresses from Routed -> Sent -> Received
#[derive(Debug)]
enum PendingRequestState {
/// A route has been determined for this request but it has not yet been sent.
Routed { request: Message },
/// The request has been sent to the specified broker and we are now awaiting a response from that broker.
Sent {
/// How many responses must be received before this response is received.
/// When this is 0 the next response from the broker will be for this request.
/// This field must be manually decremented when another response for this broker comes through.
index: usize,
/// Some message types store the request here in case they need to resend it.
request: Option<Message>,
},
/// The broker has returned a Response to this request.
/// Returning this response may be delayed until a response to an earlier request comes back from another broker.
Received {
response: Message,
/// Some message types store the request here in case they need to resend it.
// TODO: if we ever turn the Message into a CoW type we will be able to
// simplify this a lot by just storing the request field once in PendingRequest
request: Option<Message>,
},
}
impl PendingRequestState {
fn routed(request: Message) -> Self {
Self::Routed { request }
}
}
#[derive(Debug, Clone)]
enum PendingRequestTy {
Fetch {
originally_sent_at: Instant,
max_wait_ms: i32,
min_bytes: i32,
},
FindCoordinator(FindCoordinator),
// Covers multiple request types: JoinGroup, DeleteGroups etc.
RoutedToGroup(GroupId),
// Covers multiple request types: InitProducerId, EndTxn etc.
RoutedToTransaction(TransactionalId),
Other,
}
struct PendingRequest {
state: PendingRequestState,
destination: Destination,
/// Type of the request sent
ty: PendingRequestTy,
/// Combine the next N responses into a single response
/// This message should be considered the base message and will retain the shotover Message::id and kafka correlation_id
combine_responses: usize,
}
#[async_trait]
impl Transform for KafkaSinkCluster {
fn get_name(&self) -> &'static str {
NAME
}
async fn transform<'shorter, 'longer: 'shorter>(
&mut self,
chain_state: &'shorter mut ChainState<'longer>,
) -> Result<Messages> {
if chain_state.requests.is_empty() {
// there are no requests, so no point sending any, but we should check for any responses without awaiting
self.recv_responses(&mut chain_state.close_client_connection)
.await
.context("Failed to receive responses (without sending requests)")
} else {
self.update_local_nodes().await;
self.route_requests(std::mem::take(&mut chain_state.requests))
.await
.context("Failed to route requests")?;
self.send_requests()
.await
.context("Failed to send requests")?;
self.recv_responses(&mut chain_state.close_client_connection)
.await
.context("Failed to receive responses")
}
}
}
impl KafkaSinkCluster {
/// Send a request over the control connection and immediately receive the response.
/// Since we always await the response we know for sure that the response will not get mixed up with any other incoming responses.
async fn control_send_receive(&mut self, request: Message) -> Result<Message> {
match self.control_send_receive_inner(request.clone()).await {
Ok(response) => Ok(response),
Err(err) => {
// first retry on the same connection in case it was a timeout
match self
.connections
.handle_connection_error(
&self.connection_factory,
&self.authorize_scram_over_mtls,
&self.sasl_mechanism,
&self.nodes,
Destination::ControlConnection,
err,
)
.await
{
// connection recreated succesfully, retry on the original node
// if the request fails at this point its a bad request.
Ok(()) => self.control_send_receive_inner(request).await,
// connection failed, could be a bad node, retry on all known nodes
Err(err) => {
tracing::warn!("Failed to recreate original control connection {err:?}");
loop {
// remove the old control connection to force control_send_receive_inner to create a new one.
self.connections
.connections
.remove(&Destination::ControlConnection);
match self.control_send_receive_inner(request.clone()).await {
// found a new node that works
Ok(response) => return Ok(response),
// this node also doesnt work, mark as bad and try a new one.
Err(err) => {
if self.nodes.iter().all(|x| !x.is_up()) {
return Err(err.context("Failed to recreate control connection, no more brokers to retry on. Last broker gave error"));
} else {
tracing::warn!(
"Failed to recreate control connection against a new broker {err:?}"
);
// try another node
}
}
}
}
}
}
}
}
}
async fn control_send_receive_inner(&mut self, request: Message) -> Result<Message> {
assert!(
self.auth_complete,
"control_send_receive cannot be called until auth is complete. Otherwise it would collide with the control connection being used for regular routing."
);
let connection = self
.connections
.get_or_open_connection(
&mut self.rng,
&self.connection_factory,
&self.authorize_scram_over_mtls,
&self.sasl_mechanism,
&self.nodes,
&self.first_contact_points,
&self.rack,
Instant::now(),
Destination::ControlConnection,
)
.await
.context("Failed to get control connection")?;
connection.send(vec![request])?;
Ok(connection.recv().await?.remove(0))
}
fn store_topic_names(&self, topics: &mut Vec<TopicName>, topic: TopicName) {
let cache_is_missing_or_outdated = match self.topic_by_name.get(&topic) {
Some(topic) => topic.partitions.iter().any(|partition| {
// refetch the metadata if the metadata believes that a partition is stored at a down node.
// The possible results are:
// * The node is actually up and the partition is there, the node will be marked as up once a request has been succesfully routed to it.
// * The node is actually down and the partition has moved, refetching the metadata will allow us to find the new destination.
// * The node is actually down and the partition has not yet moved, refetching the metadata will have us attempt to route to the down node.
// Shotover will close the connection and the client will retry the request.
self.nodes
.iter()
.find(|node| node.broker_id == *partition.leader_id)
.map(|node| !node.is_up())
.unwrap_or(false)
}),
None => true,
};
if cache_is_missing_or_outdated && !topics.contains(&topic) && !topic.is_empty() {
topics.push(topic);
}
}
fn store_topic_ids(&self, topics: &mut Vec<Uuid>, topic: Uuid) {
let cache_is_missing_or_outdated = match self.topic_by_id.get(&topic) {
Some(topic) => topic.partitions.iter().any(|partition| {
// refetch the metadata if the metadata believes that a partition is stored at a down node.
// The possible results are:
// * The node is actually up and the partition is there, the node will be marked as up once a request has been succesfully routed to it.
// * The node is actually down and the partition has moved, refetching the metadata will allow us to find the new destination.
// * The node is actually down and the partition has not yet moved, refetching the metadata will have us attempt to route to the down node.
// Shotover will close the connection and the client will retry the request.
self.nodes
.iter()
.find(|node| node.broker_id == *partition.leader_id)
.map(|node| !node.is_up())
.unwrap_or(false)
}),
None => true,
};
if cache_is_missing_or_outdated && !topics.contains(&topic) && !topic.is_nil() {
topics.push(topic);
}
}
fn store_group(&self, groups: &mut Vec<GroupId>, group_id: GroupId) {
let cache_is_missing_or_outdated = match self.group_to_coordinator_broker.get(&group_id) {
Some(broker_id) => self
.nodes
.iter()
.find(|node| node.broker_id == *broker_id)
.map(|node| !node.is_up())
.unwrap_or(true),
None => true,
};
if cache_is_missing_or_outdated && !groups.contains(&group_id) {
debug_assert!(group_id.0.as_str() != "");
groups.push(group_id);
}
}
fn store_transaction(
&self,
transactions: &mut Vec<TransactionalId>,
transaction: TransactionalId,
) {
let cache_is_missing_or_outdated =
match self.transaction_to_coordinator_broker.get(&transaction) {
Some(broker_id) => self
.nodes
.iter()
.find(|node| node.broker_id == *broker_id)
.map(|node| !node.is_up())
.unwrap_or(true),
None => true,
};
if cache_is_missing_or_outdated && !transactions.contains(&transaction) {
debug_assert!(transaction.0.as_str() != "");
transactions.push(transaction);
}
}
async fn update_local_nodes(&mut self) {
self.nodes.clone_from(&*self.nodes_shared.read().await);
}
async fn route_requests(&mut self, mut requests: Vec<Message>) -> Result<()> {
if !self.auth_complete {
let mut handshake_request_count = 0;
for request in &mut requests {
match request.frame() {
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::SaslHandshake(SaslHandshakeRequest { mechanism, .. }),
..
})) => {
mechanism.as_str();
self.sasl_mechanism = Some(mechanism.as_str().to_owned());
self.connection_factory.add_auth_request(request.clone());
handshake_request_count += 1;
}
Some(Frame::Kafka(KafkaFrame::Request {
body:
RequestBody::SaslAuthenticate(SaslAuthenticateRequest {
auth_bytes, ..
}),
..
})) => {
if let Some(scram_over_mtls) = &mut self.authorize_scram_over_mtls {
if let Some(username) = get_username_from_scram_request(auth_bytes) {
scram_over_mtls.set_username(username).await?;
}
}
self.connection_factory.add_auth_request(request.clone());
handshake_request_count += 1;
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::ApiVersions(_),
..
})) => {
handshake_request_count += 1;
}
_ => {
// The client is no longer performing authentication, so consider auth completed
if let Some(scram_over_mtls) = &self.authorize_scram_over_mtls {
// When performing SCRAM over mTLS, we need this security check to ensure that the
// client cannot access delegation tokens that it has not successfully authenticated for.
//
// If the client were to send a request directly after the SCRAM requests,
// without waiting for responses to those scram requests first,
// this error would be triggered even if the SCRAM requests were successful.
// However that would be a violation of the SCRAM protocol as the client is supposed to check
// the server's signature contained in the server's final message in order to authenticate the server.
// So I dont think this problem is worth solving.
if !matches!(
scram_over_mtls.original_scram_state,
OriginalScramState::AuthSuccess
) {
return Err(anyhow!(
"Client attempted to send requests before a successful auth was completed or after an unsuccessful auth"
));
}
}
self.auth_complete = true;
break;
}
}
}
// route all handshake messages
for _ in 0..handshake_request_count {
let request = requests.remove(0);
self.route_to_control_connection(request);
}
if requests.is_empty() {
// all messages received in this batch are handshake messages,
// so dont continue with regular message handling
return Ok(());
} else {
// the later messages in this batch are not handshake messages,
// so continue onto the regular message handling
}
}
let mut topic_names = vec![];
let mut topic_ids = vec![];
let mut groups = vec![];
let mut transactions = vec![];
for request in &mut requests {
match request.frame() {
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::Produce(produce),
..
})) => {
for topic_data in &produce.topic_data {
self.store_topic_names(&mut topic_names, topic_data.name.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::ListOffsets(list_offsets),
..
})) => {
for topic in &list_offsets.topics {
self.store_topic_names(&mut topic_names, topic.name.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::OffsetForLeaderEpoch(body),
..
})) => {
for topic in &body.topics {
self.store_topic_names(&mut topic_names, topic.topic.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DescribeProducers(body),
..
})) => {
for topic in &body.topics {
self.store_topic_names(&mut topic_names, topic.name.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DeleteRecords(body),
..
})) => {
for topic in &body.topics {
self.store_topic_names(&mut topic_names, topic.name.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::Fetch(fetch),
..
})) => {
for topic in &fetch.topics {
self.store_topic_names(&mut topic_names, topic.topic.clone());
self.store_topic_ids(&mut topic_ids, topic.topic_id);
}
fetch.session_id = 0;
fetch.session_epoch = -1;
request.invalidate_cache();
}
Some(Frame::Kafka(KafkaFrame::Request {
body:
RequestBody::Heartbeat(HeartbeatRequest { group_id, .. })
| RequestBody::ConsumerGroupHeartbeat(ConsumerGroupHeartbeatRequest {
group_id,
..
})
| RequestBody::SyncGroup(SyncGroupRequest { group_id, .. })
| RequestBody::JoinGroup(JoinGroupRequest { group_id, .. })
| RequestBody::LeaveGroup(LeaveGroupRequest { group_id, .. })
| RequestBody::TxnOffsetCommit(TxnOffsetCommitRequest { group_id, .. }),
..
})) => {
self.store_group(&mut groups, group_id.clone());
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::ConsumerGroupDescribe(describe),
..
})) => {
for group_id in &describe.group_ids {
self.store_group(&mut groups, group_id.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DeleteGroups(delete_groups),
..
})) => {
for group_id in &delete_groups.groups_names {
self.store_group(&mut groups, group_id.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::OffsetDelete(offset_delete),
..
})) => {
self.store_group(&mut groups, offset_delete.group_id.clone());
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DescribeGroups(offset_delete),
..
})) => {
for group_id in &offset_delete.groups {
self.store_group(&mut groups, group_id.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body:
RequestBody::InitProducerId(InitProducerIdRequest {
transactional_id: Some(transactional_id),
..
})
| RequestBody::EndTxn(EndTxnRequest {
transactional_id, ..
})
| RequestBody::AddOffsetsToTxn(AddOffsetsToTxnRequest {
transactional_id, ..
}),
..
})) => {
self.store_transaction(&mut transactions, transactional_id.clone());
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DescribeTransactions(describe_transaction),
..
})) => {
for transactional_id in &describe_transaction.transactional_ids {
self.store_transaction(&mut transactions, transactional_id.clone());
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::AddPartitionsToTxn(add_partitions_to_txn_request),
header,
})) => {
if header.request_api_version <= 3 {
self.store_transaction(
&mut transactions,
add_partitions_to_txn_request
.v3_and_below_transactional_id
.clone(),
);
} else {
for transaction in &add_partitions_to_txn_request.transactions {
self.store_transaction(
&mut transactions,
transaction.transactional_id.clone(),
);
}
}
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::OffsetFetch(offset_fetch),
header,
})) => {
if header.request_api_version <= 7 {
self.store_group(&mut groups, offset_fetch.group_id.clone());
} else {
for group in &offset_fetch.groups {
self.store_group(&mut groups, group.group_id.clone());
}
}
}
_ => {}
}
}
for group in groups {
match self
.find_coordinator(CoordinatorKey::Group(group.clone()))
.await
{
Ok(node) => {
tracing::debug!(
"Storing group_to_coordinator_broker metadata, group {group:?} -> broker {:?}",
node.broker_id
);
self.group_to_coordinator_broker
.insert(group, node.broker_id);
self.add_node_if_new(node).await;
}
Err(FindCoordinatorError::CoordinatorNotAvailable) => {
// We cant find the coordinator so do nothing so that the request will be routed to a random node:
// * If it happens to be the coordinator all is well
// * If its not the coordinator then it will return a NOT_COORDINATOR message to
// the client prompting it to retry the whole process again.
}
Err(FindCoordinatorError::Unrecoverable(err)) => Err(err)?,
}
}
for transaction in transactions {
match self
.find_coordinator(CoordinatorKey::Transaction(transaction.clone()))
.await
{
Ok(node) => {
tracing::debug!(
"Storing transaction_to_coordinator_broker metadata, transaction {transaction:?} -> broker {:?}",
node.broker_id
);
self.transaction_to_coordinator_broker
.insert(transaction, node.broker_id);
self.add_node_if_new(node).await;
}
Err(FindCoordinatorError::CoordinatorNotAvailable) => {
// We cant find the coordinator so do nothing so that the request will be routed to a random node:
// * If it happens to be the coordinator all is well
// * If its not the coordinator then it will return a NOT_COORDINATOR message to
// the client prompting it to retry the whole process again.
}
Err(FindCoordinatorError::Unrecoverable(err)) => Err(err)?,
}
}
// request and process metadata if we are missing topics or the controller broker id
if !topic_names.is_empty()
|| !topic_ids.is_empty()
|| self.controller_broker.get().is_none()
|| self.nodes.is_empty()
{
let mut metadata = self
.get_metadata_of_topics_with_retry(topic_names, topic_ids)
.await?;
match metadata.frame() {
Some(Frame::Kafka(KafkaFrame::Response {
body: ResponseBody::Metadata(metadata),
..
})) => {
for topic in &metadata.topics {
match ResponseError::try_from_code(topic.error_code) {
Some(ResponseError::UnknownTopicOrPartition) => {
// We need to look up all topics sent to us by the client
// but the client may request a topic that doesnt exist.
}
Some(err) => {
// Some other kind of error, better to terminate the connection
return Err(anyhow!(
"Kafka responded to Metadata request with error {err:?}"
));
}
None => {}
}
}
self.process_metadata_response(metadata).await
}
other => {
return Err(anyhow!(
"Unexpected response returned to metadata request {other:?}"
));
}
}
}
for mut request in requests {
// This routing is documented in transforms.md so make sure to update that when making changes here.
match request.frame() {
// split and route to partition leader
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::Produce(_),
..
})) => self.split_and_route_request::<ProduceRequestSplitAndRouter>(request)?,
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::Fetch(_),
..
})) => self.route_fetch_request(request)?,
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::ListOffsets(_),
..
})) => self.split_and_route_request::<ListOffsetsRequestSplitAndRouter>(request)?,
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::OffsetForLeaderEpoch(_),
..
})) => self.split_and_route_request::<OffsetForLeaderEpochRequestSplitAndRouter>(
request,
)?,
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DeleteRecords(_),
..
})) => {
self.split_and_route_request::<DeleteRecordsRequestSplitAndRouter>(request)?
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::DescribeProducers(_),
..
})) => {
self.split_and_route_request::<DescribeProducersRequestSplitAndRouter>(request)?
}
// route to group coordinator
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::Heartbeat(heartbeat),
..
})) => {
let group_id = heartbeat.group_id.clone();
self.route_to_group_coordinator(request, group_id);
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::ConsumerGroupHeartbeat(heartbeat),
..
})) => {
let group_id = heartbeat.group_id.clone();
self.route_to_group_coordinator(request, group_id);
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::SyncGroup(sync_group),
..
})) => {
let group_id = sync_group.group_id.clone();
self.route_to_group_coordinator(request, group_id);
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::OffsetFetch(offset_fetch),
header,
})) => {
if header.request_api_version <= 7 {
let group_id = offset_fetch.group_id.clone();
self.route_to_group_coordinator(request, group_id);
} else {
self.split_and_route_request::<OffsetFetchSplitAndRouter>(request)?;
};
}
Some(Frame::Kafka(KafkaFrame::Request {
body: RequestBody::OffsetCommit(offset_commit),
..
})) => {
let group_id = offset_commit.group_id.clone();
self.route_to_group_coordinator(request, group_id);