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