LCOV - code coverage report
Current view: top level - control_plane/src - storage_controller.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 0.0 % 518 0
Test Date: 2024-10-22 22:13:45 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 hyper0::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 = [
     350            0 :                     "--pgdata",
     351            0 :                     pg_data_path.as_ref(),
     352            0 :                     "--username",
     353            0 :                     &username(),
     354            0 :                     "--no-sync",
     355            0 :                     "--no-instructions",
     356            0 :                 ];
     357            0 :                 tracing::info!(
     358            0 :                     "Initializing storage controller database with args: {:?}",
     359              :                     initdb_args
     360              :                 );
     361              : 
     362              :                 // Initialize empty database
     363            0 :                 let initdb_path = pg_bin_dir.join("initdb");
     364            0 :                 let mut child = Command::new(&initdb_path)
     365            0 :                     .envs(vec![
     366            0 :                         ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     367            0 :                         ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     368            0 :                     ])
     369            0 :                     .args(initdb_args)
     370            0 :                     .spawn()
     371            0 :                     .expect("Failed to spawn initdb");
     372            0 :                 let status = child.wait().await?;
     373            0 :                 if !status.success() {
     374            0 :                     anyhow::bail!("initdb failed with status {status}");
     375            0 :                 }
     376            0 :             };
     377              : 
     378              :             // Write a minimal config file:
     379              :             // - Specify the port, since this is chosen dynamically
     380              :             // - Switch off fsync, since we're running on lightweight test environments and when e.g. scale testing
     381              :             //   the storage controller we don't want a slow local disk to interfere with that.
     382              :             //
     383              :             // NB: it's important that we rewrite this file on each start command so we propagate changes
     384              :             // from `LocalEnv`'s config file (`.neon/config`).
     385            0 :             tokio::fs::write(
     386            0 :                 &pg_data_path.join("postgresql.conf"),
     387            0 :                 format!("port = {}\nfsync=off\n", postgres_port),
     388            0 :             )
     389            0 :             .await?;
     390              : 
     391            0 :             println!("Starting storage controller database...");
     392            0 :             let db_start_args = [
     393            0 :                 "-w",
     394            0 :                 "-D",
     395            0 :                 pg_data_path.as_ref(),
     396            0 :                 "-l",
     397            0 :                 pg_log_path.as_ref(),
     398            0 :                 "-U",
     399            0 :                 &username(),
     400            0 :                 "start",
     401            0 :             ];
     402            0 :             tracing::info!(
     403            0 :                 "Starting storage controller database with args: {:?}",
     404              :                 db_start_args
     405              :             );
     406              : 
     407            0 :             background_process::start_process(
     408            0 :                 "storage_controller_db",
     409            0 :                 &self.env.base_data_dir,
     410            0 :                 pg_bin_dir.join("pg_ctl").as_std_path(),
     411            0 :                 db_start_args,
     412            0 :                 vec![
     413            0 :                     ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     414            0 :                     ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     415            0 :                 ],
     416            0 :                 background_process::InitialPidFile::Create(self.postgres_pid_file()),
     417            0 :                 &start_args.start_timeout,
     418            0 :                 || self.pg_isready(&pg_bin_dir, postgres_port),
     419            0 :             )
     420            0 :             .await?;
     421              : 
     422            0 :             self.setup_database(postgres_port).await?;
     423            0 :         }
     424              : 
     425            0 :         let database_url = format!("postgresql://localhost:{}/{DB_NAME}", postgres_port);
     426            0 : 
     427            0 :         // We support running a startup SQL script to fiddle with the database before we launch storcon.
     428            0 :         // This is used by the test suite.
     429            0 :         let startup_script_path = self
     430            0 :             .env
     431            0 :             .base_data_dir
     432            0 :             .join("storage_controller_db.startup.sql");
     433            0 :         let startup_script = match tokio::fs::read_to_string(&startup_script_path).await {
     434            0 :             Ok(script) => {
     435            0 :                 tokio::fs::remove_file(startup_script_path).await?;
     436            0 :                 script
     437              :             }
     438            0 :             Err(e) => {
     439            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
     440              :                     // always run some startup script so that this code path doesn't bit rot
     441            0 :                     "BEGIN; COMMIT;".to_string()
     442              :                 } else {
     443            0 :                     anyhow::bail!("Failed to read startup script: {e}")
     444              :                 }
     445              :             }
     446              :         };
     447            0 :         let (mut client, conn) = self.connect_to_database(postgres_port).await?;
     448            0 :         let conn = tokio::spawn(conn);
     449            0 :         let tx = client.build_transaction();
     450            0 :         let tx = tx.start().await?;
     451            0 :         tx.batch_execute(&startup_script).await?;
     452            0 :         tx.commit().await?;
     453            0 :         drop(client);
     454            0 :         conn.await??;
     455              : 
     456            0 :         let listen = self
     457            0 :             .listen
     458            0 :             .get()
     459            0 :             .expect("cell is set earlier in this function");
     460            0 :         let address_for_peers = Uri::builder()
     461            0 :             .scheme("http")
     462            0 :             .authority(format!("{}:{}", listen.ip(), listen.port()))
     463            0 :             .path_and_query("")
     464            0 :             .build()
     465            0 :             .unwrap();
     466            0 : 
     467            0 :         let mut args = vec![
     468            0 :             "-l",
     469            0 :             &listen.to_string(),
     470            0 :             "--dev",
     471            0 :             "--database-url",
     472            0 :             &database_url,
     473            0 :             "--max-offline-interval",
     474            0 :             &humantime::Duration::from(self.config.max_offline).to_string(),
     475            0 :             "--max-warming-up-interval",
     476            0 :             &humantime::Duration::from(self.config.max_warming_up).to_string(),
     477            0 :             "--heartbeat-interval",
     478            0 :             &humantime::Duration::from(self.config.heartbeat_interval).to_string(),
     479            0 :             "--address-for-peers",
     480            0 :             &address_for_peers.to_string(),
     481            0 :         ]
     482            0 :         .into_iter()
     483            0 :         .map(|s| s.to_string())
     484            0 :         .collect::<Vec<_>>();
     485            0 : 
     486            0 :         if self.config.start_as_candidate {
     487            0 :             args.push("--start-as-candidate".to_string());
     488            0 :         }
     489              : 
     490            0 :         if let Some(private_key) = &self.private_key {
     491            0 :             let claims = Claims::new(None, Scope::PageServerApi);
     492            0 :             let jwt_token =
     493            0 :                 encode_from_key_file(&claims, private_key).expect("failed to generate jwt token");
     494            0 :             args.push(format!("--jwt-token={jwt_token}"));
     495            0 : 
     496            0 :             let peer_claims = Claims::new(None, Scope::Admin);
     497            0 :             let peer_jwt_token = encode_from_key_file(&peer_claims, private_key)
     498            0 :                 .expect("failed to generate jwt token");
     499            0 :             args.push(format!("--peer-jwt-token={peer_jwt_token}"));
     500            0 :         }
     501              : 
     502            0 :         if let Some(public_key) = &self.public_key {
     503            0 :             args.push(format!("--public-key=\"{public_key}\""));
     504            0 :         }
     505              : 
     506            0 :         if let Some(control_plane_compute_hook_api) = &self.env.control_plane_compute_hook_api {
     507            0 :             args.push(format!(
     508            0 :                 "--compute-hook-url={control_plane_compute_hook_api}"
     509            0 :             ));
     510            0 :         }
     511              : 
     512            0 :         if let Some(split_threshold) = self.config.split_threshold.as_ref() {
     513            0 :             args.push(format!("--split-threshold={split_threshold}"))
     514            0 :         }
     515              : 
     516            0 :         if let Some(lag) = self.config.max_secondary_lag_bytes.as_ref() {
     517            0 :             args.push(format!("--max-secondary-lag-bytes={lag}"))
     518            0 :         }
     519              : 
     520            0 :         if let Some(threshold) = self.config.long_reconcile_threshold {
     521            0 :             args.push(format!(
     522            0 :                 "--long-reconcile-threshold={}",
     523            0 :                 humantime::Duration::from(threshold)
     524            0 :             ))
     525            0 :         }
     526              : 
     527            0 :         args.push(format!(
     528            0 :             "--neon-local-repo-dir={}",
     529            0 :             self.env.base_data_dir.display()
     530            0 :         ));
     531            0 : 
     532            0 :         background_process::start_process(
     533            0 :             COMMAND,
     534            0 :             &instance_dir,
     535            0 :             &self.env.storage_controller_bin(),
     536            0 :             args,
     537            0 :             vec![
     538            0 :                 ("LD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     539            0 :                 ("DYLD_LIBRARY_PATH".to_owned(), pg_lib_dir.to_string()),
     540            0 :             ],
     541            0 :             background_process::InitialPidFile::Create(self.pid_file(start_args.instance_id)),
     542            0 :             &start_args.start_timeout,
     543            0 :             || async {
     544            0 :                 match self.ready().await {
     545            0 :                     Ok(_) => Ok(true),
     546            0 :                     Err(_) => Ok(false),
     547              :                 }
     548            0 :             },
     549            0 :         )
     550            0 :         .await?;
     551              : 
     552            0 :         Ok(())
     553            0 :     }
     554              : 
     555            0 :     pub async fn stop(&self, stop_args: NeonStorageControllerStopArgs) -> anyhow::Result<()> {
     556            0 :         background_process::stop_process(
     557            0 :             stop_args.immediate,
     558            0 :             COMMAND,
     559            0 :             &self.pid_file(stop_args.instance_id),
     560            0 :         )?;
     561              : 
     562            0 :         let storcon_instances = self.env.storage_controller_instances().await?;
     563            0 :         for (instance_id, instanced_dir_path) in storcon_instances {
     564            0 :             if instance_id == stop_args.instance_id {
     565            0 :                 continue;
     566            0 :             }
     567            0 : 
     568            0 :             let pid_file = instanced_dir_path.join("storage_controller.pid");
     569            0 :             let pid = tokio::fs::read_to_string(&pid_file)
     570            0 :                 .await
     571            0 :                 .map_err(|err| {
     572            0 :                     anyhow::anyhow!("Failed to read storcon pid file at {pid_file:?}: {err}")
     573            0 :                 })?
     574            0 :                 .parse::<i32>()
     575            0 :                 .expect("pid is valid i32");
     576              : 
     577            0 :             let other_proc_alive = !background_process::process_has_stopped(Pid::from_raw(pid))?;
     578            0 :             if other_proc_alive {
     579              :                 // There is another storage controller instance running, so we return
     580              :                 // and leave the database running.
     581            0 :                 return Ok(());
     582            0 :             }
     583              :         }
     584              : 
     585            0 :         let pg_data_path = self.env.base_data_dir.join("storage_controller_db");
     586            0 :         let pg_bin_dir = self.get_pg_bin_dir().await?;
     587              : 
     588            0 :         println!("Stopping storage controller database...");
     589            0 :         let pg_stop_args = ["-D", &pg_data_path.to_string_lossy(), "stop"];
     590            0 :         let stop_status = Command::new(pg_bin_dir.join("pg_ctl"))
     591            0 :             .args(pg_stop_args)
     592            0 :             .spawn()?
     593            0 :             .wait()
     594            0 :             .await?;
     595            0 :         if !stop_status.success() {
     596            0 :             match self.is_postgres_running().await {
     597              :                 Ok(false) => {
     598            0 :                     println!("Storage controller database is already stopped");
     599            0 :                     return Ok(());
     600              :                 }
     601              :                 Ok(true) => {
     602            0 :                     anyhow::bail!("Failed to stop storage controller database");
     603              :                 }
     604            0 :                 Err(err) => {
     605            0 :                     anyhow::bail!("Failed to stop storage controller database: {err}");
     606              :                 }
     607              :             }
     608            0 :         }
     609            0 : 
     610            0 :         Ok(())
     611            0 :     }
     612              : 
     613            0 :     async fn is_postgres_running(&self) -> anyhow::Result<bool> {
     614            0 :         let pg_data_path = self.env.base_data_dir.join("storage_controller_db");
     615            0 :         let pg_bin_dir = self.get_pg_bin_dir().await?;
     616              : 
     617            0 :         let pg_status_args = ["-D", &pg_data_path.to_string_lossy(), "status"];
     618            0 :         let status_exitcode = Command::new(pg_bin_dir.join("pg_ctl"))
     619            0 :             .args(pg_status_args)
     620            0 :             .spawn()?
     621            0 :             .wait()
     622            0 :             .await?;
     623              : 
     624              :         // pg_ctl status returns this exit code if postgres is not running: in this case it is
     625              :         // fine that stop failed.  Otherwise it is an error that stop failed.
     626              :         const PG_STATUS_NOT_RUNNING: i32 = 3;
     627              :         const PG_NO_DATA_DIR: i32 = 4;
     628              :         const PG_STATUS_RUNNING: i32 = 0;
     629            0 :         match status_exitcode.code() {
     630            0 :             Some(PG_STATUS_NOT_RUNNING) => Ok(false),
     631            0 :             Some(PG_NO_DATA_DIR) => Ok(false),
     632            0 :             Some(PG_STATUS_RUNNING) => Ok(true),
     633            0 :             Some(code) => Err(anyhow::anyhow!(
     634            0 :                 "pg_ctl status returned unexpected status code: {:?}",
     635            0 :                 code
     636            0 :             )),
     637            0 :             None => Err(anyhow::anyhow!("pg_ctl status returned no status code")),
     638              :         }
     639            0 :     }
     640              : 
     641            0 :     fn get_claims_for_path(path: &str) -> anyhow::Result<Option<Claims>> {
     642            0 :         let category = match path.find('/') {
     643            0 :             Some(idx) => &path[..idx],
     644            0 :             None => path,
     645              :         };
     646              : 
     647            0 :         match category {
     648            0 :             "status" | "ready" => Ok(None),
     649            0 :             "control" | "debug" => Ok(Some(Claims::new(None, Scope::Admin))),
     650            0 :             "v1" => Ok(Some(Claims::new(None, Scope::PageServerApi))),
     651            0 :             _ => Err(anyhow::anyhow!("Failed to determine claims for {}", path)),
     652              :         }
     653            0 :     }
     654              : 
     655              :     /// Simple HTTP request wrapper for calling into storage controller
     656            0 :     async fn dispatch<RQ, RS>(
     657            0 :         &self,
     658            0 :         method: reqwest::Method,
     659            0 :         path: String,
     660            0 :         body: Option<RQ>,
     661            0 :     ) -> anyhow::Result<RS>
     662            0 :     where
     663            0 :         RQ: Serialize + Sized,
     664            0 :         RS: DeserializeOwned + Sized,
     665            0 :     {
     666              :         // In the special case of the `storage_controller start` subcommand, we wish
     667              :         // to use the API endpoint of the newly started storage controller in order
     668              :         // to pass the readiness check. In this scenario [`Self::listen`] will be set
     669              :         // (see [`Self::start`]).
     670              :         //
     671              :         // Otherwise, we infer the storage controller api endpoint from the configured
     672              :         // control plane API.
     673            0 :         let url = if let Some(socket_addr) = self.listen.get() {
     674            0 :             Url::from_str(&format!(
     675            0 :                 "http://{}:{}/{path}",
     676            0 :                 socket_addr.ip().to_canonical(),
     677            0 :                 socket_addr.port()
     678            0 :             ))
     679            0 :             .unwrap()
     680              :         } else {
     681              :             // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out
     682              :             // for general purpose API access.
     683            0 :             let listen_url = self.env.control_plane_api.clone().unwrap();
     684            0 :             Url::from_str(&format!(
     685            0 :                 "http://{}:{}/{path}",
     686            0 :                 listen_url.host_str().unwrap(),
     687            0 :                 listen_url.port().unwrap()
     688            0 :             ))
     689            0 :             .unwrap()
     690              :         };
     691              : 
     692            0 :         let mut builder = self.client.request(method, url);
     693            0 :         if let Some(body) = body {
     694            0 :             builder = builder.json(&body)
     695            0 :         }
     696            0 :         if let Some(private_key) = &self.private_key {
     697            0 :             println!("Getting claims for path {}", path);
     698            0 :             if let Some(required_claims) = Self::get_claims_for_path(&path)? {
     699            0 :                 println!("Got claims {:?} for path {}", required_claims, path);
     700            0 :                 let jwt_token = encode_from_key_file(&required_claims, private_key)?;
     701            0 :                 builder = builder.header(
     702            0 :                     reqwest::header::AUTHORIZATION,
     703            0 :                     format!("Bearer {jwt_token}"),
     704            0 :                 );
     705            0 :             }
     706            0 :         }
     707              : 
     708            0 :         let response = builder.send().await?;
     709            0 :         let response = response.error_from_body().await?;
     710              : 
     711            0 :         Ok(response
     712            0 :             .json()
     713            0 :             .await
     714            0 :             .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)?)
     715            0 :     }
     716              : 
     717              :     /// Call into the attach_hook API, for use before handing out attachments to pageservers
     718            0 :     #[instrument(skip(self))]
     719              :     pub async fn attach_hook(
     720              :         &self,
     721              :         tenant_shard_id: TenantShardId,
     722              :         pageserver_id: NodeId,
     723              :     ) -> anyhow::Result<Option<u32>> {
     724              :         let request = AttachHookRequest {
     725              :             tenant_shard_id,
     726              :             node_id: Some(pageserver_id),
     727              :             generation_override: None,
     728              :         };
     729              : 
     730              :         let response = self
     731              :             .dispatch::<_, AttachHookResponse>(
     732              :                 Method::POST,
     733              :                 "debug/v1/attach-hook".to_string(),
     734              :                 Some(request),
     735              :             )
     736              :             .await?;
     737              : 
     738              :         Ok(response.gen)
     739              :     }
     740              : 
     741            0 :     #[instrument(skip(self))]
     742              :     pub async fn inspect(
     743              :         &self,
     744              :         tenant_shard_id: TenantShardId,
     745              :     ) -> anyhow::Result<Option<(u32, NodeId)>> {
     746              :         let request = InspectRequest { tenant_shard_id };
     747              : 
     748              :         let response = self
     749              :             .dispatch::<_, InspectResponse>(
     750              :                 Method::POST,
     751              :                 "debug/v1/inspect".to_string(),
     752              :                 Some(request),
     753              :             )
     754              :             .await?;
     755              : 
     756              :         Ok(response.attachment)
     757              :     }
     758              : 
     759            0 :     #[instrument(skip(self))]
     760              :     pub async fn tenant_create(
     761              :         &self,
     762              :         req: TenantCreateRequest,
     763              :     ) -> anyhow::Result<TenantCreateResponse> {
     764              :         self.dispatch(Method::POST, "v1/tenant".to_string(), Some(req))
     765              :             .await
     766              :     }
     767              : 
     768            0 :     #[instrument(skip(self))]
     769              :     pub async fn tenant_import(&self, tenant_id: TenantId) -> anyhow::Result<TenantCreateResponse> {
     770              :         self.dispatch::<(), TenantCreateResponse>(
     771              :             Method::POST,
     772              :             format!("debug/v1/tenant/{tenant_id}/import"),
     773              :             None,
     774              :         )
     775              :         .await
     776              :     }
     777              : 
     778            0 :     #[instrument(skip(self))]
     779              :     pub async fn tenant_locate(&self, tenant_id: TenantId) -> anyhow::Result<TenantLocateResponse> {
     780              :         self.dispatch::<(), _>(
     781              :             Method::GET,
     782              :             format!("debug/v1/tenant/{tenant_id}/locate"),
     783              :             None,
     784              :         )
     785              :         .await
     786              :     }
     787              : 
     788            0 :     #[instrument(skip(self))]
     789              :     pub async fn tenant_migrate(
     790              :         &self,
     791              :         tenant_shard_id: TenantShardId,
     792              :         node_id: NodeId,
     793              :     ) -> anyhow::Result<TenantShardMigrateResponse> {
     794              :         self.dispatch(
     795              :             Method::PUT,
     796              :             format!("control/v1/tenant/{tenant_shard_id}/migrate"),
     797              :             Some(TenantShardMigrateRequest {
     798              :                 tenant_shard_id,
     799              :                 node_id,
     800              :             }),
     801              :         )
     802              :         .await
     803              :     }
     804              : 
     805            0 :     #[instrument(skip(self), fields(%tenant_id, %new_shard_count))]
     806              :     pub async fn tenant_split(
     807              :         &self,
     808              :         tenant_id: TenantId,
     809              :         new_shard_count: u8,
     810              :         new_stripe_size: Option<ShardStripeSize>,
     811              :     ) -> anyhow::Result<TenantShardSplitResponse> {
     812              :         self.dispatch(
     813              :             Method::PUT,
     814              :             format!("control/v1/tenant/{tenant_id}/shard_split"),
     815              :             Some(TenantShardSplitRequest {
     816              :                 new_shard_count,
     817              :                 new_stripe_size,
     818              :             }),
     819              :         )
     820              :         .await
     821              :     }
     822              : 
     823            0 :     #[instrument(skip_all, fields(node_id=%req.node_id))]
     824              :     pub async fn node_register(&self, req: NodeRegisterRequest) -> anyhow::Result<()> {
     825              :         self.dispatch::<_, ()>(Method::POST, "control/v1/node".to_string(), Some(req))
     826              :             .await
     827              :     }
     828              : 
     829            0 :     #[instrument(skip_all, fields(node_id=%req.node_id))]
     830              :     pub async fn node_configure(&self, req: NodeConfigureRequest) -> anyhow::Result<()> {
     831              :         self.dispatch::<_, ()>(
     832              :             Method::PUT,
     833              :             format!("control/v1/node/{}/config", req.node_id),
     834              :             Some(req),
     835              :         )
     836              :         .await
     837              :     }
     838              : 
     839            0 :     pub async fn node_list(&self) -> anyhow::Result<Vec<NodeDescribeResponse>> {
     840            0 :         self.dispatch::<(), Vec<NodeDescribeResponse>>(
     841            0 :             Method::GET,
     842            0 :             "control/v1/node".to_string(),
     843            0 :             None,
     844            0 :         )
     845            0 :         .await
     846            0 :     }
     847              : 
     848            0 :     #[instrument(skip(self))]
     849              :     pub async fn ready(&self) -> anyhow::Result<()> {
     850              :         self.dispatch::<(), ()>(Method::GET, "ready".to_string(), None)
     851              :             .await
     852              :     }
     853              : 
     854            0 :     #[instrument(skip_all, fields(%tenant_id, timeline_id=%req.new_timeline_id))]
     855              :     pub async fn tenant_timeline_create(
     856              :         &self,
     857              :         tenant_id: TenantId,
     858              :         req: TimelineCreateRequest,
     859              :     ) -> anyhow::Result<TimelineInfo> {
     860              :         self.dispatch(
     861              :             Method::POST,
     862              :             format!("v1/tenant/{tenant_id}/timeline"),
     863              :             Some(req),
     864              :         )
     865              :         .await
     866              :     }
     867              : }
        

Generated by: LCOV version 2.1-beta