LCOV - code coverage report
Current view: top level - control_plane/src - storage_controller.rs (source / functions) Coverage Total Hit
Test: 2620485e474b48c32427149a5d91ef8fc2cd649e.info Lines: 0.0 % 562 0
Test Date: 2025-05-01 22:50:11 Functions: 0.0 % 84 0

            Line data    Source code
       1              : use std::ffi::OsStr;
       2              : use std::fs;
       3              : use std::path::PathBuf;
       4              : use std::process::ExitStatus;
       5              : use std::str::FromStr;
       6              : use std::sync::OnceLock;
       7              : use std::time::{Duration, Instant};
       8              : 
       9              : use camino::{Utf8Path, Utf8PathBuf};
      10              : use hyper0::Uri;
      11              : use nix::unistd::Pid;
      12              : use pageserver_api::controller_api::{
      13              :     NodeConfigureRequest, NodeDescribeResponse, NodeRegisterRequest, TenantCreateRequest,
      14              :     TenantCreateResponse, TenantLocateResponse,
      15              : };
      16              : use pageserver_api::models::{
      17              :     TenantConfig, TenantConfigRequest, TimelineCreateRequest, TimelineInfo,
      18              : };
      19              : use pageserver_api::shard::TenantShardId;
      20              : use pageserver_client::mgmt_api::ResponseErrorMessageExt;
      21              : use pem::Pem;
      22              : use postgres_backend::AuthType;
      23              : use reqwest::Method;
      24              : use serde::de::DeserializeOwned;
      25              : use serde::{Deserialize, Serialize};
      26              : use tokio::process::Command;
      27              : use tracing::instrument;
      28              : use url::Url;
      29              : use utils::auth::{Claims, Scope, encode_from_key_file};
      30              : use utils::id::{NodeId, TenantId};
      31              : use whoami::username;
      32              : 
      33              : use crate::background_process;
      34              : use crate::local_env::{LocalEnv, NeonStorageControllerConf};
      35              : 
      36              : pub struct StorageController {
      37              :     env: LocalEnv,
      38              :     private_key: Option<Pem>,
      39              :     public_key: Option<Pem>,
      40              :     client: reqwest::Client,
      41              :     config: NeonStorageControllerConf,
      42              : 
      43              :     // The listen port is learned when starting the storage controller,
      44              :     // hence the use of OnceLock to init it at the right time.
      45              :     listen_port: OnceLock<u16>,
      46              : }
      47              : 
      48              : const COMMAND: &str = "storage_controller";
      49              : 
      50              : const STORAGE_CONTROLLER_POSTGRES_VERSION: u32 = 16;
      51              : 
      52              : const DB_NAME: &str = "storage_controller";
      53              : 
      54              : pub struct NeonStorageControllerStartArgs {
      55              :     pub instance_id: u8,
      56              :     pub base_port: Option<u16>,
      57              :     pub start_timeout: humantime::Duration,
      58              : }
      59              : 
      60              : impl NeonStorageControllerStartArgs {
      61            0 :     pub fn with_default_instance_id(start_timeout: humantime::Duration) -> Self {
      62            0 :         Self {
      63            0 :             instance_id: 1,
      64            0 :             base_port: None,
      65            0 :             start_timeout,
      66            0 :         }
      67            0 :     }
      68              : }
      69              : 
      70              : pub struct NeonStorageControllerStopArgs {
      71              :     pub instance_id: u8,
      72              :     pub immediate: bool,
      73              : }
      74              : 
      75              : impl NeonStorageControllerStopArgs {
      76            0 :     pub fn with_default_instance_id(immediate: bool) -> Self {
      77            0 :         Self {
      78            0 :             instance_id: 1,
      79            0 :             immediate,
      80            0 :         }
      81            0 :     }
      82              : }
      83              : 
      84            0 : #[derive(Serialize, Deserialize)]
      85              : pub struct AttachHookRequest {
      86              :     pub tenant_shard_id: TenantShardId,
      87              :     pub node_id: Option<NodeId>,
      88              :     pub generation_override: Option<i32>, // only new tenants
      89              :     pub config: Option<TenantConfig>,     // only new tenants
      90              : }
      91              : 
      92            0 : #[derive(Serialize, Deserialize)]
      93              : pub struct AttachHookResponse {
      94              :     #[serde(rename = "gen")]
      95              :     pub generation: Option<u32>,
      96              : }
      97              : 
      98            0 : #[derive(Serialize, Deserialize)]
      99              : pub struct InspectRequest {
     100              :     pub tenant_shard_id: TenantShardId,
     101              : }
     102              : 
     103            0 : #[derive(Serialize, Deserialize)]
     104              : pub struct InspectResponse {
     105              :     pub attachment: Option<(u32, NodeId)>,
     106              : }
     107              : 
     108              : impl StorageController {
     109            0 :     pub fn from_env(env: &LocalEnv) -> Self {
     110            0 :         // Assume all pageservers have symmetric auth configuration: this service
     111            0 :         // expects to use one JWT token to talk to all of them.
     112            0 :         let ps_conf = env
     113            0 :             .pageservers
     114            0 :             .first()
     115            0 :             .expect("Config is validated to contain at least one pageserver");
     116            0 :         let (private_key, public_key) = match ps_conf.http_auth_type {
     117            0 :             AuthType::Trust => (None, None),
     118              :             AuthType::NeonJWT => {
     119            0 :                 let private_key_path = env.get_private_key_path();
     120            0 :                 let private_key =
     121            0 :                     pem::parse(fs::read(private_key_path).expect("failed to read private key"))
     122            0 :                         .expect("failed to parse PEM file");
     123            0 : 
     124            0 :                 // If pageserver auth is enabled, this implicitly enables auth for this service,
     125            0 :                 // using the same credentials.
     126            0 :                 let public_key_path =
     127            0 :                     camino::Utf8PathBuf::try_from(env.base_data_dir.join("auth_public_key.pem"))
     128            0 :                         .unwrap();
     129              : 
     130              :                 // This service takes keys as a string rather than as a path to a file/dir: read the key into memory.
     131            0 :                 let public_key = if std::fs::metadata(&public_key_path)
     132            0 :                     .expect("Can't stat public key")
     133            0 :                     .is_dir()
     134              :                 {
     135              :                     // Our config may specify a directory: this is for the pageserver's ability to handle multiple
     136              :                     // keys.  We only use one key at a time, so, arbitrarily load the first one in the directory.
     137            0 :                     let mut dir =
     138            0 :                         std::fs::read_dir(&public_key_path).expect("Can't readdir public key path");
     139            0 :                     let dent = dir
     140            0 :                         .next()
     141            0 :                         .expect("Empty key dir")
     142            0 :                         .expect("Error reading key dir");
     143            0 : 
     144            0 :                     pem::parse(std::fs::read_to_string(dent.path()).expect("Can't read public key"))
     145            0 :                         .expect("Failed to parse PEM file")
     146              :                 } else {
     147            0 :                     pem::parse(
     148            0 :                         std::fs::read_to_string(&public_key_path).expect("Can't read public key"),
     149            0 :                     )
     150            0 :                     .expect("Failed to parse PEM file")
     151              :                 };
     152            0 :                 (Some(private_key), Some(public_key))
     153              :             }
     154              :         };
     155              : 
     156            0 :         Self {
     157            0 :             env: env.clone(),
     158            0 :             private_key,
     159            0 :             public_key,
     160            0 :             client: env.create_http_client(),
     161            0 :             config: env.storage_controller.clone(),
     162            0 :             listen_port: OnceLock::default(),
     163            0 :         }
     164            0 :     }
     165              : 
     166            0 :     fn storage_controller_instance_dir(&self, instance_id: u8) -> PathBuf {
     167            0 :         self.env
     168            0 :             .base_data_dir
     169            0 :             .join(format!("storage_controller_{}", instance_id))
     170            0 :     }
     171              : 
     172            0 :     fn pid_file(&self, instance_id: u8) -> Utf8PathBuf {
     173            0 :         Utf8PathBuf::from_path_buf(
     174            0 :             self.storage_controller_instance_dir(instance_id)
     175            0 :                 .join("storage_controller.pid"),
     176            0 :         )
     177            0 :         .expect("non-Unicode path")
     178            0 :     }
     179              : 
     180              :     /// Find the directory containing postgres subdirectories, such `bin` and `lib`
     181              :     ///
     182              :     /// This usually uses STORAGE_CONTROLLER_POSTGRES_VERSION of postgres, but will fall back
     183              :     /// to other versions if that one isn't found.  Some automated tests create circumstances
     184              :     /// where only one version is available in pg_distrib_dir, such as `test_remote_extensions`.
     185            0 :     async fn get_pg_dir(&self, dir_name: &str) -> anyhow::Result<Utf8PathBuf> {
     186            0 :         let prefer_versions = [STORAGE_CONTROLLER_POSTGRES_VERSION, 16, 15, 14];
     187              : 
     188            0 :         for v in prefer_versions {
     189            0 :             let path = Utf8PathBuf::from_path_buf(self.env.pg_dir(v, dir_name)?).unwrap();
     190            0 :             if tokio::fs::try_exists(&path).await? {
     191            0 :                 return Ok(path);
     192            0 :             }
     193              :         }
     194              : 
     195              :         // Fall through
     196            0 :         anyhow::bail!(
     197            0 :             "Postgres directory '{}' not found in {}",
     198            0 :             dir_name,
     199            0 :             self.env.pg_distrib_dir.display(),
     200            0 :         );
     201            0 :     }
     202              : 
     203            0 :     pub async fn get_pg_bin_dir(&self) -> anyhow::Result<Utf8PathBuf> {
     204            0 :         self.get_pg_dir("bin").await
     205            0 :     }
     206              : 
     207            0 :     pub async fn get_pg_lib_dir(&self) -> anyhow::Result<Utf8PathBuf> {
     208            0 :         self.get_pg_dir("lib").await
     209            0 :     }
     210              : 
     211              :     /// Readiness check for our postgres process
     212            0 :     async fn pg_isready(&self, pg_bin_dir: &Utf8Path, postgres_port: u16) -> anyhow::Result<bool> {
     213            0 :         let bin_path = pg_bin_dir.join("pg_isready");
     214            0 :         let args = [
     215            0 :             "-h",
     216            0 :             "localhost",
     217            0 :             "-U",
     218            0 :             &username(),
     219            0 :             "-d",
     220            0 :             DB_NAME,
     221            0 :             "-p",
     222            0 :             &format!("{}", postgres_port),
     223            0 :         ];
     224            0 :         let pg_lib_dir = self.get_pg_lib_dir().await.unwrap();
     225            0 :         let envs = [
     226            0 :             ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     227            0 :             ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     228            0 :         ];
     229            0 :         let exitcode = Command::new(bin_path)
     230            0 :             .args(args)
     231            0 :             .envs(envs)
     232            0 :             .spawn()?
     233            0 :             .wait()
     234            0 :             .await?;
     235              : 
     236            0 :         Ok(exitcode.success())
     237            0 :     }
     238              : 
     239              :     /// Create our database if it doesn't exist
     240              :     ///
     241              :     /// This function is equivalent to the `diesel setup` command in the diesel CLI.  We implement
     242              :     /// the same steps by hand to avoid imposing a dependency on installing diesel-cli for developers
     243              :     /// who just want to run `cargo neon_local` without knowing about diesel.
     244              :     ///
     245              :     /// Returns the database url
     246            0 :     pub async fn setup_database(&self, postgres_port: u16) -> anyhow::Result<String> {
     247            0 :         let database_url = format!(
     248            0 :             "postgresql://{}@localhost:{}/{DB_NAME}",
     249            0 :             &username(),
     250            0 :             postgres_port
     251            0 :         );
     252              : 
     253            0 :         let pg_bin_dir = self.get_pg_bin_dir().await?;
     254            0 :         let createdb_path = pg_bin_dir.join("createdb");
     255            0 :         let pg_lib_dir = self.get_pg_lib_dir().await.unwrap();
     256            0 :         let envs = [
     257            0 :             ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     258            0 :             ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     259            0 :         ];
     260            0 :         let output = Command::new(&createdb_path)
     261            0 :             .args([
     262            0 :                 "-h",
     263            0 :                 "localhost",
     264            0 :                 "-p",
     265            0 :                 &format!("{}", postgres_port),
     266            0 :                 "-U",
     267            0 :                 &username(),
     268            0 :                 "-O",
     269            0 :                 &username(),
     270            0 :                 DB_NAME,
     271            0 :             ])
     272            0 :             .envs(envs)
     273            0 :             .output()
     274            0 :             .await
     275            0 :             .expect("Failed to spawn createdb");
     276            0 : 
     277            0 :         if !output.status.success() {
     278            0 :             let stderr = String::from_utf8(output.stderr).expect("Non-UTF8 output from createdb");
     279            0 :             if stderr.contains("already exists") {
     280            0 :                 tracing::info!("Database {DB_NAME} already exists");
     281              :             } else {
     282            0 :                 anyhow::bail!("createdb failed with status {}: {stderr}", output.status);
     283              :             }
     284            0 :         }
     285              : 
     286            0 :         Ok(database_url)
     287            0 :     }
     288              : 
     289            0 :     pub async fn connect_to_database(
     290            0 :         &self,
     291            0 :         postgres_port: u16,
     292            0 :     ) -> anyhow::Result<(
     293            0 :         tokio_postgres::Client,
     294            0 :         tokio_postgres::Connection<tokio_postgres::Socket, tokio_postgres::tls::NoTlsStream>,
     295            0 :     )> {
     296            0 :         tokio_postgres::Config::new()
     297            0 :             .host("localhost")
     298            0 :             .port(postgres_port)
     299            0 :             // The user is the ambient operating system user name.
     300            0 :             // That is an impurity which we want to fix in => TODO https://github.com/neondatabase/neon/issues/8400
     301            0 :             //
     302            0 :             // Until we get there, use the ambient operating system user name.
     303            0 :             // Recent tokio-postgres versions default to this if the user isn't specified.
     304            0 :             // But tokio-postgres fork doesn't have this upstream commit:
     305            0 :             // https://github.com/sfackler/rust-postgres/commit/cb609be758f3fb5af537f04b584a2ee0cebd5e79
     306            0 :             // => we should rebase our fork => TODO https://github.com/neondatabase/neon/issues/8399
     307            0 :             .user(&username())
     308            0 :             .dbname(DB_NAME)
     309            0 :             .connect(tokio_postgres::NoTls)
     310            0 :             .await
     311            0 :             .map_err(anyhow::Error::new)
     312            0 :     }
     313              : 
     314              :     /// Wrapper for the pg_ctl binary, which we spawn as a short-lived subprocess when starting and stopping postgres
     315            0 :     async fn pg_ctl<I, S>(&self, args: I) -> ExitStatus
     316            0 :     where
     317            0 :         I: IntoIterator<Item = S>,
     318            0 :         S: AsRef<OsStr>,
     319            0 :     {
     320            0 :         let pg_bin_dir = self.get_pg_bin_dir().await.unwrap();
     321            0 :         let bin_path = pg_bin_dir.join("pg_ctl");
     322              : 
     323            0 :         let pg_lib_dir = self.get_pg_lib_dir().await.unwrap();
     324            0 :         let envs = [
     325            0 :             ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     326            0 :             ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     327            0 :         ];
     328            0 : 
     329            0 :         Command::new(bin_path)
     330            0 :             .args(args)
     331            0 :             .envs(envs)
     332            0 :             .spawn()
     333            0 :             .expect("Failed to spawn pg_ctl, binary_missing?")
     334            0 :             .wait()
     335            0 :             .await
     336            0 :             .expect("Failed to wait for pg_ctl termination")
     337            0 :     }
     338              : 
     339            0 :     pub async fn start(&self, start_args: NeonStorageControllerStartArgs) -> anyhow::Result<()> {
     340            0 :         let instance_dir = self.storage_controller_instance_dir(start_args.instance_id);
     341            0 :         if let Err(err) = tokio::fs::create_dir(&instance_dir).await {
     342            0 :             if err.kind() != std::io::ErrorKind::AlreadyExists {
     343            0 :                 panic!("Failed to create instance dir {instance_dir:?}");
     344            0 :             }
     345            0 :         }
     346              : 
     347            0 :         if self.env.generate_local_ssl_certs {
     348            0 :             self.env.generate_ssl_cert(
     349            0 :                 &instance_dir.join("server.crt"),
     350            0 :                 &instance_dir.join("server.key"),
     351            0 :             )?;
     352            0 :         }
     353              : 
     354            0 :         let listen_url = &self.env.control_plane_api;
     355            0 : 
     356            0 :         let scheme = listen_url.scheme();
     357            0 :         let host = listen_url.host_str().unwrap();
     358              : 
     359            0 :         let (listen_port, postgres_port) = if let Some(base_port) = start_args.base_port {
     360            0 :             (
     361            0 :                 base_port,
     362            0 :                 self.config
     363            0 :                     .database_url
     364            0 :                     .expect("--base-port requires NeonStorageControllerConf::database_url")
     365            0 :                     .port(),
     366            0 :             )
     367              :         } else {
     368            0 :             let port = listen_url.port().unwrap();
     369            0 :             (port, port + 1)
     370              :         };
     371              : 
     372            0 :         self.listen_port
     373            0 :             .set(listen_port)
     374            0 :             .expect("StorageController::listen_port is only set here");
     375              : 
     376              :         // Do we remove the pid file on stop?
     377            0 :         let pg_started = self.is_postgres_running().await?;
     378            0 :         let pg_lib_dir = self.get_pg_lib_dir().await?;
     379              : 
     380            0 :         if !pg_started {
     381              :             // Start a vanilla Postgres process used by the storage controller for persistence.
     382            0 :             let pg_data_path = Utf8PathBuf::from_path_buf(self.env.base_data_dir.clone())
     383            0 :                 .unwrap()
     384            0 :                 .join("storage_controller_db");
     385            0 :             let pg_bin_dir = self.get_pg_bin_dir().await?;
     386            0 :             let pg_log_path = pg_data_path.join("postgres.log");
     387            0 : 
     388            0 :             if !tokio::fs::try_exists(&pg_data_path).await? {
     389            0 :                 let initdb_args = [
     390            0 :                     "--pgdata",
     391            0 :                     pg_data_path.as_ref(),
     392            0 :                     "--username",
     393            0 :                     &username(),
     394            0 :                     "--no-sync",
     395            0 :                     "--no-instructions",
     396            0 :                 ];
     397            0 :                 tracing::info!(
     398            0 :                     "Initializing storage controller database with args: {:?}",
     399              :                     initdb_args
     400              :                 );
     401              : 
     402              :                 // Initialize empty database
     403            0 :                 let initdb_path = pg_bin_dir.join("initdb");
     404            0 :                 let mut child = Command::new(&initdb_path)
     405            0 :                     .envs(vec![
     406            0 :                         ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     407            0 :                         ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     408            0 :                     ])
     409            0 :                     .args(initdb_args)
     410            0 :                     .spawn()
     411            0 :                     .expect("Failed to spawn initdb");
     412            0 :                 let status = child.wait().await?;
     413            0 :                 if !status.success() {
     414            0 :                     anyhow::bail!("initdb failed with status {status}");
     415            0 :                 }
     416            0 :             };
     417              : 
     418              :             // Write a minimal config file:
     419              :             // - Specify the port, since this is chosen dynamically
     420              :             // - Switch off fsync, since we're running on lightweight test environments and when e.g. scale testing
     421              :             //   the storage controller we don't want a slow local disk to interfere with that.
     422              :             //
     423              :             // NB: it's important that we rewrite this file on each start command so we propagate changes
     424              :             // from `LocalEnv`'s config file (`.neon/config`).
     425            0 :             tokio::fs::write(
     426            0 :                 &pg_data_path.join("postgresql.conf"),
     427            0 :                 format!("port = {}\nfsync=off\n", postgres_port),
     428            0 :             )
     429            0 :             .await?;
     430              : 
     431            0 :             println!("Starting storage controller database...");
     432            0 :             let db_start_args = [
     433            0 :                 "-w",
     434            0 :                 "-D",
     435            0 :                 pg_data_path.as_ref(),
     436            0 :                 "-l",
     437            0 :                 pg_log_path.as_ref(),
     438            0 :                 "-U",
     439            0 :                 &username(),
     440            0 :                 "start",
     441            0 :             ];
     442            0 :             tracing::info!(
     443            0 :                 "Starting storage controller database with args: {:?}",
     444              :                 db_start_args
     445              :             );
     446              : 
     447            0 :             let db_start_status = self.pg_ctl(db_start_args).await;
     448            0 :             let start_timeout: Duration = start_args.start_timeout.into();
     449            0 :             let db_start_deadline = Instant::now() + start_timeout;
     450            0 :             if !db_start_status.success() {
     451            0 :                 return Err(anyhow::anyhow!(
     452            0 :                     "Failed to start postgres {}",
     453            0 :                     db_start_status.code().unwrap()
     454            0 :                 ));
     455            0 :             }
     456              : 
     457              :             loop {
     458            0 :                 if Instant::now() > db_start_deadline {
     459            0 :                     return Err(anyhow::anyhow!("Timed out waiting for postgres to start"));
     460            0 :                 }
     461            0 : 
     462            0 :                 match self.pg_isready(&pg_bin_dir, postgres_port).await {
     463              :                     Ok(true) => {
     464            0 :                         tracing::info!("storage controller postgres is now ready");
     465            0 :                         break;
     466              :                     }
     467              :                     Ok(false) => {
     468            0 :                         tokio::time::sleep(Duration::from_millis(100)).await;
     469              :                     }
     470            0 :                     Err(e) => {
     471            0 :                         tracing::warn!("Failed to check postgres status: {e}")
     472              :                     }
     473              :                 }
     474              :             }
     475              : 
     476            0 :             self.setup_database(postgres_port).await?;
     477            0 :         }
     478              : 
     479            0 :         let database_url = format!("postgresql://localhost:{}/{DB_NAME}", postgres_port);
     480            0 : 
     481            0 :         // We support running a startup SQL script to fiddle with the database before we launch storcon.
     482            0 :         // This is used by the test suite.
     483            0 :         let startup_script_path = self
     484            0 :             .env
     485            0 :             .base_data_dir
     486            0 :             .join("storage_controller_db.startup.sql");
     487            0 :         let startup_script = match tokio::fs::read_to_string(&startup_script_path).await {
     488            0 :             Ok(script) => {
     489            0 :                 tokio::fs::remove_file(startup_script_path).await?;
     490            0 :                 script
     491              :             }
     492            0 :             Err(e) => {
     493            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
     494              :                     // always run some startup script so that this code path doesn't bit rot
     495            0 :                     "BEGIN; COMMIT;".to_string()
     496              :                 } else {
     497            0 :                     anyhow::bail!("Failed to read startup script: {e}")
     498              :                 }
     499              :             }
     500              :         };
     501            0 :         let (mut client, conn) = self.connect_to_database(postgres_port).await?;
     502            0 :         let conn = tokio::spawn(conn);
     503            0 :         let tx = client.build_transaction();
     504            0 :         let tx = tx.start().await?;
     505            0 :         tx.batch_execute(&startup_script).await?;
     506            0 :         tx.commit().await?;
     507            0 :         drop(client);
     508            0 :         conn.await??;
     509              : 
     510            0 :         let addr = format!("{}:{}", host, listen_port);
     511            0 :         let address_for_peers = Uri::builder()
     512            0 :             .scheme(scheme)
     513            0 :             .authority(addr.clone())
     514            0 :             .path_and_query("")
     515            0 :             .build()
     516            0 :             .unwrap();
     517            0 : 
     518            0 :         let mut args = vec![
     519            0 :             "--dev",
     520            0 :             "--database-url",
     521            0 :             &database_url,
     522            0 :             "--max-offline-interval",
     523            0 :             &humantime::Duration::from(self.config.max_offline).to_string(),
     524            0 :             "--max-warming-up-interval",
     525            0 :             &humantime::Duration::from(self.config.max_warming_up).to_string(),
     526            0 :             "--heartbeat-interval",
     527            0 :             &humantime::Duration::from(self.config.heartbeat_interval).to_string(),
     528            0 :             "--address-for-peers",
     529            0 :             &address_for_peers.to_string(),
     530            0 :         ]
     531            0 :         .into_iter()
     532            0 :         .map(|s| s.to_string())
     533            0 :         .collect::<Vec<_>>();
     534            0 : 
     535            0 :         match scheme {
     536            0 :             "http" => args.extend(["--listen".to_string(), addr]),
     537            0 :             "https" => args.extend(["--listen-https".to_string(), addr]),
     538              :             _ => {
     539            0 :                 panic!("Unexpected url scheme in control_plane_api: {scheme}");
     540              :             }
     541              :         }
     542              : 
     543            0 :         if self.config.start_as_candidate {
     544            0 :             args.push("--start-as-candidate".to_string());
     545            0 :         }
     546              : 
     547            0 :         if self.config.use_https_pageserver_api {
     548            0 :             args.push("--use-https-pageserver-api".to_string());
     549            0 :         }
     550              : 
     551            0 :         if self.config.use_https_safekeeper_api {
     552            0 :             args.push("--use-https-safekeeper-api".to_string());
     553            0 :         }
     554              : 
     555            0 :         if self.config.use_local_compute_notifications {
     556            0 :             args.push("--use-local-compute-notifications".to_string());
     557            0 :         }
     558              : 
     559            0 :         if let Some(ssl_ca_file) = self.env.ssl_ca_cert_path() {
     560            0 :             args.push(format!("--ssl-ca-file={}", ssl_ca_file.to_str().unwrap()));
     561            0 :         }
     562              : 
     563            0 :         if let Some(private_key) = &self.private_key {
     564            0 :             let claims = Claims::new(None, Scope::PageServerApi);
     565            0 :             let jwt_token =
     566            0 :                 encode_from_key_file(&claims, private_key).expect("failed to generate jwt token");
     567            0 :             args.push(format!("--jwt-token={jwt_token}"));
     568            0 : 
     569            0 :             let peer_claims = Claims::new(None, Scope::Admin);
     570            0 :             let peer_jwt_token = encode_from_key_file(&peer_claims, private_key)
     571            0 :                 .expect("failed to generate jwt token");
     572            0 :             args.push(format!("--peer-jwt-token={peer_jwt_token}"));
     573            0 :         }
     574              : 
     575            0 :         if let Some(public_key) = &self.public_key {
     576            0 :             args.push(format!("--public-key=\"{public_key}\""));
     577            0 :         }
     578              : 
     579            0 :         if let Some(control_plane_hooks_api) = &self.env.control_plane_hooks_api {
     580            0 :             args.push(format!("--control-plane-url={control_plane_hooks_api}"));
     581            0 :         }
     582              : 
     583            0 :         if let Some(split_threshold) = self.config.split_threshold.as_ref() {
     584            0 :             args.push(format!("--split-threshold={split_threshold}"))
     585            0 :         }
     586              : 
     587            0 :         if let Some(max_split_shards) = self.config.max_split_shards.as_ref() {
     588            0 :             args.push(format!("--max-split-shards={max_split_shards}"))
     589            0 :         }
     590              : 
     591            0 :         if let Some(initial_split_threshold) = self.config.initial_split_threshold.as_ref() {
     592            0 :             args.push(format!(
     593            0 :                 "--initial-split-threshold={initial_split_threshold}"
     594            0 :             ))
     595            0 :         }
     596              : 
     597            0 :         if let Some(initial_split_shards) = self.config.initial_split_shards.as_ref() {
     598            0 :             args.push(format!("--initial-split-shards={initial_split_shards}"))
     599            0 :         }
     600              : 
     601            0 :         if let Some(lag) = self.config.max_secondary_lag_bytes.as_ref() {
     602            0 :             args.push(format!("--max-secondary-lag-bytes={lag}"))
     603            0 :         }
     604              : 
     605            0 :         if let Some(threshold) = self.config.long_reconcile_threshold {
     606            0 :             args.push(format!(
     607            0 :                 "--long-reconcile-threshold={}",
     608            0 :                 humantime::Duration::from(threshold)
     609            0 :             ))
     610            0 :         }
     611              : 
     612            0 :         args.push(format!(
     613            0 :             "--neon-local-repo-dir={}",
     614            0 :             self.env.base_data_dir.display()
     615            0 :         ));
     616            0 : 
     617            0 :         if self.config.timelines_onto_safekeepers {
     618            0 :             args.push("--timelines-onto-safekeepers".to_string());
     619            0 :         }
     620              : 
     621            0 :         println!("Starting storage controller");
     622            0 : 
     623            0 :         background_process::start_process(
     624            0 :             COMMAND,
     625            0 :             &instance_dir,
     626            0 :             &self.env.storage_controller_bin(),
     627            0 :             args,
     628            0 :             vec![
     629            0 :                 ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     630            0 :                 ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     631            0 :             ],
     632            0 :             background_process::InitialPidFile::Create(self.pid_file(start_args.instance_id)),
     633            0 :             &start_args.start_timeout,
     634            0 :             || async {
     635            0 :                 match self.ready().await {
     636            0 :                     Ok(_) => Ok(true),
     637            0 :                     Err(_) => Ok(false),
     638              :                 }
     639            0 :             },
     640            0 :         )
     641            0 :         .await?;
     642              : 
     643            0 :         Ok(())
     644            0 :     }
     645              : 
     646            0 :     pub async fn stop(&self, stop_args: NeonStorageControllerStopArgs) -> anyhow::Result<()> {
     647            0 :         background_process::stop_process(
     648            0 :             stop_args.immediate,
     649            0 :             COMMAND,
     650            0 :             &self.pid_file(stop_args.instance_id),
     651            0 :         )?;
     652              : 
     653            0 :         let storcon_instances = self.env.storage_controller_instances().await?;
     654            0 :         for (instance_id, instanced_dir_path) in storcon_instances {
     655            0 :             if instance_id == stop_args.instance_id {
     656            0 :                 continue;
     657            0 :             }
     658            0 : 
     659            0 :             let pid_file = instanced_dir_path.join("storage_controller.pid");
     660            0 :             let pid = tokio::fs::read_to_string(&pid_file)
     661            0 :                 .await
     662            0 :                 .map_err(|err| {
     663            0 :                     anyhow::anyhow!("Failed to read storcon pid file at {pid_file:?}: {err}")
     664            0 :                 })?
     665            0 :                 .parse::<i32>()
     666            0 :                 .expect("pid is valid i32");
     667              : 
     668            0 :             let other_proc_alive = !background_process::process_has_stopped(Pid::from_raw(pid))?;
     669            0 :             if other_proc_alive {
     670              :                 // There is another storage controller instance running, so we return
     671              :                 // and leave the database running.
     672            0 :                 return Ok(());
     673            0 :             }
     674              :         }
     675              : 
     676            0 :         let pg_data_path = self.env.base_data_dir.join("storage_controller_db");
     677            0 : 
     678            0 :         println!("Stopping storage controller database...");
     679            0 :         let pg_stop_args = ["-D", &pg_data_path.to_string_lossy(), "stop"];
     680            0 :         let stop_status = self.pg_ctl(pg_stop_args).await;
     681            0 :         if !stop_status.success() {
     682            0 :             match self.is_postgres_running().await {
     683              :                 Ok(false) => {
     684            0 :                     println!("Storage controller database is already stopped");
     685            0 :                     return Ok(());
     686              :                 }
     687              :                 Ok(true) => {
     688            0 :                     anyhow::bail!("Failed to stop storage controller database");
     689              :                 }
     690            0 :                 Err(err) => {
     691            0 :                     anyhow::bail!("Failed to stop storage controller database: {err}");
     692              :                 }
     693              :             }
     694            0 :         }
     695            0 : 
     696            0 :         Ok(())
     697            0 :     }
     698              : 
     699            0 :     async fn is_postgres_running(&self) -> anyhow::Result<bool> {
     700            0 :         let pg_data_path = self.env.base_data_dir.join("storage_controller_db");
     701            0 : 
     702            0 :         let pg_status_args = ["-D", &pg_data_path.to_string_lossy(), "status"];
     703            0 :         let status_exitcode = self.pg_ctl(pg_status_args).await;
     704              : 
     705              :         // pg_ctl status returns this exit code if postgres is not running: in this case it is
     706              :         // fine that stop failed.  Otherwise it is an error that stop failed.
     707              :         const PG_STATUS_NOT_RUNNING: i32 = 3;
     708              :         const PG_NO_DATA_DIR: i32 = 4;
     709              :         const PG_STATUS_RUNNING: i32 = 0;
     710            0 :         match status_exitcode.code() {
     711            0 :             Some(PG_STATUS_NOT_RUNNING) => Ok(false),
     712            0 :             Some(PG_NO_DATA_DIR) => Ok(false),
     713            0 :             Some(PG_STATUS_RUNNING) => Ok(true),
     714            0 :             Some(code) => Err(anyhow::anyhow!(
     715            0 :                 "pg_ctl status returned unexpected status code: {:?}",
     716            0 :                 code
     717            0 :             )),
     718            0 :             None => Err(anyhow::anyhow!("pg_ctl status returned no status code")),
     719              :         }
     720            0 :     }
     721              : 
     722            0 :     fn get_claims_for_path(path: &str) -> anyhow::Result<Option<Claims>> {
     723            0 :         let category = match path.find('/') {
     724            0 :             Some(idx) => &path[..idx],
     725            0 :             None => path,
     726              :         };
     727              : 
     728            0 :         match category {
     729            0 :             "status" | "ready" => Ok(None),
     730            0 :             "control" | "debug" => Ok(Some(Claims::new(None, Scope::Admin))),
     731            0 :             "v1" => Ok(Some(Claims::new(None, Scope::PageServerApi))),
     732            0 :             _ => Err(anyhow::anyhow!("Failed to determine claims for {}", path)),
     733              :         }
     734            0 :     }
     735              : 
     736              :     /// Simple HTTP request wrapper for calling into storage controller
     737            0 :     async fn dispatch<RQ, RS>(
     738            0 :         &self,
     739            0 :         method: reqwest::Method,
     740            0 :         path: String,
     741            0 :         body: Option<RQ>,
     742            0 :     ) -> anyhow::Result<RS>
     743            0 :     where
     744            0 :         RQ: Serialize + Sized,
     745            0 :         RS: DeserializeOwned + Sized,
     746            0 :     {
     747              :         // In the special case of the `storage_controller start` subcommand, we wish
     748              :         // to use the API endpoint of the newly started storage controller in order
     749              :         // to pass the readiness check. In this scenario [`Self::listen_port`] will
     750              :         // be set (see [`Self::start`]).
     751              :         //
     752              :         // Otherwise, we infer the storage controller api endpoint from the configured
     753              :         // control plane API.
     754            0 :         let port = if let Some(port) = self.listen_port.get() {
     755            0 :             *port
     756              :         } else {
     757            0 :             self.env.control_plane_api.port().unwrap()
     758              :         };
     759              : 
     760              :         // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out
     761              :         // for general purpose API access.
     762            0 :         let url = Url::from_str(&format!(
     763            0 :             "{}://{}:{port}/{path}",
     764            0 :             self.env.control_plane_api.scheme(),
     765            0 :             self.env.control_plane_api.host_str().unwrap(),
     766            0 :         ))
     767            0 :         .unwrap();
     768            0 : 
     769            0 :         let mut builder = self.client.request(method, url);
     770            0 :         if let Some(body) = body {
     771            0 :             builder = builder.json(&body)
     772            0 :         }
     773            0 :         if let Some(private_key) = &self.private_key {
     774            0 :             println!("Getting claims for path {}", path);
     775            0 :             if let Some(required_claims) = Self::get_claims_for_path(&path)? {
     776            0 :                 println!("Got claims {:?} for path {}", required_claims, path);
     777            0 :                 let jwt_token = encode_from_key_file(&required_claims, private_key)?;
     778            0 :                 builder = builder.header(
     779            0 :                     reqwest::header::AUTHORIZATION,
     780            0 :                     format!("Bearer {jwt_token}"),
     781            0 :                 );
     782            0 :             }
     783            0 :         }
     784              : 
     785            0 :         let response = builder.send().await?;
     786            0 :         let response = response.error_from_body().await?;
     787              : 
     788            0 :         Ok(response
     789            0 :             .json()
     790            0 :             .await
     791            0 :             .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)?)
     792            0 :     }
     793              : 
     794              :     /// Call into the attach_hook API, for use before handing out attachments to pageservers
     795              :     #[instrument(skip(self))]
     796              :     pub async fn attach_hook(
     797              :         &self,
     798              :         tenant_shard_id: TenantShardId,
     799              :         pageserver_id: NodeId,
     800              :     ) -> anyhow::Result<Option<u32>> {
     801              :         let request = AttachHookRequest {
     802              :             tenant_shard_id,
     803              :             node_id: Some(pageserver_id),
     804              :             generation_override: None,
     805              :             config: None,
     806              :         };
     807              : 
     808              :         let response = self
     809              :             .dispatch::<_, AttachHookResponse>(
     810              :                 Method::POST,
     811              :                 "debug/v1/attach-hook".to_string(),
     812              :                 Some(request),
     813              :             )
     814              :             .await?;
     815              : 
     816              :         Ok(response.generation)
     817              :     }
     818              : 
     819              :     #[instrument(skip(self))]
     820              :     pub async fn inspect(
     821              :         &self,
     822              :         tenant_shard_id: TenantShardId,
     823              :     ) -> anyhow::Result<Option<(u32, NodeId)>> {
     824              :         let request = InspectRequest { tenant_shard_id };
     825              : 
     826              :         let response = self
     827              :             .dispatch::<_, InspectResponse>(
     828              :                 Method::POST,
     829              :                 "debug/v1/inspect".to_string(),
     830              :                 Some(request),
     831              :             )
     832              :             .await?;
     833              : 
     834              :         Ok(response.attachment)
     835              :     }
     836              : 
     837              :     #[instrument(skip(self))]
     838              :     pub async fn tenant_create(
     839              :         &self,
     840              :         req: TenantCreateRequest,
     841              :     ) -> anyhow::Result<TenantCreateResponse> {
     842              :         self.dispatch(Method::POST, "v1/tenant".to_string(), Some(req))
     843              :             .await
     844              :     }
     845              : 
     846              :     #[instrument(skip(self))]
     847              :     pub async fn tenant_import(&self, tenant_id: TenantId) -> anyhow::Result<TenantCreateResponse> {
     848              :         self.dispatch::<(), TenantCreateResponse>(
     849              :             Method::POST,
     850              :             format!("debug/v1/tenant/{tenant_id}/import"),
     851              :             None,
     852              :         )
     853              :         .await
     854              :     }
     855              : 
     856              :     #[instrument(skip(self))]
     857              :     pub async fn tenant_locate(&self, tenant_id: TenantId) -> anyhow::Result<TenantLocateResponse> {
     858              :         self.dispatch::<(), _>(
     859              :             Method::GET,
     860              :             format!("debug/v1/tenant/{tenant_id}/locate"),
     861              :             None,
     862              :         )
     863              :         .await
     864              :     }
     865              : 
     866              :     #[instrument(skip_all, fields(node_id=%req.node_id))]
     867              :     pub async fn node_register(&self, req: NodeRegisterRequest) -> anyhow::Result<()> {
     868              :         self.dispatch::<_, ()>(Method::POST, "control/v1/node".to_string(), Some(req))
     869              :             .await
     870              :     }
     871              : 
     872              :     #[instrument(skip_all, fields(node_id=%req.node_id))]
     873              :     pub async fn node_configure(&self, req: NodeConfigureRequest) -> anyhow::Result<()> {
     874              :         self.dispatch::<_, ()>(
     875              :             Method::PUT,
     876              :             format!("control/v1/node/{}/config", req.node_id),
     877              :             Some(req),
     878              :         )
     879              :         .await
     880              :     }
     881              : 
     882            0 :     pub async fn node_list(&self) -> anyhow::Result<Vec<NodeDescribeResponse>> {
     883            0 :         self.dispatch::<(), Vec<NodeDescribeResponse>>(
     884            0 :             Method::GET,
     885            0 :             "control/v1/node".to_string(),
     886            0 :             None,
     887            0 :         )
     888            0 :         .await
     889            0 :     }
     890              : 
     891              :     #[instrument(skip(self))]
     892              :     pub async fn ready(&self) -> anyhow::Result<()> {
     893              :         self.dispatch::<(), ()>(Method::GET, "ready".to_string(), None)
     894              :             .await
     895              :     }
     896              : 
     897              :     #[instrument(skip_all, fields(%tenant_id, timeline_id=%req.new_timeline_id))]
     898              :     pub async fn tenant_timeline_create(
     899              :         &self,
     900              :         tenant_id: TenantId,
     901              :         req: TimelineCreateRequest,
     902              :     ) -> anyhow::Result<TimelineInfo> {
     903              :         self.dispatch(
     904              :             Method::POST,
     905              :             format!("v1/tenant/{tenant_id}/timeline"),
     906              :             Some(req),
     907              :         )
     908              :         .await
     909              :     }
     910              : 
     911            0 :     pub async fn set_tenant_config(&self, req: &TenantConfigRequest) -> anyhow::Result<()> {
     912            0 :         self.dispatch(Method::PUT, "v1/tenant/config".to_string(), Some(req))
     913            0 :             .await
     914            0 :     }
     915              : }
        

Generated by: LCOV version 2.1-beta