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