LCOV - code coverage report
Current view: top level - control_plane/src - local_env.rs (source / functions) Coverage Total Hit
Test: 36bb8dd7c7efcb53483d1a7d9f7cb33e8406dcf0.info Lines: 22.9 % 340 78
Test Date: 2024-04-08 10:22:05 Functions: 23.3 % 86 20

            Line data    Source code
       1              : //! This module is responsible for locating and loading paths in a local setup.
       2              : //!
       3              : //! Now it also provides init method which acts like a stub for proper installation
       4              : //! script which will use local paths.
       5              : 
       6              : use anyhow::{bail, ensure, Context};
       7              : 
       8              : use clap::ValueEnum;
       9              : use postgres_backend::AuthType;
      10              : use reqwest::Url;
      11              : use serde::{Deserialize, Serialize};
      12              : use std::collections::HashMap;
      13              : use std::env;
      14              : use std::fs;
      15              : use std::net::IpAddr;
      16              : use std::net::Ipv4Addr;
      17              : use std::net::SocketAddr;
      18              : use std::path::{Path, PathBuf};
      19              : use std::process::{Command, Stdio};
      20              : use utils::{
      21              :     auth::{encode_from_key_file, Claims},
      22              :     id::{NodeId, TenantId, TenantTimelineId, TimelineId},
      23              : };
      24              : 
      25              : use crate::safekeeper::SafekeeperNode;
      26              : 
      27              : pub const DEFAULT_PG_VERSION: u32 = 15;
      28              : 
      29              : //
      30              : // This data structures represents neon_local CLI config
      31              : //
      32              : // It is deserialized from the .neon/config file, or the config file passed
      33              : // to 'neon_local init --config=<path>' option. See control_plane/simple.conf for
      34              : // an example.
      35              : //
      36           30 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
      37              : pub struct LocalEnv {
      38              :     // Base directory for all the nodes (the pageserver, safekeepers and
      39              :     // compute endpoints).
      40              :     //
      41              :     // This is not stored in the config file. Rather, this is the path where the
      42              :     // config file itself is. It is read from the NEON_REPO_DIR env variable or
      43              :     // '.neon' if not given.
      44              :     #[serde(skip)]
      45              :     pub base_data_dir: PathBuf,
      46              : 
      47              :     // Path to postgres distribution. It's expected that "bin", "include",
      48              :     // "lib", "share" from postgres distribution are there. If at some point
      49              :     // in time we will be able to run against vanilla postgres we may split that
      50              :     // to four separate paths and match OS-specific installation layout.
      51              :     #[serde(default)]
      52              :     pub pg_distrib_dir: PathBuf,
      53              : 
      54              :     // Path to pageserver binary.
      55              :     #[serde(default)]
      56              :     pub neon_distrib_dir: PathBuf,
      57              : 
      58              :     // Default tenant ID to use with the 'neon_local' command line utility, when
      59              :     // --tenant_id is not explicitly specified.
      60              :     #[serde(default)]
      61              :     pub default_tenant_id: Option<TenantId>,
      62              : 
      63              :     // used to issue tokens during e.g pg start
      64              :     #[serde(default)]
      65              :     pub private_key_path: PathBuf,
      66              : 
      67              :     pub broker: NeonBroker,
      68              : 
      69              :     /// This Vec must always contain at least one pageserver
      70              :     pub pageservers: Vec<PageServerConf>,
      71              : 
      72              :     #[serde(default)]
      73              :     pub safekeepers: Vec<SafekeeperConf>,
      74              : 
      75              :     // Control plane upcall API for pageserver: if None, we will not run storage_controller  If set, this will
      76              :     // be propagated into each pageserver's configuration.
      77              :     #[serde(default)]
      78              :     pub control_plane_api: Option<Url>,
      79              : 
      80              :     // Control plane upcall API for storage controller.  If set, this will be propagated into the
      81              :     // storage controller's configuration.
      82              :     #[serde(default)]
      83              :     pub control_plane_compute_hook_api: Option<Url>,
      84              : 
      85              :     /// Keep human-readable aliases in memory (and persist them to config), to hide ZId hex strings from the user.
      86              :     #[serde(default)]
      87              :     // A `HashMap<String, HashMap<TenantId, TimelineId>>` would be more appropriate here,
      88              :     // but deserialization into a generic toml object as `toml::Value::try_from` fails with an error.
      89              :     // https://toml.io/en/v1.0.0 does not contain a concept of "a table inside another table".
      90              :     branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
      91              : }
      92              : 
      93              : /// Broker config for cluster internal communication.
      94           14 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
      95              : #[serde(default)]
      96              : pub struct NeonBroker {
      97              :     /// Broker listen address for storage nodes coordination, e.g. '127.0.0.1:50051'.
      98              :     pub listen_addr: SocketAddr,
      99              : }
     100              : 
     101              : // Dummy Default impl to satisfy Deserialize derive.
     102              : impl Default for NeonBroker {
     103            2 :     fn default() -> Self {
     104            2 :         NeonBroker {
     105            2 :             listen_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0),
     106            2 :         }
     107            2 :     }
     108              : }
     109              : 
     110              : impl NeonBroker {
     111            0 :     pub fn client_url(&self) -> Url {
     112            0 :         Url::parse(&format!("http://{}", self.listen_addr)).expect("failed to construct url")
     113            0 :     }
     114              : }
     115              : 
     116           44 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     117              : #[serde(default, deny_unknown_fields)]
     118              : pub struct PageServerConf {
     119              :     // node id
     120              :     pub id: NodeId,
     121              : 
     122              :     // Pageserver connection settings
     123              :     pub listen_pg_addr: String,
     124              :     pub listen_http_addr: String,
     125              : 
     126              :     // auth type used for the PG and HTTP ports
     127              :     pub pg_auth_type: AuthType,
     128              :     pub http_auth_type: AuthType,
     129              : 
     130              :     pub(crate) virtual_file_io_engine: Option<String>,
     131              :     pub(crate) get_vectored_impl: Option<String>,
     132              : }
     133              : 
     134              : impl Default for PageServerConf {
     135            4 :     fn default() -> Self {
     136            4 :         Self {
     137            4 :             id: NodeId(0),
     138            4 :             listen_pg_addr: String::new(),
     139            4 :             listen_http_addr: String::new(),
     140            4 :             pg_auth_type: AuthType::Trust,
     141            4 :             http_auth_type: AuthType::Trust,
     142            4 :             virtual_file_io_engine: None,
     143            4 :             get_vectored_impl: None,
     144            4 :         }
     145            4 :     }
     146              : }
     147              : 
     148           28 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     149              : #[serde(default)]
     150              : pub struct SafekeeperConf {
     151              :     pub id: NodeId,
     152              :     pub pg_port: u16,
     153              :     pub pg_tenant_only_port: Option<u16>,
     154              :     pub http_port: u16,
     155              :     pub sync: bool,
     156              :     pub remote_storage: Option<String>,
     157              :     pub backup_threads: Option<u32>,
     158              :     pub auth_enabled: bool,
     159              : }
     160              : 
     161              : impl Default for SafekeeperConf {
     162            4 :     fn default() -> Self {
     163            4 :         Self {
     164            4 :             id: NodeId(0),
     165            4 :             pg_port: 0,
     166            4 :             pg_tenant_only_port: None,
     167            4 :             http_port: 0,
     168            4 :             sync: true,
     169            4 :             remote_storage: None,
     170            4 :             backup_threads: None,
     171            4 :             auth_enabled: false,
     172            4 :         }
     173            4 :     }
     174              : }
     175              : 
     176              : #[derive(Clone, Copy)]
     177              : pub enum InitForceMode {
     178              :     MustNotExist,
     179              :     EmptyDirOk,
     180              :     RemoveAllContents,
     181              : }
     182              : 
     183              : impl ValueEnum for InitForceMode {
     184            4 :     fn value_variants<'a>() -> &'a [Self] {
     185            4 :         &[
     186            4 :             Self::MustNotExist,
     187            4 :             Self::EmptyDirOk,
     188            4 :             Self::RemoveAllContents,
     189            4 :         ]
     190            4 :     }
     191              : 
     192           10 :     fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
     193           10 :         Some(clap::builder::PossibleValue::new(match self {
     194            6 :             InitForceMode::MustNotExist => "must-not-exist",
     195            2 :             InitForceMode::EmptyDirOk => "empty-dir-ok",
     196            2 :             InitForceMode::RemoveAllContents => "remove-all-contents",
     197              :         }))
     198           10 :     }
     199              : }
     200              : 
     201              : impl SafekeeperConf {
     202              :     /// Compute is served by port on which only tenant scoped tokens allowed, if
     203              :     /// it is configured.
     204            0 :     pub fn get_compute_port(&self) -> u16 {
     205            0 :         self.pg_tenant_only_port.unwrap_or(self.pg_port)
     206            0 :     }
     207              : }
     208              : 
     209              : impl LocalEnv {
     210            0 :     pub fn pg_distrib_dir_raw(&self) -> PathBuf {
     211            0 :         self.pg_distrib_dir.clone()
     212            0 :     }
     213              : 
     214            0 :     pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     215            0 :         let path = self.pg_distrib_dir.clone();
     216            0 : 
     217            0 :         #[allow(clippy::manual_range_patterns)]
     218            0 :         match pg_version {
     219            0 :             14 | 15 | 16 => Ok(path.join(format!("v{pg_version}"))),
     220            0 :             _ => bail!("Unsupported postgres version: {}", pg_version),
     221              :         }
     222            0 :     }
     223              : 
     224            0 :     pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     225            0 :         Ok(self.pg_distrib_dir(pg_version)?.join("bin"))
     226            0 :     }
     227            0 :     pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     228            0 :         Ok(self.pg_distrib_dir(pg_version)?.join("lib"))
     229            0 :     }
     230              : 
     231            0 :     pub fn pageserver_bin(&self) -> PathBuf {
     232            0 :         self.neon_distrib_dir.join("pageserver")
     233            0 :     }
     234              : 
     235            0 :     pub fn storage_controller_bin(&self) -> PathBuf {
     236            0 :         // Irrespective of configuration, storage controller binary is always
     237            0 :         // run from the same location as neon_local.  This means that for compatibility
     238            0 :         // tests that run old pageserver/safekeeper, they still run latest storage controller.
     239            0 :         let neon_local_bin_dir = env::current_exe().unwrap().parent().unwrap().to_owned();
     240            0 :         neon_local_bin_dir.join("storage_controller")
     241            0 :     }
     242              : 
     243            0 :     pub fn safekeeper_bin(&self) -> PathBuf {
     244            0 :         self.neon_distrib_dir.join("safekeeper")
     245            0 :     }
     246              : 
     247            0 :     pub fn storage_broker_bin(&self) -> PathBuf {
     248            0 :         self.neon_distrib_dir.join("storage_broker")
     249            0 :     }
     250              : 
     251            0 :     pub fn endpoints_path(&self) -> PathBuf {
     252            0 :         self.base_data_dir.join("endpoints")
     253            0 :     }
     254              : 
     255            0 :     pub fn pageserver_data_dir(&self, pageserver_id: NodeId) -> PathBuf {
     256            0 :         self.base_data_dir
     257            0 :             .join(format!("pageserver_{pageserver_id}"))
     258            0 :     }
     259              : 
     260            0 :     pub fn safekeeper_data_dir(&self, data_dir_name: &str) -> PathBuf {
     261            0 :         self.base_data_dir.join("safekeepers").join(data_dir_name)
     262            0 :     }
     263              : 
     264            0 :     pub fn get_pageserver_conf(&self, id: NodeId) -> anyhow::Result<&PageServerConf> {
     265            0 :         if let Some(conf) = self.pageservers.iter().find(|node| node.id == id) {
     266            0 :             Ok(conf)
     267              :         } else {
     268            0 :             let have_ids = self
     269            0 :                 .pageservers
     270            0 :                 .iter()
     271            0 :                 .map(|node| format!("{}:{}", node.id, node.listen_http_addr))
     272            0 :                 .collect::<Vec<_>>();
     273            0 :             let joined = have_ids.join(",");
     274            0 :             bail!("could not find pageserver {id}, have ids {joined}")
     275              :         }
     276            0 :     }
     277              : 
     278            0 :     pub fn register_branch_mapping(
     279            0 :         &mut self,
     280            0 :         branch_name: String,
     281            0 :         tenant_id: TenantId,
     282            0 :         timeline_id: TimelineId,
     283            0 :     ) -> anyhow::Result<()> {
     284            0 :         let existing_values = self
     285            0 :             .branch_name_mappings
     286            0 :             .entry(branch_name.clone())
     287            0 :             .or_default();
     288            0 : 
     289            0 :         let existing_ids = existing_values
     290            0 :             .iter()
     291            0 :             .find(|(existing_tenant_id, _)| existing_tenant_id == &tenant_id);
     292              : 
     293            0 :         if let Some((_, old_timeline_id)) = existing_ids {
     294            0 :             if old_timeline_id == &timeline_id {
     295            0 :                 Ok(())
     296              :             } else {
     297            0 :                 bail!("branch '{branch_name}' is already mapped to timeline {old_timeline_id}, cannot map to another timeline {timeline_id}");
     298              :             }
     299              :         } else {
     300            0 :             existing_values.push((tenant_id, timeline_id));
     301            0 :             Ok(())
     302              :         }
     303            0 :     }
     304              : 
     305            0 :     pub fn get_branch_timeline_id(
     306            0 :         &self,
     307            0 :         branch_name: &str,
     308            0 :         tenant_id: TenantId,
     309            0 :     ) -> Option<TimelineId> {
     310            0 :         self.branch_name_mappings
     311            0 :             .get(branch_name)?
     312            0 :             .iter()
     313            0 :             .find(|(mapped_tenant_id, _)| mapped_tenant_id == &tenant_id)
     314            0 :             .map(|&(_, timeline_id)| timeline_id)
     315            0 :             .map(TimelineId::from)
     316            0 :     }
     317              : 
     318            0 :     pub fn timeline_name_mappings(&self) -> HashMap<TenantTimelineId, String> {
     319            0 :         self.branch_name_mappings
     320            0 :             .iter()
     321            0 :             .flat_map(|(name, tenant_timelines)| {
     322            0 :                 tenant_timelines.iter().map(|&(tenant_id, timeline_id)| {
     323            0 :                     (TenantTimelineId::new(tenant_id, timeline_id), name.clone())
     324            0 :                 })
     325            0 :             })
     326            0 :             .collect()
     327            0 :     }
     328              : 
     329              :     /// Create a LocalEnv from a config file.
     330              :     ///
     331              :     /// Unlike 'load_config', this function fills in any defaults that are missing
     332              :     /// from the config file.
     333            4 :     pub fn parse_config(toml: &str) -> anyhow::Result<Self> {
     334            4 :         let mut env: LocalEnv = toml::from_str(toml)?;
     335              : 
     336              :         // Find postgres binaries.
     337              :         // Follow POSTGRES_DISTRIB_DIR if set, otherwise look in "pg_install".
     338              :         // Note that later in the code we assume, that distrib dirs follow the same pattern
     339              :         // for all postgres versions.
     340            2 :         if env.pg_distrib_dir == Path::new("") {
     341            2 :             if let Some(postgres_bin) = env::var_os("POSTGRES_DISTRIB_DIR") {
     342            0 :                 env.pg_distrib_dir = postgres_bin.into();
     343            0 :             } else {
     344            2 :                 let cwd = env::current_dir()?;
     345            2 :                 env.pg_distrib_dir = cwd.join("pg_install")
     346              :             }
     347            0 :         }
     348              : 
     349              :         // Find neon binaries.
     350            2 :         if env.neon_distrib_dir == Path::new("") {
     351            2 :             env.neon_distrib_dir = env::current_exe()?.parent().unwrap().to_owned();
     352            0 :         }
     353              : 
     354            2 :         if env.pageservers.is_empty() {
     355            0 :             anyhow::bail!("Configuration must contain at least one pageserver");
     356            2 :         }
     357            2 : 
     358            2 :         env.base_data_dir = base_path();
     359            2 : 
     360            2 :         Ok(env)
     361            4 :     }
     362              : 
     363              :     /// Locate and load config
     364            0 :     pub fn load_config() -> anyhow::Result<Self> {
     365            0 :         let repopath = base_path();
     366            0 : 
     367            0 :         if !repopath.exists() {
     368            0 :             bail!(
     369            0 :                 "Neon config is not found in {}. You need to run 'neon_local init' first",
     370            0 :                 repopath.to_str().unwrap()
     371            0 :             );
     372            0 :         }
     373              : 
     374              :         // TODO: check that it looks like a neon repository
     375              : 
     376              :         // load and parse file
     377            0 :         let config = fs::read_to_string(repopath.join("config"))?;
     378            0 :         let mut env: LocalEnv = toml::from_str(config.as_str())?;
     379              : 
     380            0 :         env.base_data_dir = repopath;
     381            0 : 
     382            0 :         Ok(env)
     383            0 :     }
     384              : 
     385            0 :     pub fn persist_config(&self, base_path: &Path) -> anyhow::Result<()> {
     386            0 :         // Currently, the user first passes a config file with 'neon_local init --config=<path>'
     387            0 :         // We read that in, in `create_config`, and fill any missing defaults. Then it's saved
     388            0 :         // to .neon/config. TODO: We lose any formatting and comments along the way, which is
     389            0 :         // a bit sad.
     390            0 :         let mut conf_content = r#"# This file describes a local deployment of the page server
     391            0 : # and safekeeeper node. It is read by the 'neon_local' command-line
     392            0 : # utility.
     393            0 : "#
     394            0 :         .to_string();
     395            0 : 
     396            0 :         // Convert the LocalEnv to a toml file.
     397            0 :         //
     398            0 :         // This could be as simple as this:
     399            0 :         //
     400            0 :         // conf_content += &toml::to_string_pretty(env)?;
     401            0 :         //
     402            0 :         // But it results in a "values must be emitted before tables". I'm not sure
     403            0 :         // why, AFAICS the table, i.e. 'safekeepers: Vec<SafekeeperConf>' is last.
     404            0 :         // Maybe rust reorders the fields to squeeze avoid padding or something?
     405            0 :         // In any case, converting to toml::Value first, and serializing that, works.
     406            0 :         // See https://github.com/alexcrichton/toml-rs/issues/142
     407            0 :         conf_content += &toml::to_string_pretty(&toml::Value::try_from(self)?)?;
     408              : 
     409            0 :         let target_config_path = base_path.join("config");
     410            0 :         fs::write(&target_config_path, conf_content).with_context(|| {
     411            0 :             format!(
     412            0 :                 "Failed to write config file into path '{}'",
     413            0 :                 target_config_path.display()
     414            0 :             )
     415            0 :         })
     416            0 :     }
     417              : 
     418              :     // this function is used only for testing purposes in CLI e g generate tokens during init
     419            0 :     pub fn generate_auth_token(&self, claims: &Claims) -> anyhow::Result<String> {
     420            0 :         let private_key_path = self.get_private_key_path();
     421            0 :         let key_data = fs::read(private_key_path)?;
     422            0 :         encode_from_key_file(claims, &key_data)
     423            0 :     }
     424              : 
     425            0 :     pub fn get_private_key_path(&self) -> PathBuf {
     426            0 :         if self.private_key_path.is_absolute() {
     427            0 :             self.private_key_path.to_path_buf()
     428              :         } else {
     429            0 :             self.base_data_dir.join(&self.private_key_path)
     430              :         }
     431            0 :     }
     432              : 
     433              :     //
     434              :     // Initialize a new Neon repository
     435              :     //
     436            0 :     pub fn init(&mut self, pg_version: u32, force: &InitForceMode) -> anyhow::Result<()> {
     437            0 :         // check if config already exists
     438            0 :         let base_path = &self.base_data_dir;
     439            0 :         ensure!(
     440            0 :             base_path != Path::new(""),
     441            0 :             "repository base path is missing"
     442              :         );
     443              : 
     444            0 :         if base_path.exists() {
     445            0 :             match force {
     446              :                 InitForceMode::MustNotExist => {
     447            0 :                     bail!(
     448            0 :                         "directory '{}' already exists. Perhaps already initialized?",
     449            0 :                         base_path.display()
     450            0 :                     );
     451              :                 }
     452              :                 InitForceMode::EmptyDirOk => {
     453            0 :                     if let Some(res) = std::fs::read_dir(base_path)?.next() {
     454            0 :                         res.context("check if directory is empty")?;
     455            0 :                         anyhow::bail!("directory not empty: {base_path:?}");
     456            0 :                     }
     457              :                 }
     458              :                 InitForceMode::RemoveAllContents => {
     459            0 :                     println!("removing all contents of '{}'", base_path.display());
     460              :                     // instead of directly calling `remove_dir_all`, we keep the original dir but removing
     461              :                     // all contents inside. This helps if the developer symbol links another directory (i.e.,
     462              :                     // S3 local SSD) to the `.neon` base directory.
     463            0 :                     for entry in std::fs::read_dir(base_path)? {
     464            0 :                         let entry = entry?;
     465            0 :                         let path = entry.path();
     466            0 :                         if path.is_dir() {
     467            0 :                             fs::remove_dir_all(&path)?;
     468              :                         } else {
     469            0 :                             fs::remove_file(&path)?;
     470              :                         }
     471              :                     }
     472              :                 }
     473              :             }
     474            0 :         }
     475              : 
     476            0 :         if !self.pg_bin_dir(pg_version)?.join("postgres").exists() {
     477            0 :             bail!(
     478            0 :                 "Can't find postgres binary at {}",
     479            0 :                 self.pg_bin_dir(pg_version)?.display()
     480              :             );
     481            0 :         }
     482            0 :         for binary in ["pageserver", "safekeeper"] {
     483            0 :             if !self.neon_distrib_dir.join(binary).exists() {
     484            0 :                 bail!(
     485            0 :                     "Can't find binary '{binary}' in neon distrib dir '{}'",
     486            0 :                     self.neon_distrib_dir.display()
     487            0 :                 );
     488            0 :             }
     489              :         }
     490              : 
     491            0 :         if !base_path.exists() {
     492            0 :             fs::create_dir(base_path)?;
     493            0 :         }
     494              : 
     495              :         // Generate keypair for JWT.
     496              :         //
     497              :         // The keypair is only needed if authentication is enabled in any of the
     498              :         // components. For convenience, we generate the keypair even if authentication
     499              :         // is not enabled, so that you can easily enable it after the initialization
     500              :         // step. However, if the key generation fails, we treat it as non-fatal if
     501              :         // authentication was not enabled.
     502            0 :         if self.private_key_path == PathBuf::new() {
     503            0 :             match generate_auth_keys(
     504            0 :                 base_path.join("auth_private_key.pem").as_path(),
     505            0 :                 base_path.join("auth_public_key.pem").as_path(),
     506            0 :             ) {
     507            0 :                 Ok(()) => {
     508            0 :                     self.private_key_path = PathBuf::from("auth_private_key.pem");
     509            0 :                 }
     510            0 :                 Err(e) => {
     511            0 :                     if !self.auth_keys_needed() {
     512            0 :                         eprintln!("Could not generate keypair for JWT authentication: {e}");
     513            0 :                         eprintln!("Continuing anyway because authentication was not enabled");
     514            0 :                         self.private_key_path = PathBuf::from("auth_private_key.pem");
     515            0 :                     } else {
     516            0 :                         return Err(e);
     517              :                     }
     518              :                 }
     519              :             }
     520            0 :         }
     521              : 
     522            0 :         fs::create_dir_all(self.endpoints_path())?;
     523              : 
     524            0 :         for safekeeper in &self.safekeepers {
     525            0 :             fs::create_dir_all(SafekeeperNode::datadir_path_by_id(self, safekeeper.id))?;
     526              :         }
     527              : 
     528            0 :         self.persist_config(base_path)
     529            0 :     }
     530              : 
     531            0 :     fn auth_keys_needed(&self) -> bool {
     532            0 :         self.pageservers.iter().any(|ps| {
     533            0 :             ps.pg_auth_type == AuthType::NeonJWT || ps.http_auth_type == AuthType::NeonJWT
     534            0 :         }) || self.safekeepers.iter().any(|sk| sk.auth_enabled)
     535            0 :     }
     536              : }
     537              : 
     538            2 : fn base_path() -> PathBuf {
     539            2 :     match std::env::var_os("NEON_REPO_DIR") {
     540            0 :         Some(val) => PathBuf::from(val),
     541            2 :         None => PathBuf::from(".neon"),
     542              :     }
     543            2 : }
     544              : 
     545              : /// Generate a public/private key pair for JWT authentication
     546            0 : fn generate_auth_keys(private_key_path: &Path, public_key_path: &Path) -> anyhow::Result<()> {
     547              :     // Generate the key pair
     548              :     //
     549              :     // openssl genpkey -algorithm ed25519 -out auth_private_key.pem
     550            0 :     let keygen_output = Command::new("openssl")
     551            0 :         .arg("genpkey")
     552            0 :         .args(["-algorithm", "ed25519"])
     553            0 :         .args(["-out", private_key_path.to_str().unwrap()])
     554            0 :         .stdout(Stdio::null())
     555            0 :         .output()
     556            0 :         .context("failed to generate auth private key")?;
     557            0 :     if !keygen_output.status.success() {
     558            0 :         bail!(
     559            0 :             "openssl failed: '{}'",
     560            0 :             String::from_utf8_lossy(&keygen_output.stderr)
     561            0 :         );
     562            0 :     }
     563              :     // Extract the public key from the private key file
     564              :     //
     565              :     // openssl pkey -in auth_private_key.pem -pubout -out auth_public_key.pem
     566            0 :     let keygen_output = Command::new("openssl")
     567            0 :         .arg("pkey")
     568            0 :         .args(["-in", private_key_path.to_str().unwrap()])
     569            0 :         .arg("-pubout")
     570            0 :         .args(["-out", public_key_path.to_str().unwrap()])
     571            0 :         .output()
     572            0 :         .context("failed to extract public key from private key")?;
     573            0 :     if !keygen_output.status.success() {
     574            0 :         bail!(
     575            0 :             "openssl failed: '{}'",
     576            0 :             String::from_utf8_lossy(&keygen_output.stderr)
     577            0 :         );
     578            0 :     }
     579            0 :     Ok(())
     580            0 : }
     581              : 
     582              : #[cfg(test)]
     583              : mod tests {
     584              :     use super::*;
     585              : 
     586              :     #[test]
     587            2 :     fn simple_conf_parsing() {
     588            2 :         let simple_conf_toml = include_str!("../simple.conf");
     589            2 :         let simple_conf_parse_result = LocalEnv::parse_config(simple_conf_toml);
     590            2 :         assert!(
     591            2 :             simple_conf_parse_result.is_ok(),
     592            0 :             "failed to parse simple config {simple_conf_toml}, reason: {simple_conf_parse_result:?}"
     593              :         );
     594              : 
     595            2 :         let string_to_replace = "listen_addr = '127.0.0.1:50051'";
     596            2 :         let spoiled_url_str = "listen_addr = '!@$XOXO%^&'";
     597            2 :         let spoiled_url_toml = simple_conf_toml.replace(string_to_replace, spoiled_url_str);
     598            2 :         assert!(
     599            2 :             spoiled_url_toml.contains(spoiled_url_str),
     600            0 :             "Failed to replace string {string_to_replace} in the toml file {simple_conf_toml}"
     601              :         );
     602            2 :         let spoiled_url_parse_result = LocalEnv::parse_config(&spoiled_url_toml);
     603            2 :         assert!(
     604            2 :             spoiled_url_parse_result.is_err(),
     605            0 :             "expected toml with invalid Url {spoiled_url_toml} to fail the parsing, but got {spoiled_url_parse_result:?}"
     606              :         );
     607            2 :     }
     608              : }
        

Generated by: LCOV version 2.1-beta