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