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