Line data Source code
1 : use std::{
2 : cell::{RefCell, RefMut, UnsafeCell},
3 : ffi::CStr,
4 : sync::Arc,
5 : };
6 :
7 : use bytes::Bytes;
8 : use desim::{
9 : executor::{self, PollSome},
10 : network::TCP,
11 : node_os::NodeOs,
12 : proto::{AnyMessage, NetEvent, NodeEvent},
13 : world::NodeId,
14 : };
15 : use tracing::debug;
16 : use utils::lsn::Lsn;
17 : use walproposer::{
18 : api_bindings::Level,
19 : bindings::{
20 : NeonWALReadResult, SafekeeperStateDesiredEvents, WL_SOCKET_READABLE, WL_SOCKET_WRITEABLE,
21 : },
22 : walproposer::{ApiImpl, Config},
23 : };
24 :
25 : use super::walproposer_disk::DiskWalProposer;
26 :
27 : /// Special state for each wp->sk connection.
28 : struct SafekeeperConn {
29 : host: String,
30 : port: String,
31 : node_id: NodeId,
32 : // socket is Some(..) equals to connection is established
33 : socket: Option<TCP>,
34 : // connection is in progress
35 : is_connecting: bool,
36 : // START_WAL_PUSH is in progress
37 : is_start_wal_push: bool,
38 : // pointer to Safekeeper in walproposer for callbacks
39 : raw_ptr: *mut walproposer::bindings::Safekeeper,
40 : }
41 :
42 : impl SafekeeperConn {
43 27855 : pub fn new(host: String, port: String) -> Self {
44 27855 : // port number is the same as NodeId
45 27855 : let port_num = port.parse::<u32>().unwrap();
46 27855 : Self {
47 27855 : host,
48 27855 : port,
49 27855 : node_id: port_num,
50 27855 : socket: None,
51 27855 : is_connecting: false,
52 27855 : is_start_wal_push: false,
53 27855 : raw_ptr: std::ptr::null_mut(),
54 27855 : }
55 27855 : }
56 : }
57 :
58 : /// Simulation version of a postgres WaitEventSet. At pos 0 there is always
59 : /// a special NodeEvents channel, which is used as a latch.
60 : struct EventSet {
61 : os: NodeOs,
62 : // all pollable channels, 0 is always NodeEvent channel
63 : chans: Vec<Box<dyn PollSome>>,
64 : // 0 is always nullptr
65 : sk_ptrs: Vec<*mut walproposer::bindings::Safekeeper>,
66 : // event mask for each channel
67 : masks: Vec<u32>,
68 : }
69 :
70 : impl EventSet {
71 9285 : pub fn new(os: NodeOs) -> Self {
72 9285 : let node_events = os.node_events();
73 9285 : Self {
74 9285 : os,
75 9285 : chans: vec![Box::new(node_events)],
76 9285 : sk_ptrs: vec![std::ptr::null_mut()],
77 9285 : masks: vec![WL_SOCKET_READABLE],
78 9285 : }
79 9285 : }
80 :
81 : /// Leaves all readable channels at the beginning of the array.
82 27977 : fn sort_readable(&mut self) -> usize {
83 27977 : let mut cnt = 1;
84 67011 : for i in 1..self.chans.len() {
85 67011 : if self.masks[i] & WL_SOCKET_READABLE != 0 {
86 67011 : self.chans.swap(i, cnt);
87 67011 : self.sk_ptrs.swap(i, cnt);
88 67011 : self.masks.swap(i, cnt);
89 67011 : cnt += 1;
90 67011 : }
91 : }
92 27977 : cnt
93 27977 : }
94 :
95 67408 : fn update_event_set(&mut self, conn: &SafekeeperConn, event_mask: u32) {
96 67408 : let index = self
97 67408 : .sk_ptrs
98 67408 : .iter()
99 255320 : .position(|&ptr| ptr == conn.raw_ptr)
100 67408 : .expect("safekeeper should exist in event set");
101 67408 : self.masks[index] = event_mask;
102 67408 : }
103 :
104 61466 : fn add_safekeeper(&mut self, sk: &SafekeeperConn, event_mask: u32) {
105 148994 : for ptr in self.sk_ptrs.iter() {
106 148994 : assert!(*ptr != sk.raw_ptr);
107 : }
108 :
109 61466 : self.chans.push(Box::new(
110 61466 : sk.socket
111 61466 : .as_ref()
112 61466 : .expect("socket should not be closed")
113 61466 : .recv_chan(),
114 61466 : ));
115 61466 : self.sk_ptrs.push(sk.raw_ptr);
116 61466 : self.masks.push(event_mask);
117 61466 : }
118 :
119 38095 : fn remove_safekeeper(&mut self, sk: &SafekeeperConn) {
120 80811 : let index = self.sk_ptrs.iter().position(|&ptr| ptr == sk.raw_ptr);
121 38095 : if index.is_none() {
122 3 : debug!("remove_safekeeper: sk={:?} not found", sk.raw_ptr);
123 3 : return;
124 38092 : }
125 38092 : let index = index.unwrap();
126 38092 :
127 38092 : self.chans.remove(index);
128 38092 : self.sk_ptrs.remove(index);
129 38092 : self.masks.remove(index);
130 38092 :
131 38092 : // to simulate the actual behaviour
132 38092 : self.refresh_event_set();
133 38095 : }
134 :
135 : /// Updates all masks to match the result of a SafekeeperStateDesiredEvents.
136 44918 : fn refresh_event_set(&mut self) {
137 128511 : for (i, mask) in self.masks.iter_mut().enumerate() {
138 128511 : if i == 0 {
139 44918 : continue;
140 83593 : }
141 83593 :
142 83593 : let mut mask_sk: u32 = 0;
143 83593 : let mut mask_nwr: u32 = 0;
144 83593 : unsafe { SafekeeperStateDesiredEvents(self.sk_ptrs[i], &mut mask_sk, &mut mask_nwr) };
145 83593 :
146 83593 : if mask_sk != *mask {
147 0 : debug!(
148 0 : "refresh_event_set: sk={:?}, old_mask={:#b}, new_mask={:#b}",
149 0 : self.sk_ptrs[i], *mask, mask_sk
150 : );
151 0 : *mask = mask_sk;
152 83593 : }
153 : }
154 44918 : }
155 :
156 : /// Wait for events on all channels.
157 27977 : fn wait(&mut self, timeout_millis: i64) -> walproposer::walproposer::WaitResult {
158 : // all channels are always writeable
159 94988 : for (i, mask) in self.masks.iter().enumerate() {
160 94988 : if *mask & WL_SOCKET_WRITEABLE != 0 {
161 0 : return walproposer::walproposer::WaitResult::Network(
162 0 : self.sk_ptrs[i],
163 0 : WL_SOCKET_WRITEABLE,
164 0 : );
165 94988 : }
166 : }
167 :
168 27977 : let cnt = self.sort_readable();
169 27977 :
170 27977 : let slice = &self.chans[0..cnt];
171 27977 : match executor::epoll_chans(slice, timeout_millis) {
172 11625 : None => walproposer::walproposer::WaitResult::Timeout,
173 : Some(0) => {
174 521 : let msg = self.os.node_events().must_recv();
175 521 : match msg {
176 521 : NodeEvent::Internal(AnyMessage::Just32(0)) => {
177 521 : // got a notification about new WAL available
178 521 : }
179 0 : NodeEvent::Internal(_) => unreachable!(),
180 0 : NodeEvent::Accept(_) => unreachable!(),
181 : }
182 521 : walproposer::walproposer::WaitResult::Latch
183 : }
184 15831 : Some(index) => walproposer::walproposer::WaitResult::Network(
185 15831 : self.sk_ptrs[index],
186 15831 : WL_SOCKET_READABLE,
187 15831 : ),
188 : }
189 27977 : }
190 : }
191 :
192 : /// This struct handles all calls from walproposer into walproposer_api.
193 : pub struct SimulationApi {
194 : os: NodeOs,
195 : safekeepers: RefCell<Vec<SafekeeperConn>>,
196 : disk: Arc<DiskWalProposer>,
197 : redo_start_lsn: Option<Lsn>,
198 : last_logged_commit_lsn: u64,
199 : shmem: UnsafeCell<walproposer::bindings::WalproposerShmemState>,
200 : config: Config,
201 : event_set: RefCell<Option<EventSet>>,
202 : }
203 :
204 : pub struct Args {
205 : pub os: NodeOs,
206 : pub config: Config,
207 : pub disk: Arc<DiskWalProposer>,
208 : pub redo_start_lsn: Option<Lsn>,
209 : }
210 :
211 : impl SimulationApi {
212 9285 : pub fn new(args: Args) -> Self {
213 9285 : // initialize connection state for each safekeeper
214 9285 : let sk_conns = args
215 9285 : .config
216 9285 : .safekeepers_list
217 9285 : .iter()
218 27855 : .map(|s| {
219 27855 : SafekeeperConn::new(
220 27855 : s.split(':').next().unwrap().to_string(),
221 27855 : s.split(':').nth(1).unwrap().to_string(),
222 27855 : )
223 27855 : })
224 9285 : .collect::<Vec<_>>();
225 9285 :
226 9285 : Self {
227 9285 : os: args.os,
228 9285 : safekeepers: RefCell::new(sk_conns),
229 9285 : disk: args.disk,
230 9285 : redo_start_lsn: args.redo_start_lsn,
231 9285 : last_logged_commit_lsn: 0,
232 9285 : shmem: UnsafeCell::new(walproposer::api_bindings::empty_shmem()),
233 9285 : config: args.config,
234 9285 : event_set: RefCell::new(None),
235 9285 : }
236 9285 : }
237 :
238 : /// Get SafekeeperConn for the given Safekeeper.
239 300599 : fn get_conn(&self, sk: &mut walproposer::bindings::Safekeeper) -> RefMut<'_, SafekeeperConn> {
240 300599 : let sk_port = unsafe { CStr::from_ptr(sk.port).to_str().unwrap() };
241 300599 : let state = self.safekeepers.borrow_mut();
242 300599 : RefMut::map(state, |v| {
243 300599 : v.iter_mut()
244 599902 : .find(|conn| conn.port == sk_port)
245 300599 : .expect("safekeeper conn not found by port")
246 300599 : })
247 300599 : }
248 : }
249 :
250 : impl ApiImpl for SimulationApi {
251 321165 : fn get_current_timestamp(&self) -> i64 {
252 321165 : debug!("get_current_timestamp");
253 : // PG TimestampTZ is microseconds, but simulation unit is assumed to be
254 : // milliseconds, so add 10^3
255 321165 : self.os.now() as i64 * 1000
256 321165 : }
257 :
258 1062 : fn update_donor(&self, donor: &mut walproposer::bindings::Safekeeper, donor_lsn: u64) {
259 1062 : let mut shmem = unsafe { *self.get_shmem_state() };
260 1062 : shmem.propEpochStartLsn.value = donor_lsn;
261 1062 : shmem.donor_conninfo = donor.conninfo;
262 1062 : }
263 :
264 34036 : fn conn_status(
265 34036 : &self,
266 34036 : _: &mut walproposer::bindings::Safekeeper,
267 34036 : ) -> walproposer::bindings::WalProposerConnStatusType {
268 34036 : debug!("conn_status");
269 : // break the connection with a 10% chance
270 34036 : if self.os.random(100) < 10 {
271 3303 : walproposer::bindings::WalProposerConnStatusType_WP_CONNECTION_BAD
272 : } else {
273 30733 : walproposer::bindings::WalProposerConnStatusType_WP_CONNECTION_OK
274 : }
275 34036 : }
276 :
277 34036 : fn conn_connect_start(&self, sk: &mut walproposer::bindings::Safekeeper) {
278 34036 : debug!("conn_connect_start");
279 34036 : let mut conn = self.get_conn(sk);
280 34036 :
281 34036 : assert!(conn.socket.is_none());
282 34036 : let socket = self.os.open_tcp(conn.node_id);
283 34036 : conn.socket = Some(socket);
284 34036 : conn.raw_ptr = sk;
285 34036 : conn.is_connecting = true;
286 34036 : }
287 :
288 30733 : fn conn_connect_poll(
289 30733 : &self,
290 30733 : _: &mut walproposer::bindings::Safekeeper,
291 30733 : ) -> walproposer::bindings::WalProposerConnectPollStatusType {
292 30733 : debug!("conn_connect_poll");
293 : // TODO: break the connection here
294 30733 : walproposer::bindings::WalProposerConnectPollStatusType_WP_CONN_POLLING_OK
295 30733 : }
296 :
297 30733 : fn conn_send_query(&self, sk: &mut walproposer::bindings::Safekeeper, query: &str) -> bool {
298 30733 : debug!("conn_send_query: {}", query);
299 30733 : self.get_conn(sk).is_start_wal_push = true;
300 30733 : true
301 30733 : }
302 :
303 30733 : fn conn_get_query_result(
304 30733 : &self,
305 30733 : _: &mut walproposer::bindings::Safekeeper,
306 30733 : ) -> walproposer::bindings::WalProposerExecStatusType {
307 30733 : debug!("conn_get_query_result");
308 : // TODO: break the connection here
309 30733 : walproposer::bindings::WalProposerExecStatusType_WP_EXEC_SUCCESS_COPYBOTH
310 30733 : }
311 :
312 18134 : fn conn_async_read(
313 18134 : &self,
314 18134 : sk: &mut walproposer::bindings::Safekeeper,
315 18134 : vec: &mut Vec<u8>,
316 18134 : ) -> walproposer::bindings::PGAsyncReadResult {
317 18134 : debug!("conn_async_read");
318 18134 : let mut conn = self.get_conn(sk);
319 :
320 18134 : let socket = if let Some(socket) = conn.socket.as_mut() {
321 18134 : socket
322 : } else {
323 : // socket is already closed
324 0 : return walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_FAIL;
325 : };
326 :
327 18134 : let msg = socket.recv_chan().try_recv();
328 :
329 15743 : match msg {
330 : None => {
331 : // no message is ready
332 2391 : walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_TRY_AGAIN
333 : }
334 : Some(NetEvent::Closed) => {
335 : // connection is closed
336 7151 : debug!("conn_async_read: connection is closed");
337 7151 : conn.socket = None;
338 7151 : walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_FAIL
339 : }
340 8592 : Some(NetEvent::Message(msg)) => {
341 : // got a message
342 8592 : let b = match msg {
343 8592 : desim::proto::AnyMessage::Bytes(b) => b,
344 0 : _ => unreachable!(),
345 : };
346 8592 : vec.extend_from_slice(&b);
347 8592 : walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_SUCCESS
348 : }
349 : }
350 18134 : }
351 :
352 34236 : fn conn_blocking_write(&self, sk: &mut walproposer::bindings::Safekeeper, buf: &[u8]) -> bool {
353 34236 : let mut conn = self.get_conn(sk);
354 34236 : debug!("conn_blocking_write to {}: {:?}", conn.node_id, buf);
355 34236 : let socket = conn.socket.as_mut().unwrap();
356 34236 : socket.send(desim::proto::AnyMessage::Bytes(Bytes::copy_from_slice(buf)));
357 34236 : true
358 34236 : }
359 :
360 5538 : fn conn_async_write(
361 5538 : &self,
362 5538 : sk: &mut walproposer::bindings::Safekeeper,
363 5538 : buf: &[u8],
364 5538 : ) -> walproposer::bindings::PGAsyncWriteResult {
365 5538 : let mut conn = self.get_conn(sk);
366 5538 : debug!("conn_async_write to {}: {:?}", conn.node_id, buf);
367 5538 : if let Some(socket) = conn.socket.as_mut() {
368 5538 : socket.send(desim::proto::AnyMessage::Bytes(Bytes::copy_from_slice(buf)));
369 5538 : } else {
370 : // connection is already closed
371 0 : debug!("conn_async_write: writing to a closed socket!");
372 : // TODO: maybe we should return error here?
373 : }
374 5538 : walproposer::bindings::PGAsyncWriteResult_PG_ASYNC_WRITE_SUCCESS
375 5538 : }
376 :
377 1103 : fn wal_reader_allocate(&self, _: &mut walproposer::bindings::Safekeeper) -> NeonWALReadResult {
378 1103 : debug!("wal_reader_allocate");
379 1103 : walproposer::bindings::NeonWALReadResult_NEON_WALREAD_SUCCESS
380 1103 : }
381 :
382 982 : fn wal_read(
383 982 : &self,
384 982 : _sk: &mut walproposer::bindings::Safekeeper,
385 982 : buf: &mut [u8],
386 982 : startpos: u64,
387 982 : ) -> NeonWALReadResult {
388 982 : self.disk.lock().read(startpos, buf);
389 982 : walproposer::bindings::NeonWALReadResult_NEON_WALREAD_SUCCESS
390 982 : }
391 :
392 9285 : fn init_event_set(&self, _: &mut walproposer::bindings::WalProposer) {
393 9285 : debug!("init_event_set");
394 9285 : let new_event_set = EventSet::new(self.os.clone());
395 9285 : let old_event_set = self.event_set.replace(Some(new_event_set));
396 9285 : assert!(old_event_set.is_none());
397 9285 : }
398 :
399 67408 : fn update_event_set(&self, sk: &mut walproposer::bindings::Safekeeper, event_mask: u32) {
400 67408 : debug!(
401 0 : "update_event_set, sk={:?}, events_mask={:#b}",
402 0 : sk as *mut walproposer::bindings::Safekeeper, event_mask
403 : );
404 67408 : let conn = self.get_conn(sk);
405 67408 :
406 67408 : self.event_set
407 67408 : .borrow_mut()
408 67408 : .as_mut()
409 67408 : .unwrap()
410 67408 : .update_event_set(&conn, event_mask);
411 67408 : }
412 :
413 61466 : fn add_safekeeper_event_set(
414 61466 : &self,
415 61466 : sk: &mut walproposer::bindings::Safekeeper,
416 61466 : event_mask: u32,
417 61466 : ) {
418 61466 : debug!(
419 0 : "add_safekeeper_event_set, sk={:?}, events_mask={:#b}",
420 0 : sk as *mut walproposer::bindings::Safekeeper, event_mask
421 : );
422 :
423 61466 : self.event_set
424 61466 : .borrow_mut()
425 61466 : .as_mut()
426 61466 : .unwrap()
427 61466 : .add_safekeeper(&self.get_conn(sk), event_mask);
428 61466 : }
429 :
430 38095 : fn rm_safekeeper_event_set(&self, sk: &mut walproposer::bindings::Safekeeper) {
431 38095 : debug!(
432 0 : "rm_safekeeper_event_set, sk={:?}",
433 0 : sk as *mut walproposer::bindings::Safekeeper,
434 : );
435 :
436 38095 : self.event_set
437 38095 : .borrow_mut()
438 38095 : .as_mut()
439 38095 : .unwrap()
440 38095 : .remove_safekeeper(&self.get_conn(sk));
441 38095 : }
442 :
443 6826 : fn active_state_update_event_set(&self, sk: &mut walproposer::bindings::Safekeeper) {
444 6826 : debug!("active_state_update_event_set");
445 :
446 6826 : assert!(sk.state == walproposer::bindings::SafekeeperState_SS_ACTIVE);
447 6826 : self.event_set
448 6826 : .borrow_mut()
449 6826 : .as_mut()
450 6826 : .unwrap()
451 6826 : .refresh_event_set();
452 6826 : }
453 :
454 19139 : fn wal_reader_events(&self, _sk: &mut walproposer::bindings::Safekeeper) -> u32 {
455 19139 : 0
456 19139 : }
457 :
458 89443 : fn wait_event_set(
459 89443 : &self,
460 89443 : _: &mut walproposer::bindings::WalProposer,
461 89443 : timeout_millis: i64,
462 89443 : ) -> walproposer::walproposer::WaitResult {
463 89443 : // TODO: handle multiple stages as part of the simulation (e.g. connect, start_wal_push, etc)
464 89443 : let mut conns = self.safekeepers.borrow_mut();
465 206813 : for conn in conns.iter_mut() {
466 206813 : if conn.socket.is_some() && conn.is_connecting {
467 30733 : conn.is_connecting = false;
468 30733 : debug!("wait_event_set, connecting to {}:{}", conn.host, conn.port);
469 30733 : return walproposer::walproposer::WaitResult::Network(
470 30733 : conn.raw_ptr,
471 30733 : WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE,
472 30733 : );
473 176080 : }
474 176080 : if conn.socket.is_some() && conn.is_start_wal_push {
475 30733 : conn.is_start_wal_push = false;
476 30733 : debug!(
477 0 : "wait_event_set, start wal push to {}:{}",
478 : conn.host, conn.port
479 : );
480 30733 : return walproposer::walproposer::WaitResult::Network(
481 30733 : conn.raw_ptr,
482 30733 : WL_SOCKET_READABLE,
483 30733 : );
484 145347 : }
485 : }
486 27977 : drop(conns);
487 27977 :
488 27977 : let res = self
489 27977 : .event_set
490 27977 : .borrow_mut()
491 27977 : .as_mut()
492 27977 : .unwrap()
493 27977 : .wait(timeout_millis);
494 27977 :
495 27977 : debug!(
496 0 : "wait_event_set, timeout_millis={}, res={:?}",
497 : timeout_millis, res,
498 : );
499 19160 : res
500 80626 : }
501 :
502 9285 : fn strong_random(&self, buf: &mut [u8]) -> bool {
503 9285 : debug!("strong_random");
504 9285 : buf.fill(0);
505 9285 : true
506 9285 : }
507 :
508 346 : fn finish_sync_safekeepers(&self, lsn: u64) {
509 346 : debug!("finish_sync_safekeepers, lsn={}", lsn);
510 346 : executor::exit(0, Lsn(lsn).to_string());
511 346 : }
512 :
513 92311 : fn log_internal(&self, _wp: &mut walproposer::bindings::WalProposer, level: Level, msg: &str) {
514 92311 : debug!("wp_log[{}] {}", level, msg);
515 92311 : if level == Level::Fatal || level == Level::Panic {
516 71 : if msg.contains("rejects our connection request with term") {
517 40 : // collected quorum with lower term, then got rejected by next connected safekeeper
518 40 : executor::exit(1, msg.to_owned());
519 40 : }
520 71 : if msg.contains("collected propEpochStartLsn") && msg.contains(", but basebackup LSN ")
521 1 : {
522 1 : // sync-safekeepers collected wrong quorum, walproposer collected another quorum
523 1 : executor::exit(1, msg.to_owned());
524 70 : }
525 71 : if msg.contains("failed to download WAL for logical replicaiton") {
526 16 : // Recovery connection broken and recovery was failed
527 16 : executor::exit(1, msg.to_owned());
528 55 : }
529 71 : if msg.contains("missing majority of votes, collected") {
530 14 : // Voting bug when safekeeper disconnects after voting
531 14 : executor::exit(1, msg.to_owned());
532 57 : }
533 71 : panic!("unknown FATAL error from walproposer: {}", msg);
534 92240 : }
535 92240 : }
536 :
537 737 : fn after_election(&self, wp: &mut walproposer::bindings::WalProposer) {
538 737 : let prop_lsn = wp.propEpochStartLsn;
539 737 : let prop_term = wp.propTerm;
540 737 :
541 737 : let mut prev_lsn: u64 = 0;
542 737 : let mut prev_term: u64 = 0;
543 737 :
544 737 : unsafe {
545 737 : let history = wp.propTermHistory.entries;
546 737 : let len = wp.propTermHistory.n_entries as usize;
547 737 : if len > 1 {
548 510 : let entry = *history.wrapping_add(len - 2);
549 510 : prev_lsn = entry.lsn;
550 510 : prev_term = entry.term;
551 510 : }
552 : }
553 :
554 737 : let msg = format!(
555 737 : "prop_elected;{};{};{};{}",
556 737 : prop_lsn, prop_term, prev_lsn, prev_term
557 737 : );
558 737 :
559 737 : debug!(msg);
560 737 : self.os.log_event(msg);
561 737 : }
562 :
563 295 : fn get_redo_start_lsn(&self) -> u64 {
564 295 : debug!("get_redo_start_lsn -> {:?}", self.redo_start_lsn);
565 295 : self.redo_start_lsn.expect("redo_start_lsn is not set").0
566 295 : }
567 :
568 2538 : fn get_shmem_state(&self) -> *mut walproposer::bindings::WalproposerShmemState {
569 2538 : self.shmem.get()
570 2538 : }
571 :
572 179 : fn start_streaming(
573 179 : &self,
574 179 : startpos: u64,
575 179 : callback: &walproposer::walproposer::StreamingCallback,
576 179 : ) {
577 179 : let disk = &self.disk;
578 179 : let disk_lsn = disk.lock().flush_rec_ptr().0;
579 179 : debug!("start_streaming at {} (disk_lsn={})", startpos, disk_lsn);
580 179 : if startpos < disk_lsn {
581 44 : debug!("startpos < disk_lsn, it means we wrote some transaction even before streaming started");
582 135 : }
583 179 : assert!(startpos <= disk_lsn);
584 179 : let mut broadcasted = Lsn(startpos);
585 :
586 : loop {
587 733 : let available = disk.lock().flush_rec_ptr();
588 733 : assert!(available >= broadcasted);
589 554 : callback.broadcast(broadcasted, available);
590 554 : broadcasted = available;
591 554 : callback.poll();
592 : }
593 : }
594 :
595 2578 : fn process_safekeeper_feedback(
596 2578 : &mut self,
597 2578 : wp: &mut walproposer::bindings::WalProposer,
598 2578 : _sk: &mut walproposer::bindings::Safekeeper,
599 2578 : ) {
600 2578 : debug!("process_safekeeper_feedback, commit_lsn={}", wp.commitLsn);
601 2578 : if wp.commitLsn > self.last_logged_commit_lsn {
602 581 : self.os.log_event(format!("commit_lsn;{}", wp.commitLsn));
603 581 : self.last_logged_commit_lsn = wp.commitLsn;
604 1997 : }
605 2578 : }
606 :
607 107 : fn get_flush_rec_ptr(&self) -> u64 {
608 107 : let lsn = self.disk.lock().flush_rec_ptr();
609 107 : debug!("get_flush_rec_ptr: {}", lsn);
610 107 : lsn.0
611 107 : }
612 :
613 737 : fn recovery_download(
614 737 : &self,
615 737 : wp: &mut walproposer::bindings::WalProposer,
616 737 : sk: &mut walproposer::bindings::Safekeeper,
617 737 : ) -> bool {
618 737 : let mut startpos = wp.truncateLsn;
619 737 : let endpos = wp.propEpochStartLsn;
620 737 :
621 737 : if startpos == endpos {
622 449 : debug!("recovery_download: nothing to download");
623 449 : return true;
624 288 : }
625 288 :
626 288 : debug!("recovery_download from {} to {}", startpos, endpos,);
627 :
628 288 : let replication_prompt = format!(
629 288 : "START_REPLICATION {} {} {} {}",
630 288 : self.config.ttid.tenant_id, self.config.ttid.timeline_id, startpos, endpos,
631 288 : );
632 288 : let async_conn = self.get_conn(sk);
633 288 :
634 288 : let conn = self.os.open_tcp(async_conn.node_id);
635 288 : conn.send(desim::proto::AnyMessage::Bytes(replication_prompt.into()));
636 288 :
637 288 : let chan = conn.recv_chan();
638 509 : while startpos < endpos {
639 288 : let event = chan.recv();
640 272 : match event {
641 : NetEvent::Closed => {
642 16 : debug!("connection closed in recovery");
643 16 : break;
644 : }
645 272 : NetEvent::Message(AnyMessage::Bytes(b)) => {
646 272 : debug!("got recovery bytes from safekeeper");
647 221 : self.disk.lock().write(startpos, &b);
648 221 : startpos += b.len() as u64;
649 : }
650 0 : NetEvent::Message(_) => unreachable!(),
651 : }
652 : }
653 :
654 237 : debug!("recovery finished at {}", startpos);
655 :
656 237 : startpos == endpos
657 686 : }
658 :
659 10665 : fn conn_finish(&self, sk: &mut walproposer::bindings::Safekeeper) {
660 10665 : let mut conn = self.get_conn(sk);
661 10665 : debug!("conn_finish to {}", conn.node_id);
662 10665 : if let Some(socket) = conn.socket.as_mut() {
663 3511 : socket.close();
664 7154 : } else {
665 7154 : // connection is already closed
666 7154 : }
667 10665 : conn.socket = None;
668 10665 : }
669 :
670 10454 : fn conn_error_message(&self, _sk: &mut walproposer::bindings::Safekeeper) -> String {
671 10454 : "connection is closed, probably".into()
672 10454 : }
673 : }
|