LCOV - code coverage report
Current view: top level - control_plane/src - storage_controller.rs (source / functions) Coverage Total Hit
Test: fc67f8dc6087a0b4f4f0bcd74f6e1dc25fab8cf3.info Lines: 0.0 % 505 0
Test Date: 2024-09-24 13:57:57 Functions: 0.0 % 97 0

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

Generated by: LCOV version 2.1-beta