LCOV - code coverage report
Current view: top level - control_plane/src - safekeeper.rs (source / functions) Coverage Total Hit
Test: f8d8f5b90fa487a9e82c42da223f012f5d4fece7.info Lines: 0.0 % 170 0
Test Date: 2024-09-19 20:36:02 Functions: 0.0 % 22 0

            Line data    Source code
       1              : //! Code to manage safekeepers
       2              : //!
       3              : //! In the local test environment, the data for each safekeeper is stored in
       4              : //!
       5              : //! ```text
       6              : //!   .neon/safekeepers/<safekeeper id>
       7              : //! ```
       8              : use std::future::Future;
       9              : use std::io::Write;
      10              : use std::path::PathBuf;
      11              : use std::time::Duration;
      12              : use std::{io, result};
      13              : 
      14              : use anyhow::Context;
      15              : use camino::Utf8PathBuf;
      16              : use postgres_connection::PgConnectionConfig;
      17              : use reqwest::{IntoUrl, Method};
      18              : use thiserror::Error;
      19              : use utils::auth::{Claims, Scope};
      20              : use utils::{http::error::HttpErrorBody, id::NodeId};
      21              : 
      22              : use crate::{
      23              :     background_process,
      24              :     local_env::{LocalEnv, SafekeeperConf},
      25              : };
      26              : 
      27            0 : #[derive(Error, Debug)]
      28              : pub enum SafekeeperHttpError {
      29              :     #[error("Reqwest error: {0}")]
      30              :     Transport(#[from] reqwest::Error),
      31              : 
      32              :     #[error("Error: {0}")]
      33              :     Response(String),
      34              : }
      35              : 
      36              : type Result<T> = result::Result<T, SafekeeperHttpError>;
      37              : 
      38              : pub(crate) trait ResponseErrorMessageExt: Sized {
      39              :     fn error_from_body(self) -> impl Future<Output = Result<Self>> + Send;
      40              : }
      41              : 
      42              : impl ResponseErrorMessageExt for reqwest::Response {
      43            0 :     async fn error_from_body(self) -> Result<Self> {
      44            0 :         let status = self.status();
      45            0 :         if !(status.is_client_error() || status.is_server_error()) {
      46            0 :             return Ok(self);
      47            0 :         }
      48            0 : 
      49            0 :         // reqwest does not export its error construction utility functions, so let's craft the message ourselves
      50            0 :         let url = self.url().to_owned();
      51            0 :         Err(SafekeeperHttpError::Response(
      52            0 :             match self.json::<HttpErrorBody>().await {
      53            0 :                 Ok(err_body) => format!("Error: {}", err_body.msg),
      54            0 :                 Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
      55              :             },
      56              :         ))
      57            0 :     }
      58              : }
      59              : 
      60              : //
      61              : // Control routines for safekeeper.
      62              : //
      63              : // Used in CLI and tests.
      64              : //
      65              : #[derive(Debug)]
      66              : pub struct SafekeeperNode {
      67              :     pub id: NodeId,
      68              : 
      69              :     pub conf: SafekeeperConf,
      70              : 
      71              :     pub pg_connection_config: PgConnectionConfig,
      72              :     pub env: LocalEnv,
      73              :     pub http_client: reqwest::Client,
      74              :     pub listen_addr: String,
      75              :     pub http_base_url: String,
      76              : }
      77              : 
      78              : impl SafekeeperNode {
      79            0 :     pub fn from_env(env: &LocalEnv, conf: &SafekeeperConf) -> SafekeeperNode {
      80            0 :         let listen_addr = if let Some(ref listen_addr) = conf.listen_addr {
      81            0 :             listen_addr.clone()
      82              :         } else {
      83            0 :             "127.0.0.1".to_string()
      84              :         };
      85            0 :         SafekeeperNode {
      86            0 :             id: conf.id,
      87            0 :             conf: conf.clone(),
      88            0 :             pg_connection_config: Self::safekeeper_connection_config(&listen_addr, conf.pg_port),
      89            0 :             env: env.clone(),
      90            0 :             http_client: reqwest::Client::new(),
      91            0 :             http_base_url: format!("http://{}:{}/v1", listen_addr, conf.http_port),
      92            0 :             listen_addr,
      93            0 :         }
      94            0 :     }
      95              : 
      96              :     /// Construct libpq connection string for connecting to this safekeeper.
      97            0 :     fn safekeeper_connection_config(addr: &str, port: u16) -> PgConnectionConfig {
      98            0 :         PgConnectionConfig::new_host_port(url::Host::parse(addr).unwrap(), port)
      99            0 :     }
     100              : 
     101            0 :     pub fn datadir_path_by_id(env: &LocalEnv, sk_id: NodeId) -> PathBuf {
     102            0 :         env.safekeeper_data_dir(&format!("sk{sk_id}"))
     103            0 :     }
     104              : 
     105            0 :     pub fn datadir_path(&self) -> PathBuf {
     106            0 :         SafekeeperNode::datadir_path_by_id(&self.env, self.id)
     107            0 :     }
     108              : 
     109            0 :     pub fn pid_file(&self) -> Utf8PathBuf {
     110            0 :         Utf8PathBuf::from_path_buf(self.datadir_path().join("safekeeper.pid"))
     111            0 :             .expect("non-Unicode path")
     112            0 :     }
     113              : 
     114            0 :     pub async fn start(
     115            0 :         &self,
     116            0 :         extra_opts: Vec<String>,
     117            0 :         retry_timeout: &Duration,
     118            0 :     ) -> anyhow::Result<()> {
     119            0 :         print!(
     120            0 :             "Starting safekeeper at '{}' in '{}', retrying for {:?}",
     121            0 :             self.pg_connection_config.raw_address(),
     122            0 :             self.datadir_path().display(),
     123            0 :             retry_timeout,
     124            0 :         );
     125            0 :         io::stdout().flush().unwrap();
     126            0 : 
     127            0 :         let listen_pg = format!("{}:{}", self.listen_addr, self.conf.pg_port);
     128            0 :         let listen_http = format!("{}:{}", self.listen_addr, self.conf.http_port);
     129            0 :         let id = self.id;
     130            0 :         let datadir = self.datadir_path();
     131            0 : 
     132            0 :         let id_string = id.to_string();
     133            0 :         // TODO: add availability_zone to the config.
     134            0 :         // Right now we just specify any value here and use it to check metrics in tests.
     135            0 :         let availability_zone = format!("sk-{}", id_string);
     136              : 
     137            0 :         let mut args = vec![
     138            0 :             "-D".to_owned(),
     139            0 :             datadir
     140            0 :                 .to_str()
     141            0 :                 .with_context(|| {
     142            0 :                     format!("Datadir path {datadir:?} cannot be represented as a unicode string")
     143            0 :                 })?
     144            0 :                 .to_owned(),
     145            0 :             "--id".to_owned(),
     146            0 :             id_string,
     147            0 :             "--listen-pg".to_owned(),
     148            0 :             listen_pg,
     149            0 :             "--listen-http".to_owned(),
     150            0 :             listen_http,
     151            0 :             "--availability-zone".to_owned(),
     152            0 :             availability_zone,
     153              :         ];
     154            0 :         if let Some(pg_tenant_only_port) = self.conf.pg_tenant_only_port {
     155            0 :             let listen_pg_tenant_only = format!("{}:{}", self.listen_addr, pg_tenant_only_port);
     156            0 :             args.extend(["--listen-pg-tenant-only".to_owned(), listen_pg_tenant_only]);
     157            0 :         }
     158            0 :         if !self.conf.sync {
     159            0 :             args.push("--no-sync".to_owned());
     160            0 :         }
     161              : 
     162            0 :         let broker_endpoint = format!("{}", self.env.broker.client_url());
     163            0 :         args.extend(["--broker-endpoint".to_owned(), broker_endpoint]);
     164            0 : 
     165            0 :         let mut backup_threads = String::new();
     166            0 :         if let Some(threads) = self.conf.backup_threads {
     167            0 :             backup_threads = threads.to_string();
     168            0 :             args.extend(["--backup-threads".to_owned(), backup_threads]);
     169            0 :         } else {
     170            0 :             drop(backup_threads);
     171            0 :         }
     172              : 
     173            0 :         if let Some(ref remote_storage) = self.conf.remote_storage {
     174            0 :             args.extend(["--remote-storage".to_owned(), remote_storage.clone()]);
     175            0 :         }
     176              : 
     177            0 :         let key_path = self.env.base_data_dir.join("auth_public_key.pem");
     178            0 :         if self.conf.auth_enabled {
     179            0 :             let key_path_string = key_path
     180            0 :                 .to_str()
     181            0 :                 .with_context(|| {
     182            0 :                     format!("Key path {key_path:?} cannot be represented as a unicode string")
     183            0 :                 })?
     184            0 :                 .to_owned();
     185            0 :             args.extend([
     186            0 :                 "--pg-auth-public-key-path".to_owned(),
     187            0 :                 key_path_string.clone(),
     188            0 :             ]);
     189            0 :             args.extend([
     190            0 :                 "--pg-tenant-only-auth-public-key-path".to_owned(),
     191            0 :                 key_path_string.clone(),
     192            0 :             ]);
     193            0 :             args.extend([
     194            0 :                 "--http-auth-public-key-path".to_owned(),
     195            0 :                 key_path_string.clone(),
     196            0 :             ]);
     197            0 :         }
     198              : 
     199            0 :         args.extend(extra_opts);
     200            0 : 
     201            0 :         background_process::start_process(
     202            0 :             &format!("safekeeper-{id}"),
     203            0 :             &datadir,
     204            0 :             &self.env.safekeeper_bin(),
     205            0 :             &args,
     206            0 :             self.safekeeper_env_variables()?,
     207            0 :             background_process::InitialPidFile::Expect(self.pid_file()),
     208            0 :             retry_timeout,
     209            0 :             || async {
     210            0 :                 match self.check_status().await {
     211            0 :                     Ok(()) => Ok(true),
     212            0 :                     Err(SafekeeperHttpError::Transport(_)) => Ok(false),
     213            0 :                     Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")),
     214              :                 }
     215            0 :             },
     216            0 :         )
     217            0 :         .await
     218            0 :     }
     219              : 
     220            0 :     fn safekeeper_env_variables(&self) -> anyhow::Result<Vec<(String, String)>> {
     221            0 :         // Generate a token to connect from safekeeper to peers
     222            0 :         if self.conf.auth_enabled {
     223            0 :             let token = self
     224            0 :                 .env
     225            0 :                 .generate_auth_token(&Claims::new(None, Scope::SafekeeperData))?;
     226            0 :             Ok(vec![("SAFEKEEPER_AUTH_TOKEN".to_owned(), token)])
     227              :         } else {
     228            0 :             Ok(Vec::new())
     229              :         }
     230            0 :     }
     231              : 
     232              :     ///
     233              :     /// Stop the server.
     234              :     ///
     235              :     /// If 'immediate' is true, we use SIGQUIT, killing the process immediately.
     236              :     /// Otherwise we use SIGTERM, triggering a clean shutdown
     237              :     ///
     238              :     /// If the server is not running, returns success
     239              :     ///
     240            0 :     pub fn stop(&self, immediate: bool) -> anyhow::Result<()> {
     241            0 :         background_process::stop_process(
     242            0 :             immediate,
     243            0 :             &format!("safekeeper {}", self.id),
     244            0 :             &self.pid_file(),
     245            0 :         )
     246            0 :     }
     247              : 
     248            0 :     fn http_request<U: IntoUrl>(&self, method: Method, url: U) -> reqwest::RequestBuilder {
     249            0 :         // TODO: authentication
     250            0 :         //if self.env.auth_type == AuthType::NeonJWT {
     251            0 :         //    builder = builder.bearer_auth(&self.env.safekeeper_auth_token)
     252            0 :         //}
     253            0 :         self.http_client.request(method, url)
     254            0 :     }
     255              : 
     256            0 :     pub async fn check_status(&self) -> Result<()> {
     257            0 :         self.http_request(Method::GET, format!("{}/{}", self.http_base_url, "status"))
     258            0 :             .send()
     259            0 :             .await?
     260            0 :             .error_from_body()
     261            0 :             .await?;
     262            0 :         Ok(())
     263            0 :     }
     264              : }
        

Generated by: LCOV version 2.1-beta