Skip to main content

picodata_plugin/internal/
mod.rs

1//! Picodata internal API.
2pub mod cas;
3pub(crate) mod ffi;
4pub mod types;
5
6use crate::internal::ffi::{
7    pico_ffi_cluster_uuid, pico_ffi_instance_info, pico_ffi_raft_info, pico_ffi_rpc_version,
8    pico_ffi_version,
9};
10use crate::internal::types::InstanceInfo;
11use abi_stable::derive_macro_reexports::RResult;
12use std::{env, fs, io, process};
13use tarantool::error::BoxError;
14
15/// Return picodata version.
16pub fn picodata_version() -> &'static str {
17    let ptr_and_len = unsafe { pico_ffi_version() };
18    // SAFETY: ptr points to static string
19    let slice = unsafe { std::slice::from_raw_parts(ptr_and_len.0, ptr_and_len.1) };
20    std::str::from_utf8(slice).expect("should be valid utf8")
21}
22
23/// Return picodata RPC API version.
24pub fn rpc_version() -> &'static str {
25    let ptr_and_len = unsafe { pico_ffi_rpc_version() };
26    // SAFETY: ptr points to static string
27    let slice = unsafe { std::slice::from_raw_parts(ptr_and_len.0, ptr_and_len.1) };
28    std::str::from_utf8(slice).expect("should be valid utf8")
29}
30
31/// Return UUID of the cluster the current instance belongs to.
32pub fn cluster_uuid() -> Result<String, BoxError> {
33    match unsafe { pico_ffi_cluster_uuid() } {
34        RResult::ROk(rstring) => Ok(rstring.into()),
35        RResult::RErr(_) => {
36            let error = BoxError::last();
37            Err(error)
38        }
39    }
40}
41
42/// Return information about current picodata instance.
43pub fn instance_info() -> Result<InstanceInfo, BoxError> {
44    match unsafe { pico_ffi_instance_info() } {
45        RResult::ROk(info) => Ok(info),
46        RResult::RErr(_) => {
47            let error = BoxError::last();
48            Err(error)
49        }
50    }
51}
52
53/// Return information about RAFT protocol state.
54pub fn raft_info() -> types::RaftInfo {
55    unsafe { pico_ffi_raft_info() }
56}
57
58/// Dump the backtrace to a file to make debugging easier.
59/// This is also used in integration tests.
60fn dump_backtrace(msg: &str) -> Result<(), io::Error> {
61    let should_dump = env::var("PICODATA_INTERNAL_BACKTRACE_DUMP")
62        .map(|v| !v.is_empty())
63        .unwrap_or(false);
64
65    if !should_dump {
66        return Ok(());
67    }
68
69    let name = format!("picodata-{}.backtrace", process::id());
70    let path = env::current_dir()?.join(&name);
71
72    fs::write(&name, msg)
73        .map(|_| tarantool::say_info!("dumped panic backtrace to `{}`", path.display()))
74        .inspect_err(|e| tarantool::say_info!("{}", e))?;
75
76    Ok(())
77}
78
79#[inline]
80pub fn set_panic_hook() {
81    // NOTE: this function is called ASAP when starting up the process.
82    // Even if `say` isn't properly initialized yet, we
83    // still should be able to print a simplified line to stderr.
84    std::panic::set_hook(Box::new(|info| {
85        let version = crate::internal::picodata_version();
86
87        // Capture a backtrace regardless of RUST_BACKTRACE and such.
88        let backtrace = std::backtrace::Backtrace::force_capture();
89        let message = format!(
90            "Picodata {version}\n\n{info}\n\nbacktrace:\n{backtrace}\naborting due to panic"
91        );
92
93        // Dump backtrace to logs and file if needed
94        tarantool::say_crit!("\n\n{message}");
95        dump_backtrace(&message)
96            .unwrap_or_else(|e| tarantool::say_info!("Failed to dump panic backtrace: {}", e));
97
98        std::process::abort();
99    }));
100}
101
102#[derive(thiserror::Error, Debug)]
103pub enum InternalError {
104    #[error("timeout")]
105    Timeout,
106    #[error("internal error: {0}")]
107    Any(BoxError),
108}