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