LCOV - code coverage report
Current view: top level - control_plane/src - local_env.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 0.0 % 689 0
Test Date: 2025-05-26 10:37:33 Functions: 0.0 % 160 0

            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 std::collections::HashMap;
       7              : use std::net::SocketAddr;
       8              : use std::path::{Path, PathBuf};
       9              : use std::process::{Command, Stdio};
      10              : use std::time::Duration;
      11              : use std::{env, fs};
      12              : 
      13              : use anyhow::{Context, bail};
      14              : use clap::ValueEnum;
      15              : use pem::Pem;
      16              : use postgres_backend::AuthType;
      17              : use reqwest::{Certificate, Url};
      18              : use serde::{Deserialize, Serialize};
      19              : use utils::auth::encode_from_key_file;
      20              : use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId};
      21              : 
      22              : use crate::broker::StorageBroker;
      23              : use crate::endpoint_storage::{
      24              :     ENDPOINT_STORAGE_DEFAULT_ADDR, ENDPOINT_STORAGE_REMOTE_STORAGE_DIR, EndpointStorage,
      25              : };
      26              : use crate::pageserver::{PAGESERVER_REMOTE_STORAGE_DIR, PageServerNode};
      27              : use crate::safekeeper::SafekeeperNode;
      28              : 
      29              : pub const DEFAULT_PG_VERSION: u32 = 17;
      30              : 
      31              : //
      32              : // This data structures represents neon_local CLI config
      33              : //
      34              : // It is deserialized from the .neon/config file, or the config file passed
      35              : // to 'neon_local init --config=<path>' option. See control_plane/simple.conf for
      36              : // an example.
      37              : //
      38              : #[derive(PartialEq, Eq, Clone, Debug)]
      39              : pub struct LocalEnv {
      40              :     // Base directory for all the nodes (the pageserver, safekeepers and
      41              :     // compute endpoints).
      42              :     //
      43              :     // This is not stored in the config file. Rather, this is the path where the
      44              :     // config file itself is. It is read from the NEON_REPO_DIR env variable which
      45              :     // must be an absolute path. If the env var is not set, $PWD/.neon is used.
      46              :     pub base_data_dir: PathBuf,
      47              : 
      48              :     // Path to postgres distribution. It's expected that "bin", "include",
      49              :     // "lib", "share" from postgres distribution are there. If at some point
      50              :     // in time we will be able to run against vanilla postgres we may split that
      51              :     // to four separate paths and match OS-specific installation layout.
      52              :     pub pg_distrib_dir: PathBuf,
      53              : 
      54              :     // Path to pageserver binary.
      55              :     pub neon_distrib_dir: PathBuf,
      56              : 
      57              :     // Default tenant ID to use with the 'neon_local' command line utility, when
      58              :     // --tenant_id is not explicitly specified.
      59              :     pub default_tenant_id: Option<TenantId>,
      60              : 
      61              :     // used to issue tokens during e.g pg start
      62              :     pub private_key_path: PathBuf,
      63              :     /// Path to environment's public key
      64              :     pub public_key_path: PathBuf,
      65              : 
      66              :     pub broker: NeonBroker,
      67              : 
      68              :     // Configuration for the storage controller (1 per neon_local environment)
      69              :     pub storage_controller: NeonStorageControllerConf,
      70              : 
      71              :     /// This Vec must always contain at least one pageserver
      72              :     /// Populdated by [`Self::load_config`] from the individual `pageserver.toml`s.
      73              :     /// NB: not used anymore except for informing users that they need to change their `.neon/config`.
      74              :     pub pageservers: Vec<PageServerConf>,
      75              : 
      76              :     pub safekeepers: Vec<SafekeeperConf>,
      77              : 
      78              :     pub endpoint_storage: EndpointStorageConf,
      79              : 
      80              :     // Control plane upcall API for pageserver: if None, we will not run storage_controller  If set, this will
      81              :     // be propagated into each pageserver's configuration.
      82              :     pub control_plane_api: Url,
      83              : 
      84              :     // Control plane upcall APIs for storage controller.  If set, this will be propagated into the
      85              :     // storage controller's configuration.
      86              :     pub control_plane_hooks_api: Option<Url>,
      87              : 
      88              :     /// Keep human-readable aliases in memory (and persist them to config), to hide ZId hex strings from the user.
      89              :     // A `HashMap<String, HashMap<TenantId, TimelineId>>` would be more appropriate here,
      90              :     // but deserialization into a generic toml object as `toml::Value::try_from` fails with an error.
      91              :     // https://toml.io/en/v1.0.0 does not contain a concept of "a table inside another table".
      92              :     pub branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
      93              : 
      94              :     /// Flag to generate SSL certificates for components that need it.
      95              :     /// Also generates root CA certificate that is used to sign all other certificates.
      96              :     pub generate_local_ssl_certs: bool,
      97              : }
      98              : 
      99              : /// On-disk state stored in `.neon/config`.
     100            0 : #[derive(PartialEq, Eq, Clone, Debug, Default, Serialize, Deserialize)]
     101              : #[serde(default, deny_unknown_fields)]
     102              : pub struct OnDiskConfig {
     103              :     pub pg_distrib_dir: PathBuf,
     104              :     pub neon_distrib_dir: PathBuf,
     105              :     pub default_tenant_id: Option<TenantId>,
     106              :     pub private_key_path: PathBuf,
     107              :     pub public_key_path: PathBuf,
     108              :     pub broker: NeonBroker,
     109              :     pub storage_controller: NeonStorageControllerConf,
     110              :     #[serde(
     111              :         skip_serializing,
     112              :         deserialize_with = "fail_if_pageservers_field_specified"
     113              :     )]
     114              :     pub pageservers: Vec<PageServerConf>,
     115              :     pub safekeepers: Vec<SafekeeperConf>,
     116              :     pub endpoint_storage: EndpointStorageConf,
     117              :     pub control_plane_api: Option<Url>,
     118              :     pub control_plane_hooks_api: Option<Url>,
     119              :     pub control_plane_compute_hook_api: Option<Url>,
     120              :     branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
     121              :     // Note: skip serializing because in compat tests old storage controller fails
     122              :     // to load new config file. May be removed after this field is in release branch.
     123              :     #[serde(skip_serializing_if = "std::ops::Not::not")]
     124              :     pub generate_local_ssl_certs: bool,
     125              : }
     126              : 
     127            0 : fn fail_if_pageservers_field_specified<'de, D>(_: D) -> Result<Vec<PageServerConf>, D::Error>
     128            0 : where
     129            0 :     D: serde::Deserializer<'de>,
     130            0 : {
     131            0 :     Err(serde::de::Error::custom(
     132            0 :         "The 'pageservers' field is no longer used; pageserver.toml is now authoritative; \
     133            0 :          Please remove the `pageservers` from your .neon/config.",
     134            0 :     ))
     135            0 : }
     136              : 
     137              : /// The description of the neon_local env to be initialized by `neon_local init --config`.
     138            0 : #[derive(Clone, Debug, Deserialize)]
     139              : #[serde(deny_unknown_fields)]
     140              : pub struct NeonLocalInitConf {
     141              :     // TODO: do we need this? Seems unused
     142              :     pub pg_distrib_dir: Option<PathBuf>,
     143              :     // TODO: do we need this? Seems unused
     144              :     pub neon_distrib_dir: Option<PathBuf>,
     145              :     pub default_tenant_id: TenantId,
     146              :     pub broker: NeonBroker,
     147              :     pub storage_controller: Option<NeonStorageControllerConf>,
     148              :     pub pageservers: Vec<NeonLocalInitPageserverConf>,
     149              :     pub safekeepers: Vec<SafekeeperConf>,
     150              :     pub endpoint_storage: EndpointStorageConf,
     151              :     pub control_plane_api: Option<Url>,
     152              :     pub control_plane_hooks_api: Option<Url>,
     153              :     pub generate_local_ssl_certs: bool,
     154              : }
     155              : 
     156            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     157              : #[serde(default)]
     158              : pub struct EndpointStorageConf {
     159              :     pub listen_addr: SocketAddr,
     160              : }
     161              : 
     162              : /// Broker config for cluster internal communication.
     163            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Default)]
     164              : #[serde(default)]
     165              : pub struct NeonBroker {
     166              :     /// Broker listen HTTP address for storage nodes coordination, e.g. '127.0.0.1:50051'.
     167              :     /// At least one of listen_addr or listen_https_addr must be set.
     168              :     pub listen_addr: Option<SocketAddr>,
     169              :     /// Broker listen HTTPS address for storage nodes coordination, e.g. '127.0.0.1:50051'.
     170              :     /// At least one of listen_addr or listen_https_addr must be set.
     171              :     /// listen_https_addr is preferred over listen_addr in neon_local.
     172              :     pub listen_https_addr: Option<SocketAddr>,
     173              : }
     174              : 
     175              : /// A part of storage controller's config the neon_local knows about.
     176            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     177              : #[serde(default)]
     178              : pub struct NeonStorageControllerConf {
     179              :     /// Heartbeat timeout before marking a node offline
     180              :     #[serde(with = "humantime_serde")]
     181              :     pub max_offline: Duration,
     182              : 
     183              :     #[serde(with = "humantime_serde")]
     184              :     pub max_warming_up: Duration,
     185              : 
     186              :     pub start_as_candidate: bool,
     187              : 
     188              :     /// Database url used when running multiple storage controller instances
     189              :     pub database_url: Option<SocketAddr>,
     190              : 
     191              :     /// Thresholds for auto-splitting a tenant into shards.
     192              :     pub split_threshold: Option<u64>,
     193              :     pub max_split_shards: Option<u8>,
     194              :     pub initial_split_threshold: Option<u64>,
     195              :     pub initial_split_shards: Option<u8>,
     196              : 
     197              :     pub max_secondary_lag_bytes: Option<u64>,
     198              : 
     199              :     #[serde(with = "humantime_serde")]
     200              :     pub heartbeat_interval: Duration,
     201              : 
     202              :     #[serde(with = "humantime_serde")]
     203              :     pub long_reconcile_threshold: Option<Duration>,
     204              : 
     205              :     pub use_https_pageserver_api: bool,
     206              : 
     207              :     pub timelines_onto_safekeepers: bool,
     208              : 
     209              :     pub use_https_safekeeper_api: bool,
     210              : 
     211              :     pub use_local_compute_notifications: bool,
     212              : }
     213              : 
     214              : impl NeonStorageControllerConf {
     215              :     // Use a shorter pageserver unavailability interval than the default to speed up tests.
     216              :     const DEFAULT_MAX_OFFLINE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);
     217              : 
     218              :     const DEFAULT_MAX_WARMING_UP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
     219              : 
     220              :     // Very tight heartbeat interval to speed up tests
     221              :     const DEFAULT_HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000);
     222              : }
     223              : 
     224              : impl Default for NeonStorageControllerConf {
     225            0 :     fn default() -> Self {
     226            0 :         Self {
     227            0 :             max_offline: Self::DEFAULT_MAX_OFFLINE_INTERVAL,
     228            0 :             max_warming_up: Self::DEFAULT_MAX_WARMING_UP_INTERVAL,
     229            0 :             start_as_candidate: false,
     230            0 :             database_url: None,
     231            0 :             split_threshold: None,
     232            0 :             max_split_shards: None,
     233            0 :             initial_split_threshold: None,
     234            0 :             initial_split_shards: None,
     235            0 :             max_secondary_lag_bytes: None,
     236            0 :             heartbeat_interval: Self::DEFAULT_HEARTBEAT_INTERVAL,
     237            0 :             long_reconcile_threshold: None,
     238            0 :             use_https_pageserver_api: false,
     239            0 :             timelines_onto_safekeepers: false,
     240            0 :             use_https_safekeeper_api: false,
     241            0 :             use_local_compute_notifications: true,
     242            0 :         }
     243            0 :     }
     244              : }
     245              : 
     246              : impl Default for EndpointStorageConf {
     247            0 :     fn default() -> Self {
     248            0 :         Self {
     249            0 :             listen_addr: ENDPOINT_STORAGE_DEFAULT_ADDR,
     250            0 :         }
     251            0 :     }
     252              : }
     253              : 
     254              : impl NeonBroker {
     255            0 :     pub fn client_url(&self) -> Url {
     256            0 :         let url = if let Some(addr) = self.listen_https_addr {
     257            0 :             format!("https://{}", addr)
     258              :         } else {
     259            0 :             format!(
     260            0 :                 "http://{}",
     261            0 :                 self.listen_addr
     262            0 :                     .expect("at least one address should be set")
     263            0 :             )
     264              :         };
     265              : 
     266            0 :         Url::parse(&url).expect("failed to construct url")
     267            0 :     }
     268              : }
     269              : 
     270              : // neon_local needs to know this subset of pageserver configuration.
     271              : // For legacy reasons, this information is duplicated from `pageserver.toml` into `.neon/config`.
     272              : // It can get stale if `pageserver.toml` is changed.
     273              : // TODO(christian): don't store this at all in `.neon/config`, always load it from `pageserver.toml`
     274            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     275              : #[serde(default, deny_unknown_fields)]
     276              : pub struct PageServerConf {
     277              :     pub id: NodeId,
     278              :     pub listen_pg_addr: String,
     279              :     pub listen_http_addr: String,
     280              :     pub listen_https_addr: Option<String>,
     281              :     pub listen_grpc_addr: Option<String>,
     282              :     pub pg_auth_type: AuthType,
     283              :     pub http_auth_type: AuthType,
     284              :     pub grpc_auth_type: AuthType,
     285              :     pub no_sync: bool,
     286              : }
     287              : 
     288              : impl Default for PageServerConf {
     289            0 :     fn default() -> Self {
     290            0 :         Self {
     291            0 :             id: NodeId(0),
     292            0 :             listen_pg_addr: String::new(),
     293            0 :             listen_http_addr: String::new(),
     294            0 :             listen_https_addr: None,
     295            0 :             listen_grpc_addr: None,
     296            0 :             pg_auth_type: AuthType::Trust,
     297            0 :             http_auth_type: AuthType::Trust,
     298            0 :             grpc_auth_type: AuthType::Trust,
     299            0 :             no_sync: false,
     300            0 :         }
     301            0 :     }
     302              : }
     303              : 
     304              : /// The toml that can be passed to `neon_local init --config`.
     305              : /// This is a subset of the `pageserver.toml` configuration.
     306              : // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656)
     307            0 : #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
     308              : pub struct NeonLocalInitPageserverConf {
     309              :     pub id: NodeId,
     310              :     pub listen_pg_addr: String,
     311              :     pub listen_http_addr: String,
     312              :     pub listen_https_addr: Option<String>,
     313              :     pub listen_grpc_addr: Option<String>,
     314              :     pub pg_auth_type: AuthType,
     315              :     pub http_auth_type: AuthType,
     316              :     pub grpc_auth_type: AuthType,
     317              :     #[serde(default, skip_serializing_if = "std::ops::Not::not")]
     318              :     pub no_sync: bool,
     319              :     #[serde(flatten)]
     320              :     pub other: HashMap<String, toml::Value>,
     321              : }
     322              : 
     323              : impl From<&NeonLocalInitPageserverConf> for PageServerConf {
     324            0 :     fn from(conf: &NeonLocalInitPageserverConf) -> Self {
     325            0 :         let NeonLocalInitPageserverConf {
     326            0 :             id,
     327            0 :             listen_pg_addr,
     328            0 :             listen_http_addr,
     329            0 :             listen_https_addr,
     330            0 :             listen_grpc_addr,
     331            0 :             pg_auth_type,
     332            0 :             http_auth_type,
     333            0 :             grpc_auth_type,
     334            0 :             no_sync,
     335            0 :             other: _,
     336            0 :         } = conf;
     337            0 :         Self {
     338            0 :             id: *id,
     339            0 :             listen_pg_addr: listen_pg_addr.clone(),
     340            0 :             listen_http_addr: listen_http_addr.clone(),
     341            0 :             listen_https_addr: listen_https_addr.clone(),
     342            0 :             listen_grpc_addr: listen_grpc_addr.clone(),
     343            0 :             pg_auth_type: *pg_auth_type,
     344            0 :             grpc_auth_type: *grpc_auth_type,
     345            0 :             http_auth_type: *http_auth_type,
     346            0 :             no_sync: *no_sync,
     347            0 :         }
     348            0 :     }
     349              : }
     350              : 
     351            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     352              : #[serde(default)]
     353              : pub struct SafekeeperConf {
     354              :     pub id: NodeId,
     355              :     pub pg_port: u16,
     356              :     pub pg_tenant_only_port: Option<u16>,
     357              :     pub http_port: u16,
     358              :     pub https_port: Option<u16>,
     359              :     pub sync: bool,
     360              :     pub remote_storage: Option<String>,
     361              :     pub backup_threads: Option<u32>,
     362              :     pub auth_enabled: bool,
     363              :     pub listen_addr: Option<String>,
     364              : }
     365              : 
     366              : impl Default for SafekeeperConf {
     367            0 :     fn default() -> Self {
     368            0 :         Self {
     369            0 :             id: NodeId(0),
     370            0 :             pg_port: 0,
     371            0 :             pg_tenant_only_port: None,
     372            0 :             http_port: 0,
     373            0 :             https_port: None,
     374            0 :             sync: true,
     375            0 :             remote_storage: None,
     376            0 :             backup_threads: None,
     377            0 :             auth_enabled: false,
     378            0 :             listen_addr: None,
     379            0 :         }
     380            0 :     }
     381              : }
     382              : 
     383              : #[derive(Clone, Copy)]
     384              : pub enum InitForceMode {
     385              :     MustNotExist,
     386              :     EmptyDirOk,
     387              :     RemoveAllContents,
     388              : }
     389              : 
     390              : impl ValueEnum for InitForceMode {
     391            0 :     fn value_variants<'a>() -> &'a [Self] {
     392            0 :         &[
     393            0 :             Self::MustNotExist,
     394            0 :             Self::EmptyDirOk,
     395            0 :             Self::RemoveAllContents,
     396            0 :         ]
     397            0 :     }
     398              : 
     399            0 :     fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
     400            0 :         Some(clap::builder::PossibleValue::new(match self {
     401            0 :             InitForceMode::MustNotExist => "must-not-exist",
     402            0 :             InitForceMode::EmptyDirOk => "empty-dir-ok",
     403            0 :             InitForceMode::RemoveAllContents => "remove-all-contents",
     404              :         }))
     405            0 :     }
     406              : }
     407              : 
     408              : impl SafekeeperConf {
     409              :     /// Compute is served by port on which only tenant scoped tokens allowed, if
     410              :     /// it is configured.
     411            0 :     pub fn get_compute_port(&self) -> u16 {
     412            0 :         self.pg_tenant_only_port.unwrap_or(self.pg_port)
     413            0 :     }
     414              : }
     415              : 
     416              : impl LocalEnv {
     417            0 :     pub fn pg_distrib_dir_raw(&self) -> PathBuf {
     418            0 :         self.pg_distrib_dir.clone()
     419            0 :     }
     420              : 
     421            0 :     pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     422            0 :         let path = self.pg_distrib_dir.clone();
     423            0 : 
     424            0 :         #[allow(clippy::manual_range_patterns)]
     425            0 :         match pg_version {
     426            0 :             14 | 15 | 16 | 17 => Ok(path.join(format!("v{pg_version}"))),
     427            0 :             _ => bail!("Unsupported postgres version: {}", pg_version),
     428              :         }
     429            0 :     }
     430              : 
     431            0 :     pub fn pg_dir(&self, pg_version: u32, dir_name: &str) -> anyhow::Result<PathBuf> {
     432            0 :         Ok(self.pg_distrib_dir(pg_version)?.join(dir_name))
     433            0 :     }
     434              : 
     435            0 :     pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     436            0 :         self.pg_dir(pg_version, "bin")
     437            0 :     }
     438              : 
     439            0 :     pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     440            0 :         self.pg_dir(pg_version, "lib")
     441            0 :     }
     442              : 
     443            0 :     pub fn endpoint_storage_bin(&self) -> PathBuf {
     444            0 :         self.neon_distrib_dir.join("endpoint_storage")
     445            0 :     }
     446              : 
     447            0 :     pub fn pageserver_bin(&self) -> PathBuf {
     448            0 :         self.neon_distrib_dir.join("pageserver")
     449            0 :     }
     450              : 
     451            0 :     pub fn storage_controller_bin(&self) -> PathBuf {
     452            0 :         // Irrespective of configuration, storage controller binary is always
     453            0 :         // run from the same location as neon_local.  This means that for compatibility
     454            0 :         // tests that run old pageserver/safekeeper, they still run latest storage controller.
     455            0 :         let neon_local_bin_dir = env::current_exe().unwrap().parent().unwrap().to_owned();
     456            0 :         neon_local_bin_dir.join("storage_controller")
     457            0 :     }
     458              : 
     459            0 :     pub fn safekeeper_bin(&self) -> PathBuf {
     460            0 :         self.neon_distrib_dir.join("safekeeper")
     461            0 :     }
     462              : 
     463            0 :     pub fn storage_broker_bin(&self) -> PathBuf {
     464            0 :         self.neon_distrib_dir.join("storage_broker")
     465            0 :     }
     466              : 
     467            0 :     pub fn endpoints_path(&self) -> PathBuf {
     468            0 :         self.base_data_dir.join("endpoints")
     469            0 :     }
     470              : 
     471            0 :     pub fn storage_broker_data_dir(&self) -> PathBuf {
     472            0 :         self.base_data_dir.join("storage_broker")
     473            0 :     }
     474              : 
     475            0 :     pub fn pageserver_data_dir(&self, pageserver_id: NodeId) -> PathBuf {
     476            0 :         self.base_data_dir
     477            0 :             .join(format!("pageserver_{pageserver_id}"))
     478            0 :     }
     479              : 
     480            0 :     pub fn safekeeper_data_dir(&self, data_dir_name: &str) -> PathBuf {
     481            0 :         self.base_data_dir.join("safekeepers").join(data_dir_name)
     482            0 :     }
     483              : 
     484            0 :     pub fn endpoint_storage_data_dir(&self) -> PathBuf {
     485            0 :         self.base_data_dir.join("endpoint_storage")
     486            0 :     }
     487              : 
     488            0 :     pub fn get_pageserver_conf(&self, id: NodeId) -> anyhow::Result<&PageServerConf> {
     489            0 :         if let Some(conf) = self.pageservers.iter().find(|node| node.id == id) {
     490            0 :             Ok(conf)
     491              :         } else {
     492            0 :             let have_ids = self
     493            0 :                 .pageservers
     494            0 :                 .iter()
     495            0 :                 .map(|node| format!("{}:{}", node.id, node.listen_http_addr))
     496            0 :                 .collect::<Vec<_>>();
     497            0 :             let joined = have_ids.join(",");
     498            0 :             bail!("could not find pageserver {id}, have ids {joined}")
     499              :         }
     500            0 :     }
     501              : 
     502            0 :     pub fn ssl_ca_cert_path(&self) -> Option<PathBuf> {
     503            0 :         if self.generate_local_ssl_certs {
     504            0 :             Some(self.base_data_dir.join("rootCA.crt"))
     505              :         } else {
     506            0 :             None
     507              :         }
     508            0 :     }
     509              : 
     510            0 :     pub fn ssl_ca_key_path(&self) -> Option<PathBuf> {
     511            0 :         if self.generate_local_ssl_certs {
     512            0 :             Some(self.base_data_dir.join("rootCA.key"))
     513              :         } else {
     514            0 :             None
     515              :         }
     516            0 :     }
     517              : 
     518            0 :     pub fn generate_ssl_ca_cert(&self) -> anyhow::Result<()> {
     519            0 :         let cert_path = self.ssl_ca_cert_path().unwrap();
     520            0 :         let key_path = self.ssl_ca_key_path().unwrap();
     521            0 :         if !fs::exists(cert_path.as_path())? {
     522            0 :             generate_ssl_ca_cert(cert_path.as_path(), key_path.as_path())?;
     523            0 :         }
     524            0 :         Ok(())
     525            0 :     }
     526              : 
     527            0 :     pub fn generate_ssl_cert(&self, cert_path: &Path, key_path: &Path) -> anyhow::Result<()> {
     528            0 :         self.generate_ssl_ca_cert()?;
     529            0 :         generate_ssl_cert(
     530            0 :             cert_path,
     531            0 :             key_path,
     532            0 :             self.ssl_ca_cert_path().unwrap().as_path(),
     533            0 :             self.ssl_ca_key_path().unwrap().as_path(),
     534            0 :         )
     535            0 :     }
     536              : 
     537              :     /// Creates HTTP client with local SSL CA certificates.
     538            0 :     pub fn create_http_client(&self) -> reqwest::Client {
     539            0 :         let ssl_ca_certs = self.ssl_ca_cert_path().map(|ssl_ca_file| {
     540            0 :             let buf = std::fs::read(ssl_ca_file).expect("SSL CA file should exist");
     541            0 :             Certificate::from_pem_bundle(&buf).expect("SSL CA file should be valid")
     542            0 :         });
     543            0 : 
     544            0 :         let mut http_client = reqwest::Client::builder();
     545            0 :         for ssl_ca_cert in ssl_ca_certs.unwrap_or_default() {
     546            0 :             http_client = http_client.add_root_certificate(ssl_ca_cert);
     547            0 :         }
     548              : 
     549            0 :         http_client
     550            0 :             .build()
     551            0 :             .expect("HTTP client should construct with no error")
     552            0 :     }
     553              : 
     554              :     /// Inspect the base data directory and extract the instance id and instance directory path
     555              :     /// for all storage controller instances
     556            0 :     pub async fn storage_controller_instances(&self) -> std::io::Result<Vec<(u8, PathBuf)>> {
     557            0 :         let mut instances = Vec::default();
     558              : 
     559            0 :         let dir = std::fs::read_dir(self.base_data_dir.clone())?;
     560            0 :         for dentry in dir {
     561            0 :             let dentry = dentry?;
     562            0 :             let is_dir = dentry.metadata()?.is_dir();
     563            0 :             let filename = dentry.file_name().into_string().unwrap();
     564            0 :             let parsed_instance_id = match filename.strip_prefix("storage_controller_") {
     565            0 :                 Some(suffix) => suffix.parse::<u8>().ok(),
     566            0 :                 None => None,
     567              :             };
     568              : 
     569            0 :             let is_instance_dir = is_dir && parsed_instance_id.is_some();
     570              : 
     571            0 :             if !is_instance_dir {
     572            0 :                 continue;
     573            0 :             }
     574            0 : 
     575            0 :             instances.push((
     576            0 :                 parsed_instance_id.expect("Checked previously"),
     577            0 :                 dentry.path(),
     578            0 :             ));
     579              :         }
     580              : 
     581            0 :         Ok(instances)
     582            0 :     }
     583              : 
     584            0 :     pub fn register_branch_mapping(
     585            0 :         &mut self,
     586            0 :         branch_name: String,
     587            0 :         tenant_id: TenantId,
     588            0 :         timeline_id: TimelineId,
     589            0 :     ) -> anyhow::Result<()> {
     590            0 :         let existing_values = self
     591            0 :             .branch_name_mappings
     592            0 :             .entry(branch_name.clone())
     593            0 :             .or_default();
     594            0 : 
     595            0 :         let existing_ids = existing_values
     596            0 :             .iter()
     597            0 :             .find(|(existing_tenant_id, _)| existing_tenant_id == &tenant_id);
     598              : 
     599            0 :         if let Some((_, old_timeline_id)) = existing_ids {
     600            0 :             if old_timeline_id == &timeline_id {
     601            0 :                 Ok(())
     602              :             } else {
     603            0 :                 bail!(
     604            0 :                     "branch '{branch_name}' is already mapped to timeline {old_timeline_id}, cannot map to another timeline {timeline_id}"
     605            0 :                 );
     606              :             }
     607              :         } else {
     608            0 :             existing_values.push((tenant_id, timeline_id));
     609            0 :             Ok(())
     610              :         }
     611            0 :     }
     612              : 
     613            0 :     pub fn get_branch_timeline_id(
     614            0 :         &self,
     615            0 :         branch_name: &str,
     616            0 :         tenant_id: TenantId,
     617            0 :     ) -> Option<TimelineId> {
     618            0 :         self.branch_name_mappings
     619            0 :             .get(branch_name)?
     620            0 :             .iter()
     621            0 :             .find(|(mapped_tenant_id, _)| mapped_tenant_id == &tenant_id)
     622            0 :             .map(|&(_, timeline_id)| timeline_id)
     623            0 :     }
     624              : 
     625            0 :     pub fn timeline_name_mappings(&self) -> HashMap<TenantTimelineId, String> {
     626            0 :         self.branch_name_mappings
     627            0 :             .iter()
     628            0 :             .flat_map(|(name, tenant_timelines)| {
     629            0 :                 tenant_timelines.iter().map(|&(tenant_id, timeline_id)| {
     630            0 :                     (TenantTimelineId::new(tenant_id, timeline_id), name.clone())
     631            0 :                 })
     632            0 :             })
     633            0 :             .collect()
     634            0 :     }
     635              : 
     636              :     ///  Construct `Self` from on-disk state.
     637            0 :     pub fn load_config(repopath: &Path) -> anyhow::Result<Self> {
     638            0 :         if !repopath.exists() {
     639            0 :             bail!(
     640            0 :                 "Neon config is not found in {}. You need to run 'neon_local init' first",
     641            0 :                 repopath.to_str().unwrap()
     642            0 :             );
     643            0 :         }
     644              : 
     645              :         // TODO: check that it looks like a neon repository
     646              : 
     647              :         // load and parse file
     648            0 :         let config_file_contents = fs::read_to_string(repopath.join("config"))?;
     649            0 :         let on_disk_config: OnDiskConfig = toml::from_str(config_file_contents.as_str())?;
     650            0 :         let mut env = {
     651            0 :             let OnDiskConfig {
     652            0 :                 pg_distrib_dir,
     653            0 :                 neon_distrib_dir,
     654            0 :                 default_tenant_id,
     655            0 :                 private_key_path,
     656            0 :                 public_key_path,
     657            0 :                 broker,
     658            0 :                 storage_controller,
     659            0 :                 pageservers,
     660            0 :                 safekeepers,
     661            0 :                 control_plane_api,
     662            0 :                 control_plane_hooks_api,
     663            0 :                 control_plane_compute_hook_api: _,
     664            0 :                 branch_name_mappings,
     665            0 :                 generate_local_ssl_certs,
     666            0 :                 endpoint_storage,
     667            0 :             } = on_disk_config;
     668            0 :             LocalEnv {
     669            0 :                 base_data_dir: repopath.to_owned(),
     670            0 :                 pg_distrib_dir,
     671            0 :                 neon_distrib_dir,
     672            0 :                 default_tenant_id,
     673            0 :                 private_key_path,
     674            0 :                 public_key_path,
     675            0 :                 broker,
     676            0 :                 storage_controller,
     677            0 :                 pageservers,
     678            0 :                 safekeepers,
     679            0 :                 control_plane_api: control_plane_api.unwrap(),
     680            0 :                 control_plane_hooks_api,
     681            0 :                 branch_name_mappings,
     682            0 :                 generate_local_ssl_certs,
     683            0 :                 endpoint_storage,
     684            0 :             }
     685            0 :         };
     686            0 : 
     687            0 :         // The source of truth for pageserver configuration is the pageserver.toml.
     688            0 :         assert!(
     689            0 :             env.pageservers.is_empty(),
     690            0 :             "we ensure this during deserialization"
     691              :         );
     692            0 :         env.pageservers = {
     693            0 :             let iter = std::fs::read_dir(repopath).context("open dir")?;
     694            0 :             let mut pageservers = Vec::new();
     695            0 :             for res in iter {
     696            0 :                 let dentry = res?;
     697              :                 const PREFIX: &str = "pageserver_";
     698            0 :                 let dentry_name = dentry
     699            0 :                     .file_name()
     700            0 :                     .into_string()
     701            0 :                     .ok()
     702            0 :                     .with_context(|| format!("non-utf8 dentry: {:?}", dentry.path()))
     703            0 :                     .unwrap();
     704            0 :                 if !dentry_name.starts_with(PREFIX) {
     705            0 :                     continue;
     706            0 :                 }
     707            0 :                 if !dentry.file_type().context("determine file type")?.is_dir() {
     708            0 :                     anyhow::bail!("expected a directory, got {:?}", dentry.path());
     709            0 :                 }
     710            0 :                 let id = dentry_name[PREFIX.len()..]
     711            0 :                     .parse::<NodeId>()
     712            0 :                     .with_context(|| format!("parse id from {:?}", dentry.path()))?;
     713              :                 // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656)
     714            0 :                 #[derive(serde::Serialize, serde::Deserialize)]
     715              :                 // (allow unknown fields, unlike PageServerConf)
     716              :                 struct PageserverConfigTomlSubset {
     717              :                     listen_pg_addr: String,
     718              :                     listen_http_addr: String,
     719              :                     listen_https_addr: Option<String>,
     720              :                     listen_grpc_addr: Option<String>,
     721              :                     pg_auth_type: AuthType,
     722              :                     http_auth_type: AuthType,
     723              :                     grpc_auth_type: AuthType,
     724              :                     #[serde(default)]
     725              :                     no_sync: bool,
     726              :                 }
     727            0 :                 let config_toml_path = dentry.path().join("pageserver.toml");
     728            0 :                 let config_toml: PageserverConfigTomlSubset = toml_edit::de::from_str(
     729            0 :                     &std::fs::read_to_string(&config_toml_path)
     730            0 :                         .with_context(|| format!("read {:?}", config_toml_path))?,
     731              :                 )
     732            0 :                 .context("parse pageserver.toml")?;
     733            0 :                 let identity_toml_path = dentry.path().join("identity.toml");
     734            0 :                 #[derive(serde::Serialize, serde::Deserialize)]
     735              :                 struct IdentityTomlSubset {
     736              :                     id: NodeId,
     737              :                 }
     738            0 :                 let identity_toml: IdentityTomlSubset = toml_edit::de::from_str(
     739            0 :                     &std::fs::read_to_string(&identity_toml_path)
     740            0 :                         .with_context(|| format!("read {:?}", identity_toml_path))?,
     741              :                 )
     742            0 :                 .context("parse identity.toml")?;
     743              :                 let PageserverConfigTomlSubset {
     744            0 :                     listen_pg_addr,
     745            0 :                     listen_http_addr,
     746            0 :                     listen_https_addr,
     747            0 :                     listen_grpc_addr,
     748            0 :                     pg_auth_type,
     749            0 :                     http_auth_type,
     750            0 :                     grpc_auth_type,
     751            0 :                     no_sync,
     752            0 :                 } = config_toml;
     753            0 :                 let IdentityTomlSubset {
     754            0 :                     id: identity_toml_id,
     755            0 :                 } = identity_toml;
     756            0 :                 let conf = PageServerConf {
     757              :                     id: {
     758            0 :                         anyhow::ensure!(
     759            0 :                             identity_toml_id == id,
     760            0 :                             "id mismatch: identity.toml:id={identity_toml_id} pageserver_(.*) id={id}",
     761              :                         );
     762            0 :                         id
     763            0 :                     },
     764            0 :                     listen_pg_addr,
     765            0 :                     listen_http_addr,
     766            0 :                     listen_https_addr,
     767            0 :                     listen_grpc_addr,
     768            0 :                     pg_auth_type,
     769            0 :                     http_auth_type,
     770            0 :                     grpc_auth_type,
     771            0 :                     no_sync,
     772            0 :                 };
     773            0 :                 pageservers.push(conf);
     774              :             }
     775            0 :             pageservers
     776            0 :         };
     777            0 : 
     778            0 :         Ok(env)
     779            0 :     }
     780              : 
     781            0 :     pub fn persist_config(&self) -> anyhow::Result<()> {
     782            0 :         Self::persist_config_impl(
     783            0 :             &self.base_data_dir,
     784            0 :             &OnDiskConfig {
     785            0 :                 pg_distrib_dir: self.pg_distrib_dir.clone(),
     786            0 :                 neon_distrib_dir: self.neon_distrib_dir.clone(),
     787            0 :                 default_tenant_id: self.default_tenant_id,
     788            0 :                 private_key_path: self.private_key_path.clone(),
     789            0 :                 public_key_path: self.public_key_path.clone(),
     790            0 :                 broker: self.broker.clone(),
     791            0 :                 storage_controller: self.storage_controller.clone(),
     792            0 :                 pageservers: vec![], // it's skip_serializing anyway
     793            0 :                 safekeepers: self.safekeepers.clone(),
     794            0 :                 control_plane_api: Some(self.control_plane_api.clone()),
     795            0 :                 control_plane_hooks_api: self.control_plane_hooks_api.clone(),
     796            0 :                 control_plane_compute_hook_api: None,
     797            0 :                 branch_name_mappings: self.branch_name_mappings.clone(),
     798            0 :                 generate_local_ssl_certs: self.generate_local_ssl_certs,
     799            0 :                 endpoint_storage: self.endpoint_storage.clone(),
     800            0 :             },
     801            0 :         )
     802            0 :     }
     803              : 
     804            0 :     pub fn persist_config_impl(base_path: &Path, config: &OnDiskConfig) -> anyhow::Result<()> {
     805            0 :         let conf_content = &toml::to_string_pretty(config)?;
     806            0 :         let target_config_path = base_path.join("config");
     807            0 :         fs::write(&target_config_path, conf_content).with_context(|| {
     808            0 :             format!(
     809            0 :                 "Failed to write config file into path '{}'",
     810            0 :                 target_config_path.display()
     811            0 :             )
     812            0 :         })
     813            0 :     }
     814              : 
     815              :     // this function is used only for testing purposes in CLI e g generate tokens during init
     816            0 :     pub fn generate_auth_token<S: Serialize>(&self, claims: &S) -> anyhow::Result<String> {
     817            0 :         let key = self.read_private_key()?;
     818            0 :         encode_from_key_file(claims, &key)
     819            0 :     }
     820              : 
     821              :     /// Get the path to the private key.
     822            0 :     pub fn get_private_key_path(&self) -> PathBuf {
     823            0 :         if self.private_key_path.is_absolute() {
     824            0 :             self.private_key_path.to_path_buf()
     825              :         } else {
     826            0 :             self.base_data_dir.join(&self.private_key_path)
     827              :         }
     828            0 :     }
     829              : 
     830              :     /// Get the path to the public key.
     831            0 :     pub fn get_public_key_path(&self) -> PathBuf {
     832            0 :         if self.public_key_path.is_absolute() {
     833            0 :             self.public_key_path.to_path_buf()
     834              :         } else {
     835            0 :             self.base_data_dir.join(&self.public_key_path)
     836              :         }
     837            0 :     }
     838              : 
     839              :     /// Read the contents of the private key file.
     840            0 :     pub fn read_private_key(&self) -> anyhow::Result<Pem> {
     841            0 :         let private_key_path = self.get_private_key_path();
     842            0 :         let pem = pem::parse(fs::read(private_key_path)?)?;
     843            0 :         Ok(pem)
     844            0 :     }
     845              : 
     846              :     /// Read the contents of the public key file.
     847            0 :     pub fn read_public_key(&self) -> anyhow::Result<Pem> {
     848            0 :         let public_key_path = self.get_public_key_path();
     849            0 :         let pem = pem::parse(fs::read(public_key_path)?)?;
     850            0 :         Ok(pem)
     851            0 :     }
     852              : 
     853              :     /// Materialize the [`NeonLocalInitConf`] to disk. Called during [`neon_local init`].
     854            0 :     pub fn init(conf: NeonLocalInitConf, force: &InitForceMode) -> anyhow::Result<()> {
     855            0 :         let base_path = base_path();
     856            0 :         assert_ne!(base_path, Path::new(""));
     857            0 :         let base_path = &base_path;
     858            0 : 
     859            0 :         // create base_path dir
     860            0 :         if base_path.exists() {
     861            0 :             match force {
     862              :                 InitForceMode::MustNotExist => {
     863            0 :                     bail!(
     864            0 :                         "directory '{}' already exists. Perhaps already initialized?",
     865            0 :                         base_path.display()
     866            0 :                     );
     867              :                 }
     868              :                 InitForceMode::EmptyDirOk => {
     869            0 :                     if let Some(res) = std::fs::read_dir(base_path)?.next() {
     870            0 :                         res.context("check if directory is empty")?;
     871            0 :                         anyhow::bail!("directory not empty: {base_path:?}");
     872            0 :                     }
     873              :                 }
     874              :                 InitForceMode::RemoveAllContents => {
     875            0 :                     println!("removing all contents of '{}'", base_path.display());
     876              :                     // instead of directly calling `remove_dir_all`, we keep the original dir but removing
     877              :                     // all contents inside. This helps if the developer symbol links another directory (i.e.,
     878              :                     // S3 local SSD) to the `.neon` base directory.
     879            0 :                     for entry in std::fs::read_dir(base_path)? {
     880            0 :                         let entry = entry?;
     881            0 :                         let path = entry.path();
     882            0 :                         if path.is_dir() {
     883            0 :                             fs::remove_dir_all(&path)?;
     884              :                         } else {
     885            0 :                             fs::remove_file(&path)?;
     886              :                         }
     887              :                     }
     888              :                 }
     889              :             }
     890            0 :         }
     891            0 :         if !base_path.exists() {
     892            0 :             fs::create_dir(base_path)?;
     893            0 :         }
     894              : 
     895              :         let NeonLocalInitConf {
     896            0 :             pg_distrib_dir,
     897            0 :             neon_distrib_dir,
     898            0 :             default_tenant_id,
     899            0 :             broker,
     900            0 :             storage_controller,
     901            0 :             pageservers,
     902            0 :             safekeepers,
     903            0 :             control_plane_api,
     904            0 :             generate_local_ssl_certs,
     905            0 :             control_plane_hooks_api,
     906            0 :             endpoint_storage,
     907            0 :         } = conf;
     908            0 : 
     909            0 :         // Find postgres binaries.
     910            0 :         // Follow POSTGRES_DISTRIB_DIR if set, otherwise look in "pg_install".
     911            0 :         // Note that later in the code we assume, that distrib dirs follow the same pattern
     912            0 :         // for all postgres versions.
     913            0 :         let pg_distrib_dir = pg_distrib_dir.unwrap_or_else(|| {
     914            0 :             if let Some(postgres_bin) = env::var_os("POSTGRES_DISTRIB_DIR") {
     915            0 :                 postgres_bin.into()
     916              :             } else {
     917            0 :                 let cwd = env::current_dir().unwrap();
     918            0 :                 cwd.join("pg_install")
     919              :             }
     920            0 :         });
     921            0 : 
     922            0 :         // Find neon binaries.
     923            0 :         let neon_distrib_dir = neon_distrib_dir
     924            0 :             .unwrap_or_else(|| env::current_exe().unwrap().parent().unwrap().to_owned());
     925            0 : 
     926            0 :         // Generate keypair for JWT.
     927            0 :         //
     928            0 :         // The keypair is only needed if authentication is enabled in any of the
     929            0 :         // components. For convenience, we generate the keypair even if authentication
     930            0 :         // is not enabled, so that you can easily enable it after the initialization
     931            0 :         // step.
     932            0 :         generate_auth_keys(
     933            0 :             base_path.join("auth_private_key.pem").as_path(),
     934            0 :             base_path.join("auth_public_key.pem").as_path(),
     935            0 :         )
     936            0 :         .context("generate auth keys")?;
     937            0 :         let private_key_path = PathBuf::from("auth_private_key.pem");
     938            0 :         let public_key_path = PathBuf::from("auth_public_key.pem");
     939            0 : 
     940            0 :         // create the runtime type because the remaining initialization code below needs
     941            0 :         // a LocalEnv instance op operation
     942            0 :         // TODO: refactor to avoid this, LocalEnv should only be constructed from on-disk state
     943            0 :         let env = LocalEnv {
     944            0 :             base_data_dir: base_path.clone(),
     945            0 :             pg_distrib_dir,
     946            0 :             neon_distrib_dir,
     947            0 :             default_tenant_id: Some(default_tenant_id),
     948            0 :             private_key_path,
     949            0 :             public_key_path,
     950            0 :             broker,
     951            0 :             storage_controller: storage_controller.unwrap_or_default(),
     952            0 :             pageservers: pageservers.iter().map(Into::into).collect(),
     953            0 :             safekeepers,
     954            0 :             control_plane_api: control_plane_api.unwrap(),
     955            0 :             control_plane_hooks_api,
     956            0 :             branch_name_mappings: Default::default(),
     957            0 :             generate_local_ssl_certs,
     958            0 :             endpoint_storage,
     959            0 :         };
     960            0 : 
     961            0 :         if generate_local_ssl_certs {
     962            0 :             env.generate_ssl_ca_cert()?;
     963            0 :         }
     964              : 
     965              :         // create endpoints dir
     966            0 :         fs::create_dir_all(env.endpoints_path())?;
     967              : 
     968              :         // create storage broker dir
     969            0 :         fs::create_dir_all(env.storage_broker_data_dir())?;
     970            0 :         StorageBroker::from_env(&env)
     971            0 :             .initialize()
     972            0 :             .context("storage broker init failed")?;
     973              : 
     974              :         // create safekeeper dirs
     975            0 :         for safekeeper in &env.safekeepers {
     976            0 :             fs::create_dir_all(SafekeeperNode::datadir_path_by_id(&env, safekeeper.id))?;
     977            0 :             SafekeeperNode::from_env(&env, safekeeper)
     978            0 :                 .initialize()
     979            0 :                 .context("safekeeper init failed")?;
     980              :         }
     981              : 
     982              :         // initialize pageserver state
     983            0 :         for (i, ps) in pageservers.into_iter().enumerate() {
     984            0 :             let runtime_ps = &env.pageservers[i];
     985            0 :             assert_eq!(&PageServerConf::from(&ps), runtime_ps);
     986            0 :             fs::create_dir(env.pageserver_data_dir(ps.id))?;
     987            0 :             PageServerNode::from_env(&env, runtime_ps)
     988            0 :                 .initialize(ps)
     989            0 :                 .context("pageserver init failed")?;
     990              :         }
     991              : 
     992            0 :         EndpointStorage::from_env(&env)
     993            0 :             .init()
     994            0 :             .context("object storage init failed")?;
     995              : 
     996              :         // setup remote remote location for default LocalFs remote storage
     997            0 :         std::fs::create_dir_all(env.base_data_dir.join(PAGESERVER_REMOTE_STORAGE_DIR))?;
     998            0 :         std::fs::create_dir_all(env.base_data_dir.join(ENDPOINT_STORAGE_REMOTE_STORAGE_DIR))?;
     999              : 
    1000            0 :         env.persist_config()
    1001            0 :     }
    1002              : }
    1003              : 
    1004            0 : pub fn base_path() -> PathBuf {
    1005            0 :     let path = match std::env::var_os("NEON_REPO_DIR") {
    1006            0 :         Some(val) => {
    1007            0 :             let path = PathBuf::from(val);
    1008            0 :             if !path.is_absolute() {
    1009              :                 // repeat the env var in the error because our default is always absolute
    1010            0 :                 panic!("NEON_REPO_DIR must be an absolute path, got {path:?}");
    1011            0 :             }
    1012            0 :             path
    1013              :         }
    1014              :         None => {
    1015            0 :             let pwd = std::env::current_dir()
    1016            0 :                 // technically this can fail but it's quite unlikeley
    1017            0 :                 .expect("determine current directory");
    1018            0 :             let pwd_abs = pwd.canonicalize().expect("canonicalize current directory");
    1019            0 :             pwd_abs.join(".neon")
    1020              :         }
    1021              :     };
    1022            0 :     assert!(path.is_absolute());
    1023            0 :     path
    1024            0 : }
    1025              : 
    1026              : /// Generate a public/private key pair for JWT authentication
    1027            0 : fn generate_auth_keys(private_key_path: &Path, public_key_path: &Path) -> anyhow::Result<()> {
    1028              :     // Generate the key pair
    1029              :     //
    1030              :     // openssl genpkey -algorithm ed25519 -out auth_private_key.pem
    1031            0 :     let keygen_output = Command::new("openssl")
    1032            0 :         .arg("genpkey")
    1033            0 :         .args(["-algorithm", "ed25519"])
    1034            0 :         .args(["-out", private_key_path.to_str().unwrap()])
    1035            0 :         .stdout(Stdio::null())
    1036            0 :         .output()
    1037            0 :         .context("failed to generate auth private key")?;
    1038            0 :     if !keygen_output.status.success() {
    1039            0 :         bail!(
    1040            0 :             "openssl failed: '{}'",
    1041            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1042            0 :         );
    1043            0 :     }
    1044              : 
    1045              :     // Extract the public key from the private key file
    1046              :     //
    1047              :     // openssl pkey -in auth_private_key.pem -pubout -out auth_public_key.pem
    1048            0 :     let keygen_output = Command::new("openssl")
    1049            0 :         .arg("pkey")
    1050            0 :         .args(["-in", private_key_path.to_str().unwrap()])
    1051            0 :         .arg("-pubout")
    1052            0 :         .args(["-out", public_key_path.to_str().unwrap()])
    1053            0 :         .output()
    1054            0 :         .context("failed to extract public key from private key")?;
    1055            0 :     if !keygen_output.status.success() {
    1056            0 :         bail!(
    1057            0 :             "openssl failed: '{}'",
    1058            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1059            0 :         );
    1060            0 :     }
    1061            0 : 
    1062            0 :     Ok(())
    1063            0 : }
    1064              : 
    1065            0 : fn generate_ssl_ca_cert(cert_path: &Path, key_path: &Path) -> anyhow::Result<()> {
    1066              :     // openssl req -x509 -newkey rsa:2048 -nodes -subj "/CN=Neon Local CA" -days 36500 \
    1067              :     // -out rootCA.crt -keyout rootCA.key
    1068            0 :     let keygen_output = Command::new("openssl")
    1069            0 :         .args([
    1070            0 :             "req", "-x509", "-newkey", "ed25519", "-nodes", "-days", "36500",
    1071            0 :         ])
    1072            0 :         .args(["-subj", "/CN=Neon Local CA"])
    1073            0 :         .args(["-out", cert_path.to_str().unwrap()])
    1074            0 :         .args(["-keyout", key_path.to_str().unwrap()])
    1075            0 :         .output()
    1076            0 :         .context("failed to generate CA certificate")?;
    1077            0 :     if !keygen_output.status.success() {
    1078            0 :         bail!(
    1079            0 :             "openssl failed: '{}'",
    1080            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1081            0 :         );
    1082            0 :     }
    1083            0 :     Ok(())
    1084            0 : }
    1085              : 
    1086            0 : fn generate_ssl_cert(
    1087            0 :     cert_path: &Path,
    1088            0 :     key_path: &Path,
    1089            0 :     ca_cert_path: &Path,
    1090            0 :     ca_key_path: &Path,
    1091            0 : ) -> anyhow::Result<()> {
    1092            0 :     // Generate Certificate Signing Request (CSR).
    1093            0 :     let mut csr_path = cert_path.to_path_buf();
    1094            0 :     csr_path.set_extension(".csr");
    1095              : 
    1096              :     // openssl req -new -nodes -newkey rsa:2048 -keyout server.key -out server.csr \
    1097              :     // -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
    1098            0 :     let keygen_output = Command::new("openssl")
    1099            0 :         .args(["req", "-new", "-nodes"])
    1100            0 :         .args(["-newkey", "ed25519"])
    1101            0 :         .args(["-subj", "/CN=localhost"])
    1102            0 :         .args(["-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"])
    1103            0 :         .args(["-keyout", key_path.to_str().unwrap()])
    1104            0 :         .args(["-out", csr_path.to_str().unwrap()])
    1105            0 :         .output()
    1106            0 :         .context("failed to generate CSR")?;
    1107            0 :     if !keygen_output.status.success() {
    1108            0 :         bail!(
    1109            0 :             "openssl failed: '{}'",
    1110            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1111            0 :         );
    1112            0 :     }
    1113              : 
    1114              :     // Sign CSR with CA key.
    1115              :     //
    1116              :     // openssl x509 -req -in server.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial \
    1117              :     // -out server.crt -days 36500 -copy_extensions copyall
    1118            0 :     let keygen_output = Command::new("openssl")
    1119            0 :         .args(["x509", "-req"])
    1120            0 :         .args(["-in", csr_path.to_str().unwrap()])
    1121            0 :         .args(["-CA", ca_cert_path.to_str().unwrap()])
    1122            0 :         .args(["-CAkey", ca_key_path.to_str().unwrap()])
    1123            0 :         .arg("-CAcreateserial")
    1124            0 :         .args(["-out", cert_path.to_str().unwrap()])
    1125            0 :         .args(["-days", "36500"])
    1126            0 :         .args(["-copy_extensions", "copyall"])
    1127            0 :         .output()
    1128            0 :         .context("failed to sign CSR")?;
    1129            0 :     if !keygen_output.status.success() {
    1130            0 :         bail!(
    1131            0 :             "openssl failed: '{}'",
    1132            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1133            0 :         );
    1134            0 :     }
    1135            0 : 
    1136            0 :     // Remove CSR file as it's not needed anymore.
    1137            0 :     fs::remove_file(csr_path)?;
    1138              : 
    1139            0 :     Ok(())
    1140            0 : }
        

Generated by: LCOV version 2.1-beta