-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathload_balancer.rs
More file actions
278 lines (253 loc) · 9.97 KB
/
Copy pathload_balancer.rs
File metadata and controls
278 lines (253 loc) · 9.97 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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use dashmap::DashMap;
use std::{marker::PhantomData, sync::Arc, thread, time::Duration};
use tokio::{
sync::mpsc::{Receiver, Sender},
task::JoinHandle,
};
use crate::{
config::{LoadBalancingPolicy, SeparationMode, DEFAULT_CHANNEL_SIZE},
error::{NodeError, NodeResult},
executor::{
api::{ExecutionResults, Executor, PrimaryToProxyMessage, RemoraTransaction, Store},
versioned_dependency_controller::VersionedDependencyController,
},
metrics::Metrics,
primary::{
owned_obj_txn_forwarder::OwnedObjTxnForwarder,
shared_obj_txn_forwarder::{
PreConsensusSchedTask, PreConsensusSchedulingPolicy, SharedObjTxnForwarder,
StatelessTxnForwarder, VersionAssignmentTask,
},
},
proxy::core::ProxyId,
};
use sui_types::digests::TransactionDigest;
/// A load balancer is responsible for distributing transactions to proxies.
pub struct LoadBalancer<E: Executor> {
/// The executor trait
_phantom: PhantomData<E>,
/// The proxy connections.
proxy_connections:
Arc<DashMap<ProxyId, Sender<PrimaryToProxyMessage<<E as Executor>::Transaction>>>>,
/// The receiver for committed transactions
rx_committed_txns: Receiver<Vec<RemoraTransaction<E>>>,
/// The load balancing policy.
policy: PreConsensusSchedulingPolicy,
/// The proxy mode.
separation_mode: SeparationMode,
/// The metrics for the validator.
metrics: Arc<Metrics>,
}
impl<E: Executor + Send + Sync + 'static> LoadBalancer<E>
where
<E as Executor>::Transaction: Send + Sync + 'static,
{
/// Create a new load balancer.
pub fn new(
proxy_connections: Arc<
DashMap<ProxyId, Sender<PrimaryToProxyMessage<<E as Executor>::Transaction>>>,
>,
rx_committed_txns: Receiver<Vec<RemoraTransaction<E>>>,
policy: PreConsensusSchedulingPolicy,
separation_mode: SeparationMode,
metrics: Arc<Metrics>,
) -> Self {
Self {
_phantom: PhantomData,
proxy_connections,
rx_committed_txns,
policy,
separation_mode,
metrics,
}
}
/// Initialize transaction processors and return the senders
fn initialize_processors(
&self,
rx_pre_consensus_txns: Receiver<Vec<RemoraTransaction<E>>>,
rx_stateless_txns: Receiver<(TransactionDigest, Duration)>,
) -> (
Sender<Vec<RemoraTransaction<E>>>, // owned_txn_sender
Sender<Vec<RemoraTransaction<E>>>, // shared_txn_sender
) {
// Create channels for transactions
let (owned_txn_sender, owned_txn_receiver) =
tokio::sync::mpsc::channel(DEFAULT_CHANNEL_SIZE);
let (shared_txn_sender, shared_txn_receiver) =
tokio::sync::mpsc::channel(DEFAULT_CHANNEL_SIZE);
let (version_assignment_sender, version_assignment_receiver) =
tokio::sync::mpsc::channel(DEFAULT_CHANNEL_SIZE);
// Initialize the OwnedTxnProcessor
let mut owned_txn_processor = OwnedObjTxnForwarder::<E> {
proxy_connections: self.proxy_connections.clone(),
policy: LoadBalancingPolicy::RoundRobin,
index: 0,
};
let mut version_assignment_processor = VersionAssignmentTask::<E> {
shared_object_versions: rustc_hash::FxHashMap::default(),
_phantom: PhantomData,
};
version_assignment_processor
.shared_object_versions
.reserve(10000000);
let proxy_loads = Arc::new(DashMap::new());
let stateless_forwarding_table = Arc::new(DashMap::new());
let pre_consensus_routing_plan = Arc::new(DashMap::new());
// Initialize the SharedTxnProcessor
let mut shared_txn_processor = SharedObjTxnForwarder::<E>::new(
Arc::new(VersionedDependencyController::new()),
self.proxy_connections.clone(),
pre_consensus_routing_plan.clone(),
self.metrics.clone(),
Arc::new(DashMap::with_capacity(10000000)),
stateless_forwarding_table.clone(),
self.separation_mode,
self.policy.clone(),
proxy_loads.clone(),
);
let mut pre_consensus_sched_processor = PreConsensusSchedTask::<E>::new(
self.proxy_connections.clone(),
pre_consensus_routing_plan.clone(),
proxy_loads.clone(),
);
thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
owned_txn_processor
.process_owned_txns(owned_txn_receiver)
.await;
});
});
thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
version_assignment_processor
.process_version_assignments(shared_txn_receiver, version_assignment_sender)
.await;
});
});
// TODO: use more worker threads when not in primary separation mode
thread::spawn(move || {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(num_cpus::get())
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
shared_txn_processor
.process_shared_txns(version_assignment_receiver)
.await;
});
});
thread::spawn(move || {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
pre_consensus_sched_processor
.process_pre_consensus_txns(rx_pre_consensus_txns)
.await;
});
});
if self.separation_mode == SeparationMode::PrimaryPreSeparation {
let mut stateless_txn_processor = StatelessTxnForwarder::<E>::new(
self.proxy_connections.clone(),
proxy_loads.clone(),
stateless_forwarding_table.clone(),
);
thread::spawn(move || {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(8)
.enable_all()
.build()
.unwrap();
rt.block_on(async move {
stateless_txn_processor
.forward_stateless_txn(rx_stateless_txns)
.await;
});
});
}
// Return the senders so they can be used in the run loop
(owned_txn_sender, shared_txn_sender)
}
/// Run the load balancer.
pub async fn run(
&mut self,
rx_pre_consensus_txns: Receiver<Vec<RemoraTransaction<E>>>,
rx_stateless_txns: Receiver<(TransactionDigest, Duration)>,
) -> NodeResult<()> {
tracing::info!("Load balancer started");
// Initialize processors and get the transaction senders
let (owned_txn_sender, shared_txn_sender) =
self.initialize_processors(rx_pre_consensus_txns, rx_stateless_txns);
let mut txn_cnt = 0;
loop {
tokio::select! {
Some(transactions) = self.rx_committed_txns.recv() => {
txn_cnt += 1;
if txn_cnt == 1 {
self.metrics.register_start_time();
}
// Separate transactions into owned-only and shared-object transactions
let mut owned_txns = Vec::new();
let mut shared_txns = Vec::new();
for transaction in transactions {
self.metrics.update_metrics(transaction.timestamp(), "lb-ingress");
let shared_object_ids = transaction.shared_objects();
if shared_object_ids.is_empty() {
owned_txns.push(transaction);
} else {
shared_txns.push(transaction);
}
}
// Send owned-only transactions to the dedicated task
if !owned_txns.is_empty() {
if let Err(e) = owned_txn_sender.send(owned_txns).await {
tracing::error!("Failed to send owned transactions: {:?}", e);
}
}
// Send shared-object transactions to the dedicated task
if !shared_txns.is_empty() {
if let Err(e) = shared_txn_sender.send(shared_txns).await {
tracing::error!("Failed to send shared transactions: {:?}", e);
}
}
}
else => Err(NodeError::ShuttingDown)?,
}
}
}
/// Spawn the load balancer in a new task.
pub fn spawn(
mut self,
rx_pre_consensus_txns: Receiver<Vec<RemoraTransaction<E>>>,
rx_stateless_txns: Receiver<(TransactionDigest, Duration)>,
) -> JoinHandle<NodeResult<()>>
where
E: Send + 'static,
Store<E>: Send + Sync,
RemoraTransaction<E>: Send + Sync,
ExecutionResults<E>: Send,
<E as Executor>::Transaction: Send + Sync,
{
tokio::task::spawn_blocking(move || {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.enable_all()
.build()
.unwrap();
rt.block_on(async move { self.run(rx_pre_consensus_txns, rx_stateless_txns).await })
})
}
}