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