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

Generated by: LCOV version 2.1-beta