Line data Source code
1 : //! A C-Rust shim: defines implementation of C walproposer API, assuming wp
2 : //! callback_data stores Box to some Rust implementation.
3 :
4 : #![allow(dead_code)]
5 :
6 : use std::ffi::{CStr, CString};
7 :
8 : use crate::bindings::{
9 : NeonWALReadResult, PGAsyncReadResult, PGAsyncWriteResult, Safekeeper, Size, StringInfoData,
10 : TimestampTz, WalProposer, WalProposerConnStatusType, WalProposerConnectPollStatusType,
11 : WalProposerExecStatusType, WalproposerShmemState, XLogRecPtr, uint32, walproposer_api,
12 : };
13 : use crate::walproposer::{ApiImpl, StreamingCallback, WaitResult};
14 :
15 1040 : extern "C" fn get_shmem_state(wp: *mut WalProposer) -> *mut WalproposerShmemState {
16 : unsafe {
17 1040 : let callback_data = (*(*wp).config).callback_data;
18 1040 : let api = callback_data as *mut Box<dyn ApiImpl>;
19 1040 : (*api).get_shmem_state()
20 : }
21 1040 : }
22 :
23 154 : extern "C-unwind" fn start_streaming(wp: *mut WalProposer, startpos: XLogRecPtr) {
24 154 : unsafe {
25 154 : let callback_data = (*(*wp).config).callback_data;
26 154 : let api = callback_data as *mut Box<dyn ApiImpl>;
27 154 : let callback = StreamingCallback::new(wp);
28 154 : (*api).start_streaming(startpos, &callback);
29 154 : }
30 154 : }
31 :
32 92 : extern "C" fn get_flush_rec_ptr(wp: *mut WalProposer) -> XLogRecPtr {
33 : unsafe {
34 92 : let callback_data = (*(*wp).config).callback_data;
35 92 : let api = callback_data as *mut Box<dyn ApiImpl>;
36 92 : (*api).get_flush_rec_ptr()
37 : }
38 92 : }
39 :
40 930 : extern "C" fn update_donor(wp: *mut WalProposer, donor: *mut Safekeeper, donor_lsn: XLogRecPtr) {
41 : unsafe {
42 930 : let callback_data = (*(*wp).config).callback_data;
43 930 : let api = callback_data as *mut Box<dyn ApiImpl>;
44 930 : (*api).update_donor(&mut (*donor), donor_lsn)
45 : }
46 930 : }
47 :
48 320305 : extern "C" fn get_current_timestamp(wp: *mut WalProposer) -> TimestampTz {
49 : unsafe {
50 320305 : let callback_data = (*(*wp).config).callback_data;
51 320305 : let api = callback_data as *mut Box<dyn ApiImpl>;
52 320305 : (*api).get_current_timestamp()
53 : }
54 320305 : }
55 :
56 11699 : extern "C" fn conn_error_message(sk: *mut Safekeeper) -> *mut ::std::os::raw::c_char {
57 : unsafe {
58 11699 : let callback_data = (*(*(*sk).wp).config).callback_data;
59 11699 : let api = callback_data as *mut Box<dyn ApiImpl>;
60 11699 : let msg = (*api).conn_error_message(&mut (*sk));
61 11699 : let msg = CString::new(msg).unwrap();
62 : // TODO: fix leaking error message
63 11699 : msg.into_raw()
64 : }
65 11699 : }
66 :
67 33366 : extern "C" fn conn_status(sk: *mut Safekeeper) -> WalProposerConnStatusType {
68 : unsafe {
69 33366 : let callback_data = (*(*(*sk).wp).config).callback_data;
70 33366 : let api = callback_data as *mut Box<dyn ApiImpl>;
71 33366 : (*api).conn_status(&mut (*sk))
72 : }
73 33366 : }
74 :
75 33366 : extern "C" fn conn_connect_start(sk: *mut Safekeeper) {
76 : unsafe {
77 33366 : let callback_data = (*(*(*sk).wp).config).callback_data;
78 33366 : let api = callback_data as *mut Box<dyn ApiImpl>;
79 33366 : (*api).conn_connect_start(&mut (*sk))
80 : }
81 33366 : }
82 :
83 30153 : extern "C" fn conn_connect_poll(sk: *mut Safekeeper) -> WalProposerConnectPollStatusType {
84 : unsafe {
85 30153 : let callback_data = (*(*(*sk).wp).config).callback_data;
86 30153 : let api = callback_data as *mut Box<dyn ApiImpl>;
87 30153 : (*api).conn_connect_poll(&mut (*sk))
88 : }
89 30153 : }
90 :
91 30153 : extern "C" fn conn_send_query(sk: *mut Safekeeper, query: *mut ::std::os::raw::c_char) -> bool {
92 30153 : let query = unsafe { CStr::from_ptr(query) };
93 30153 : let query = query.to_str().unwrap();
94 :
95 : unsafe {
96 30153 : let callback_data = (*(*(*sk).wp).config).callback_data;
97 30153 : let api = callback_data as *mut Box<dyn ApiImpl>;
98 30153 : (*api).conn_send_query(&mut (*sk), query)
99 : }
100 30153 : }
101 :
102 30153 : extern "C" fn conn_get_query_result(sk: *mut Safekeeper) -> WalProposerExecStatusType {
103 : unsafe {
104 30153 : let callback_data = (*(*(*sk).wp).config).callback_data;
105 30153 : let api = callback_data as *mut Box<dyn ApiImpl>;
106 30153 : (*api).conn_get_query_result(&mut (*sk))
107 : }
108 30153 : }
109 :
110 0 : extern "C" fn conn_flush(sk: *mut Safekeeper) -> ::std::os::raw::c_int {
111 : unsafe {
112 0 : let callback_data = (*(*(*sk).wp).config).callback_data;
113 0 : let api = callback_data as *mut Box<dyn ApiImpl>;
114 0 : (*api).conn_flush(&mut (*sk))
115 : }
116 0 : }
117 :
118 12052 : extern "C" fn conn_finish(sk: *mut Safekeeper) {
119 : unsafe {
120 12052 : let callback_data = (*(*(*sk).wp).config).callback_data;
121 12052 : let api = callback_data as *mut Box<dyn ApiImpl>;
122 12052 : (*api).conn_finish(&mut (*sk))
123 : }
124 12052 : }
125 :
126 19548 : extern "C" fn conn_async_read(
127 19548 : sk: *mut Safekeeper,
128 19548 : buf: *mut *mut ::std::os::raw::c_char,
129 19548 : amount: *mut ::std::os::raw::c_int,
130 19548 : ) -> PGAsyncReadResult {
131 : unsafe {
132 19548 : let callback_data = (*(*(*sk).wp).config).callback_data;
133 19548 : let api = callback_data as *mut Box<dyn ApiImpl>;
134 :
135 : // This function has guarantee that returned buf will be valid until
136 : // the next call. So we can store a Vec in each Safekeeper and reuse
137 : // it on the next call.
138 19548 : let mut inbuf = take_vec_u8(&mut (*sk).inbuf).unwrap_or_default();
139 19548 : inbuf.clear();
140 :
141 19548 : let result = (*api).conn_async_read(&mut (*sk), &mut inbuf);
142 :
143 : // Put a Vec back to sk->inbuf and return data ptr.
144 19548 : *amount = inbuf.len() as i32;
145 19548 : *buf = store_vec_u8(&mut (*sk).inbuf, inbuf);
146 :
147 19548 : result
148 : }
149 19548 : }
150 :
151 5222 : extern "C" fn conn_async_write(
152 5222 : sk: *mut Safekeeper,
153 5222 : buf: *const ::std::os::raw::c_void,
154 5222 : size: usize,
155 5222 : ) -> PGAsyncWriteResult {
156 : unsafe {
157 5222 : let buf = std::slice::from_raw_parts(buf as *const u8, size);
158 5222 : let callback_data = (*(*(*sk).wp).config).callback_data;
159 5222 : let api = callback_data as *mut Box<dyn ApiImpl>;
160 5222 : (*api).conn_async_write(&mut (*sk), buf)
161 : }
162 5222 : }
163 :
164 33663 : extern "C" fn conn_blocking_write(
165 33663 : sk: *mut Safekeeper,
166 33663 : buf: *const ::std::os::raw::c_void,
167 33663 : size: usize,
168 33663 : ) -> bool {
169 : unsafe {
170 33663 : let buf = std::slice::from_raw_parts(buf as *const u8, size);
171 33663 : let callback_data = (*(*(*sk).wp).config).callback_data;
172 33663 : let api = callback_data as *mut Box<dyn ApiImpl>;
173 33663 : (*api).conn_blocking_write(&mut (*sk), buf)
174 : }
175 33663 : }
176 :
177 519 : extern "C-unwind" fn recovery_download(wp: *mut WalProposer, sk: *mut Safekeeper) -> bool {
178 : unsafe {
179 519 : let callback_data = (*(*(*sk).wp).config).callback_data;
180 519 : let api = callback_data as *mut Box<dyn ApiImpl>;
181 :
182 : // currently `recovery_download` is always called right after election
183 519 : (*api).after_election(&mut (*wp));
184 :
185 519 : (*api).recovery_download(&mut (*wp), &mut (*sk))
186 : }
187 519 : }
188 :
189 942 : extern "C" fn wal_reader_allocate(sk: *mut Safekeeper) {
190 942 : unsafe {
191 942 : let callback_data = (*(*(*sk).wp).config).callback_data;
192 942 : let api = callback_data as *mut Box<dyn ApiImpl>;
193 942 : (*api).wal_reader_allocate(&mut (*sk));
194 942 : }
195 942 : }
196 :
197 : #[allow(clippy::unnecessary_cast)]
198 1106 : extern "C" fn wal_read(
199 1106 : sk: *mut Safekeeper,
200 1106 : buf: *mut ::std::os::raw::c_char,
201 1106 : startptr: XLogRecPtr,
202 1106 : count: Size,
203 1106 : _errmsg: *mut *mut ::std::os::raw::c_char,
204 1106 : ) -> NeonWALReadResult {
205 : unsafe {
206 1106 : let buf = std::slice::from_raw_parts_mut(buf as *mut u8, count);
207 1106 : let callback_data = (*(*(*sk).wp).config).callback_data;
208 1106 : let api = callback_data as *mut Box<dyn ApiImpl>;
209 : // TODO: errmsg is not forwarded
210 1106 : (*api).wal_read(&mut (*sk), buf, startptr)
211 : }
212 1106 : }
213 :
214 20365 : extern "C" fn wal_reader_events(sk: *mut Safekeeper) -> uint32 {
215 : unsafe {
216 20365 : let callback_data = (*(*(*sk).wp).config).callback_data;
217 20365 : let api = callback_data as *mut Box<dyn ApiImpl>;
218 20365 : (*api).wal_reader_events(&mut (*sk))
219 : }
220 20365 : }
221 :
222 8954 : extern "C" fn init_event_set(wp: *mut WalProposer) {
223 8954 : unsafe {
224 8954 : let callback_data = (*(*wp).config).callback_data;
225 8954 : let api = callback_data as *mut Box<dyn ApiImpl>;
226 8954 : (*api).init_event_set(&mut (*wp));
227 8954 : }
228 8954 : }
229 :
230 65694 : extern "C" fn update_event_set(sk: *mut Safekeeper, events: uint32) {
231 65694 : unsafe {
232 65694 : let callback_data = (*(*(*sk).wp).config).callback_data;
233 65694 : let api = callback_data as *mut Box<dyn ApiImpl>;
234 65694 : (*api).update_event_set(&mut (*sk), events);
235 65694 : }
236 65694 : }
237 :
238 6648 : extern "C" fn active_state_update_event_set(sk: *mut Safekeeper) {
239 6648 : unsafe {
240 6648 : let callback_data = (*(*(*sk).wp).config).callback_data;
241 6648 : let api = callback_data as *mut Box<dyn ApiImpl>;
242 6648 : (*api).active_state_update_event_set(&mut (*sk));
243 6648 : }
244 6648 : }
245 :
246 60306 : extern "C" fn add_safekeeper_event_set(sk: *mut Safekeeper, events: uint32) {
247 60306 : unsafe {
248 60306 : let callback_data = (*(*(*sk).wp).config).callback_data;
249 60306 : let api = callback_data as *mut Box<dyn ApiImpl>;
250 60306 : (*api).add_safekeeper_event_set(&mut (*sk), events);
251 60306 : }
252 60306 : }
253 :
254 38992 : extern "C" fn rm_safekeeper_event_set(sk: *mut Safekeeper) {
255 38992 : unsafe {
256 38992 : let callback_data = (*(*(*sk).wp).config).callback_data;
257 38992 : let api = callback_data as *mut Box<dyn ApiImpl>;
258 38992 : (*api).rm_safekeeper_event_set(&mut (*sk));
259 38992 : }
260 38992 : }
261 :
262 89325 : extern "C-unwind" fn wait_event_set(
263 89325 : wp: *mut WalProposer,
264 89325 : timeout: ::std::os::raw::c_long,
265 89325 : event_sk: *mut *mut Safekeeper,
266 89325 : events: *mut uint32,
267 89325 : ) -> ::std::os::raw::c_int {
268 : unsafe {
269 89325 : let callback_data = (*(*wp).config).callback_data;
270 89325 : let api = callback_data as *mut Box<dyn ApiImpl>;
271 89325 : let result = (*api).wait_event_set(&mut (*wp), timeout);
272 89325 : match result {
273 : WaitResult::Latch => {
274 8984 : *event_sk = std::ptr::null_mut();
275 8984 : *events = crate::bindings::WL_LATCH_SET;
276 8984 : 1
277 : }
278 : WaitResult::Timeout => {
279 2660 : *event_sk = std::ptr::null_mut();
280 : // WaitEventSetWait returns 0 for timeout.
281 2660 : *events = 0;
282 2660 : 0
283 : }
284 77681 : WaitResult::Network(sk, event_mask) => {
285 77681 : *event_sk = sk;
286 77681 : *events = event_mask;
287 77681 : 1
288 : }
289 : }
290 : }
291 89325 : }
292 :
293 0 : extern "C" fn strong_random(
294 0 : wp: *mut WalProposer,
295 0 : buf: *mut ::std::os::raw::c_void,
296 0 : len: usize,
297 0 : ) -> bool {
298 : unsafe {
299 0 : let buf = std::slice::from_raw_parts_mut(buf as *mut u8, len);
300 0 : let callback_data = (*(*wp).config).callback_data;
301 0 : let api = callback_data as *mut Box<dyn ApiImpl>;
302 0 : (*api).strong_random(buf)
303 : }
304 0 : }
305 :
306 212 : extern "C" fn get_redo_start_lsn(wp: *mut WalProposer) -> XLogRecPtr {
307 : unsafe {
308 212 : let callback_data = (*(*wp).config).callback_data;
309 212 : let api = callback_data as *mut Box<dyn ApiImpl>;
310 212 : (*api).get_redo_start_lsn()
311 : }
312 212 : }
313 :
314 377 : unsafe extern "C-unwind" fn finish_sync_safekeepers(wp: *mut WalProposer, lsn: XLogRecPtr) -> ! {
315 : unsafe {
316 377 : let callback_data = (*(*wp).config).callback_data;
317 377 : let api = callback_data as *mut Box<dyn ApiImpl>;
318 377 : (*api).finish_sync_safekeepers(lsn)
319 : }
320 : }
321 :
322 2582 : extern "C" fn process_safekeeper_feedback(wp: *mut WalProposer, sk: *mut Safekeeper) {
323 2582 : unsafe {
324 2582 : let callback_data = (*(*wp).config).callback_data;
325 2582 : let api = callback_data as *mut Box<dyn ApiImpl>;
326 2582 : (*api).process_safekeeper_feedback(&mut (*wp), &mut (*sk));
327 2582 : }
328 2582 : }
329 :
330 151233 : extern "C-unwind" fn log_internal(
331 151233 : wp: *mut WalProposer,
332 151233 : level: ::std::os::raw::c_int,
333 151233 : line: *const ::std::os::raw::c_char,
334 151233 : ) {
335 : unsafe {
336 151233 : let callback_data = (*(*wp).config).callback_data;
337 151233 : let api = callback_data as *mut Box<dyn ApiImpl>;
338 151233 : let line = CStr::from_ptr(line);
339 151233 : let line = line.to_str().unwrap();
340 151233 : (*api).log_internal(&mut (*wp), Level::from(level as u32), line)
341 : }
342 151233 : }
343 :
344 : #[derive(Debug, PartialEq)]
345 : pub enum Level {
346 : Debug5,
347 : Debug4,
348 : Debug3,
349 : Debug2,
350 : Debug1,
351 : Log,
352 : Info,
353 : Notice,
354 : Warning,
355 : Error,
356 : Fatal,
357 : Panic,
358 : WPEvent,
359 : }
360 :
361 : impl Level {
362 151233 : pub fn from(elevel: u32) -> Level {
363 : use crate::bindings::*;
364 :
365 151233 : match elevel {
366 4280 : DEBUG5 => Level::Debug5,
367 0 : DEBUG4 => Level::Debug4,
368 0 : DEBUG3 => Level::Debug3,
369 2582 : DEBUG2 => Level::Debug2,
370 0 : DEBUG1 => Level::Debug1,
371 130885 : LOG => Level::Log,
372 0 : INFO => Level::Info,
373 0 : NOTICE => Level::Notice,
374 13418 : WARNING => Level::Warning,
375 0 : ERROR => Level::Error,
376 67 : FATAL => Level::Fatal,
377 1 : PANIC => Level::Panic,
378 0 : WPEVENT => Level::WPEvent,
379 0 : _ => panic!("unknown log level {elevel}"),
380 : }
381 151233 : }
382 : }
383 :
384 8954 : pub(crate) fn create_api() -> walproposer_api {
385 8954 : walproposer_api {
386 8954 : get_shmem_state: Some(get_shmem_state),
387 8954 : start_streaming: Some(start_streaming),
388 8954 : get_flush_rec_ptr: Some(get_flush_rec_ptr),
389 8954 : update_donor: Some(update_donor),
390 8954 : get_current_timestamp: Some(get_current_timestamp),
391 8954 : conn_error_message: Some(conn_error_message),
392 8954 : conn_status: Some(conn_status),
393 8954 : conn_connect_start: Some(conn_connect_start),
394 8954 : conn_connect_poll: Some(conn_connect_poll),
395 8954 : conn_send_query: Some(conn_send_query),
396 8954 : conn_get_query_result: Some(conn_get_query_result),
397 8954 : conn_flush: Some(conn_flush),
398 8954 : conn_finish: Some(conn_finish),
399 8954 : conn_async_read: Some(conn_async_read),
400 8954 : conn_async_write: Some(conn_async_write),
401 8954 : conn_blocking_write: Some(conn_blocking_write),
402 8954 : recovery_download: Some(recovery_download),
403 8954 : wal_reader_allocate: Some(wal_reader_allocate),
404 8954 : wal_read: Some(wal_read),
405 8954 : wal_reader_events: Some(wal_reader_events),
406 8954 : init_event_set: Some(init_event_set),
407 8954 : update_event_set: Some(update_event_set),
408 8954 : active_state_update_event_set: Some(active_state_update_event_set),
409 8954 : add_safekeeper_event_set: Some(add_safekeeper_event_set),
410 8954 : rm_safekeeper_event_set: Some(rm_safekeeper_event_set),
411 8954 : wait_event_set: Some(wait_event_set),
412 8954 : strong_random: Some(strong_random),
413 8954 : get_redo_start_lsn: Some(get_redo_start_lsn),
414 8954 : finish_sync_safekeepers: Some(finish_sync_safekeepers),
415 8954 : process_safekeeper_feedback: Some(process_safekeeper_feedback),
416 8954 : log_internal: Some(log_internal),
417 8954 : }
418 8954 : }
419 :
420 8954 : pub fn empty_shmem() -> crate::bindings::WalproposerShmemState {
421 8954 : let empty_feedback = crate::bindings::PageserverFeedback {
422 8954 : present: false,
423 8954 : currentClusterSize: 0,
424 8954 : last_received_lsn: 0,
425 8954 : disk_consistent_lsn: 0,
426 8954 : remote_consistent_lsn: 0,
427 8954 : replytime: 0,
428 8954 : shard_number: 0,
429 8954 : };
430 :
431 8954 : let empty_wal_rate_limiter = crate::bindings::WalRateLimiter {
432 8954 : should_limit: crate::bindings::pg_atomic_uint32 { value: 0 },
433 8954 : sent_bytes: 0,
434 8954 : last_recorded_time_us: crate::bindings::pg_atomic_uint64 { value: 0 },
435 8954 : };
436 :
437 8954 : crate::bindings::WalproposerShmemState {
438 8954 : propEpochStartLsn: crate::bindings::pg_atomic_uint64 { value: 0 },
439 8954 : donor_name: [0; 64],
440 8954 : donor_conninfo: [0; 1024],
441 8954 : donor_lsn: 0,
442 8954 : mutex: 0,
443 8954 : mineLastElectedTerm: crate::bindings::pg_atomic_uint64 { value: 0 },
444 8954 : backpressureThrottlingTime: crate::bindings::pg_atomic_uint64 { value: 0 },
445 8954 : currentClusterSize: crate::bindings::pg_atomic_uint64 { value: 0 },
446 8954 : shard_ps_feedback: [empty_feedback; 128],
447 8954 : num_shards: 0,
448 8954 : replica_promote: false,
449 8954 : min_ps_feedback: empty_feedback,
450 8954 : wal_rate_limiter: empty_wal_rate_limiter,
451 8954 : }
452 8954 : }
453 :
454 : impl std::fmt::Display for Level {
455 693 : fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
456 693 : write!(f, "{self:?}")
457 693 : }
458 : }
459 :
460 : /// Take ownership of `Vec<u8>` from StringInfoData.
461 : #[allow(clippy::unnecessary_cast)]
462 46402 : pub(crate) fn take_vec_u8(pg: &mut StringInfoData) -> Option<Vec<u8>> {
463 46402 : if pg.data.is_null() {
464 26860 : return None;
465 19542 : }
466 :
467 19542 : let ptr = pg.data as *mut u8;
468 19542 : let length = pg.len as usize;
469 19542 : let capacity = pg.maxlen as usize;
470 :
471 19542 : pg.data = std::ptr::null_mut();
472 19542 : pg.len = 0;
473 19542 : pg.maxlen = 0;
474 :
475 19542 : unsafe { Some(Vec::from_raw_parts(ptr, length, capacity)) }
476 46402 : }
477 :
478 : /// Store `Vec<u8>` in StringInfoData.
479 19548 : fn store_vec_u8(pg: &mut StringInfoData, vec: Vec<u8>) -> *mut ::std::os::raw::c_char {
480 19548 : let ptr = vec.as_ptr() as *mut ::std::os::raw::c_char;
481 19548 : let length = vec.len();
482 19548 : let capacity = vec.capacity();
483 :
484 19548 : assert!(pg.data.is_null());
485 :
486 19548 : pg.data = ptr;
487 19548 : pg.len = length as i32;
488 19548 : pg.maxlen = capacity as i32;
489 :
490 19548 : std::mem::forget(vec);
491 :
492 19548 : ptr
493 19548 : }
|