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