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

Generated by: LCOV version 2.1-beta