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