Line data Source code
1 : use crate::{
2 : background_process,
3 : local_env::{LocalEnv, NeonStorageControllerConf},
4 : };
5 : use camino::{Utf8Path, Utf8PathBuf};
6 : use pageserver_api::{
7 : controller_api::{
8 : NodeConfigureRequest, NodeRegisterRequest, TenantCreateResponse, TenantLocateResponse,
9 : TenantShardMigrateRequest, TenantShardMigrateResponse,
10 : },
11 : models::{
12 : TenantCreateRequest, TenantShardSplitRequest, TenantShardSplitResponse,
13 : TimelineCreateRequest, TimelineInfo,
14 : },
15 : shard::{ShardStripeSize, TenantShardId},
16 : };
17 : use pageserver_client::mgmt_api::ResponseErrorMessageExt;
18 : use postgres_backend::AuthType;
19 : use reqwest::Method;
20 : use serde::{de::DeserializeOwned, Deserialize, Serialize};
21 : use std::{fs, str::FromStr, time::Duration};
22 : use tokio::process::Command;
23 : use tracing::instrument;
24 : use url::Url;
25 : use utils::{
26 : auth::{encode_from_key_file, Claims, Scope},
27 : id::{NodeId, TenantId},
28 : };
29 :
30 : pub struct StorageController {
31 : env: LocalEnv,
32 : listen: String,
33 : path: Utf8PathBuf,
34 : private_key: Option<Vec<u8>>,
35 : public_key: Option<String>,
36 : postgres_port: u16,
37 : client: reqwest::Client,
38 : config: NeonStorageControllerConf,
39 : }
40 :
41 : const COMMAND: &str = "storage_controller";
42 :
43 : const STORAGE_CONTROLLER_POSTGRES_VERSION: u32 = 16;
44 :
45 0 : #[derive(Serialize, Deserialize)]
46 : pub struct AttachHookRequest {
47 : pub tenant_shard_id: TenantShardId,
48 : pub node_id: Option<NodeId>,
49 : pub generation_override: Option<i32>,
50 : }
51 :
52 0 : #[derive(Serialize, Deserialize)]
53 : pub struct AttachHookResponse {
54 : pub gen: Option<u32>,
55 : }
56 :
57 0 : #[derive(Serialize, Deserialize)]
58 : pub struct InspectRequest {
59 : pub tenant_shard_id: TenantShardId,
60 : }
61 :
62 0 : #[derive(Serialize, Deserialize)]
63 : pub struct InspectResponse {
64 : pub attachment: Option<(u32, NodeId)>,
65 : }
66 :
67 : impl StorageController {
68 0 : pub fn from_env(env: &LocalEnv) -> Self {
69 0 : let path = Utf8PathBuf::from_path_buf(env.base_data_dir.clone())
70 0 : .unwrap()
71 0 : .join("attachments.json");
72 0 :
73 0 : // Makes no sense to construct this if pageservers aren't going to use it: assume
74 0 : // pageservers have control plane API set
75 0 : let listen_url = env.control_plane_api.clone().unwrap();
76 0 :
77 0 : let listen = format!(
78 0 : "{}:{}",
79 0 : listen_url.host_str().unwrap(),
80 0 : listen_url.port().unwrap()
81 0 : );
82 0 :
83 0 : // Convention: NeonEnv in python tests reserves the next port after the control_plane_api
84 0 : // port, for use by our captive postgres.
85 0 : let postgres_port = listen_url
86 0 : .port()
87 0 : .expect("Control plane API setting should always have a port")
88 0 : + 1;
89 0 :
90 0 : // Assume all pageservers have symmetric auth configuration: this service
91 0 : // expects to use one JWT token to talk to all of them.
92 0 : let ps_conf = env
93 0 : .pageservers
94 0 : .first()
95 0 : .expect("Config is validated to contain at least one pageserver");
96 0 : let (private_key, public_key) = match ps_conf.http_auth_type {
97 0 : AuthType::Trust => (None, None),
98 : AuthType::NeonJWT => {
99 0 : let private_key_path = env.get_private_key_path();
100 0 : let private_key = fs::read(private_key_path).expect("failed to read private key");
101 0 :
102 0 : // If pageserver auth is enabled, this implicitly enables auth for this service,
103 0 : // using the same credentials.
104 0 : let public_key_path =
105 0 : camino::Utf8PathBuf::try_from(env.base_data_dir.join("auth_public_key.pem"))
106 0 : .unwrap();
107 :
108 : // This service takes keys as a string rather than as a path to a file/dir: read the key into memory.
109 0 : let public_key = if std::fs::metadata(&public_key_path)
110 0 : .expect("Can't stat public key")
111 0 : .is_dir()
112 : {
113 : // Our config may specify a directory: this is for the pageserver's ability to handle multiple
114 : // keys. We only use one key at a time, so, arbitrarily load the first one in the directory.
115 0 : let mut dir =
116 0 : std::fs::read_dir(&public_key_path).expect("Can't readdir public key path");
117 0 : let dent = dir
118 0 : .next()
119 0 : .expect("Empty key dir")
120 0 : .expect("Error reading key dir");
121 0 :
122 0 : std::fs::read_to_string(dent.path()).expect("Can't read public key")
123 : } else {
124 0 : std::fs::read_to_string(&public_key_path).expect("Can't read public key")
125 : };
126 0 : (Some(private_key), Some(public_key))
127 : }
128 : };
129 :
130 0 : Self {
131 0 : env: env.clone(),
132 0 : path,
133 0 : listen,
134 0 : private_key,
135 0 : public_key,
136 0 : postgres_port,
137 0 : client: reqwest::ClientBuilder::new()
138 0 : .build()
139 0 : .expect("Failed to construct http client"),
140 0 : config: env.storage_controller.clone(),
141 0 : }
142 0 : }
143 :
144 0 : fn pid_file(&self) -> Utf8PathBuf {
145 0 : Utf8PathBuf::from_path_buf(self.env.base_data_dir.join("storage_controller.pid"))
146 0 : .expect("non-Unicode path")
147 0 : }
148 :
149 : /// PIDFile for the postgres instance used to store storage controller state
150 0 : fn postgres_pid_file(&self) -> Utf8PathBuf {
151 0 : Utf8PathBuf::from_path_buf(
152 0 : self.env
153 0 : .base_data_dir
154 0 : .join("storage_controller_postgres.pid"),
155 0 : )
156 0 : .expect("non-Unicode path")
157 0 : }
158 :
159 : /// Find the directory containing postgres binaries, such as `initdb` and `pg_ctl`
160 : ///
161 : /// This usually uses STORAGE_CONTROLLER_POSTGRES_VERSION of postgres, but will fall back
162 : /// to other versions if that one isn't found. Some automated tests create circumstances
163 : /// where only one version is available in pg_distrib_dir, such as `test_remote_extensions`.
164 0 : pub async fn get_pg_bin_dir(&self) -> anyhow::Result<Utf8PathBuf> {
165 0 : let prefer_versions = [STORAGE_CONTROLLER_POSTGRES_VERSION, 15, 14];
166 :
167 0 : for v in prefer_versions {
168 0 : let path = Utf8PathBuf::from_path_buf(self.env.pg_bin_dir(v)?).unwrap();
169 0 : if tokio::fs::try_exists(&path).await? {
170 0 : return Ok(path);
171 0 : }
172 : }
173 :
174 : // Fall through
175 0 : anyhow::bail!(
176 0 : "Postgres binaries not found in {}",
177 0 : self.env.pg_distrib_dir.display()
178 0 : );
179 0 : }
180 :
181 : /// Readiness check for our postgres process
182 0 : async fn pg_isready(&self, pg_bin_dir: &Utf8Path) -> anyhow::Result<bool> {
183 0 : let bin_path = pg_bin_dir.join("pg_isready");
184 0 : let args = ["-h", "localhost", "-p", &format!("{}", self.postgres_port)];
185 0 : let exitcode = Command::new(bin_path).args(args).spawn()?.wait().await?;
186 :
187 0 : Ok(exitcode.success())
188 0 : }
189 :
190 : /// Create our database if it doesn't exist, and run migrations.
191 : ///
192 : /// This function is equivalent to the `diesel setup` command in the diesel CLI. We implement
193 : /// the same steps by hand to avoid imposing a dependency on installing diesel-cli for developers
194 : /// who just want to run `cargo neon_local` without knowing about diesel.
195 : ///
196 : /// Returns the database url
197 0 : pub async fn setup_database(&self) -> anyhow::Result<String> {
198 0 : const DB_NAME: &str = "storage_controller";
199 0 : let database_url = format!("postgresql://localhost:{}/{DB_NAME}", self.postgres_port);
200 :
201 0 : let pg_bin_dir = self.get_pg_bin_dir().await?;
202 0 : let createdb_path = pg_bin_dir.join("createdb");
203 0 : let output = Command::new(&createdb_path)
204 0 : .args([
205 0 : "-h",
206 0 : "localhost",
207 0 : "-p",
208 0 : &format!("{}", self.postgres_port),
209 0 : DB_NAME,
210 0 : ])
211 0 : .output()
212 0 : .await
213 0 : .expect("Failed to spawn createdb");
214 0 :
215 0 : if !output.status.success() {
216 0 : let stderr = String::from_utf8(output.stderr).expect("Non-UTF8 output from createdb");
217 0 : if stderr.contains("already exists") {
218 0 : tracing::info!("Database {DB_NAME} already exists");
219 : } else {
220 0 : anyhow::bail!("createdb failed with status {}: {stderr}", output.status);
221 : }
222 0 : }
223 :
224 0 : Ok(database_url)
225 0 : }
226 :
227 0 : pub async fn start(&self, retry_timeout: &Duration) -> anyhow::Result<()> {
228 0 : // Start a vanilla Postgres process used by the storage controller for persistence.
229 0 : let pg_data_path = Utf8PathBuf::from_path_buf(self.env.base_data_dir.clone())
230 0 : .unwrap()
231 0 : .join("storage_controller_db");
232 0 : let pg_bin_dir = self.get_pg_bin_dir().await?;
233 0 : let pg_log_path = pg_data_path.join("postgres.log");
234 0 :
235 0 : if !tokio::fs::try_exists(&pg_data_path).await? {
236 : // Initialize empty database
237 0 : let initdb_path = pg_bin_dir.join("initdb");
238 0 : let mut child = Command::new(&initdb_path)
239 0 : .args(["-D", pg_data_path.as_ref()])
240 0 : .spawn()
241 0 : .expect("Failed to spawn initdb");
242 0 : let status = child.wait().await?;
243 0 : if !status.success() {
244 0 : anyhow::bail!("initdb failed with status {status}");
245 0 : }
246 0 :
247 0 : // Write a minimal config file:
248 0 : // - Specify the port, since this is chosen dynamically
249 0 : // - Switch off fsync, since we're running on lightweight test environments and when e.g. scale testing
250 0 : // the storage controller we don't want a slow local disk to interfere with that.
251 0 : tokio::fs::write(
252 0 : &pg_data_path.join("postgresql.conf"),
253 0 : format!("port = {}\nfsync=off\n", self.postgres_port),
254 0 : )
255 0 : .await?;
256 0 : };
257 :
258 0 : println!("Starting storage controller database...");
259 0 : let db_start_args = [
260 0 : "-w",
261 0 : "-D",
262 0 : pg_data_path.as_ref(),
263 0 : "-l",
264 0 : pg_log_path.as_ref(),
265 0 : "start",
266 0 : ];
267 0 :
268 0 : background_process::start_process(
269 0 : "storage_controller_db",
270 0 : &self.env.base_data_dir,
271 0 : pg_bin_dir.join("pg_ctl").as_std_path(),
272 0 : db_start_args,
273 0 : [],
274 0 : background_process::InitialPidFile::Create(self.postgres_pid_file()),
275 0 : retry_timeout,
276 0 : || self.pg_isready(&pg_bin_dir),
277 0 : )
278 0 : .await?;
279 :
280 : // Run migrations on every startup, in case something changed.
281 0 : let database_url = self.setup_database().await?;
282 :
283 0 : let mut args = vec![
284 0 : "-l",
285 0 : &self.listen,
286 0 : "-p",
287 0 : self.path.as_ref(),
288 0 : "--dev",
289 0 : "--database-url",
290 0 : &database_url,
291 0 : "--max-unavailable-interval",
292 0 : &humantime::Duration::from(self.config.max_unavailable).to_string(),
293 0 : ]
294 0 : .into_iter()
295 0 : .map(|s| s.to_string())
296 0 : .collect::<Vec<_>>();
297 0 : if let Some(private_key) = &self.private_key {
298 0 : let claims = Claims::new(None, Scope::PageServerApi);
299 0 : let jwt_token =
300 0 : encode_from_key_file(&claims, private_key).expect("failed to generate jwt token");
301 0 : args.push(format!("--jwt-token={jwt_token}"));
302 0 : }
303 :
304 0 : if let Some(public_key) = &self.public_key {
305 0 : args.push(format!("--public-key=\"{public_key}\""));
306 0 : }
307 :
308 0 : if let Some(control_plane_compute_hook_api) = &self.env.control_plane_compute_hook_api {
309 0 : args.push(format!(
310 0 : "--compute-hook-url={control_plane_compute_hook_api}"
311 0 : ));
312 0 : }
313 :
314 0 : if let Some(split_threshold) = self.config.split_threshold.as_ref() {
315 0 : args.push(format!("--split-threshold={split_threshold}"))
316 0 : }
317 :
318 0 : args.push(format!(
319 0 : "--neon-local-repo-dir={}",
320 0 : self.env.base_data_dir.display()
321 0 : ));
322 0 :
323 0 : background_process::start_process(
324 0 : COMMAND,
325 0 : &self.env.base_data_dir,
326 0 : &self.env.storage_controller_bin(),
327 0 : args,
328 0 : [],
329 0 : background_process::InitialPidFile::Create(self.pid_file()),
330 0 : retry_timeout,
331 0 : || async {
332 0 : match self.ready().await {
333 0 : Ok(_) => Ok(true),
334 0 : Err(_) => Ok(false),
335 0 : }
336 0 : },
337 0 : )
338 0 : .await?;
339 :
340 0 : Ok(())
341 0 : }
342 :
343 0 : pub async fn stop(&self, immediate: bool) -> anyhow::Result<()> {
344 0 : background_process::stop_process(immediate, COMMAND, &self.pid_file())?;
345 :
346 0 : let pg_data_path = self.env.base_data_dir.join("storage_controller_db");
347 0 : let pg_bin_dir = self.get_pg_bin_dir().await?;
348 :
349 0 : println!("Stopping storage controller database...");
350 0 : let pg_stop_args = ["-D", &pg_data_path.to_string_lossy(), "stop"];
351 0 : let stop_status = Command::new(pg_bin_dir.join("pg_ctl"))
352 0 : .args(pg_stop_args)
353 0 : .spawn()?
354 0 : .wait()
355 0 : .await?;
356 0 : if !stop_status.success() {
357 0 : let pg_status_args = ["-D", &pg_data_path.to_string_lossy(), "status"];
358 0 : let status_exitcode = Command::new(pg_bin_dir.join("pg_ctl"))
359 0 : .args(pg_status_args)
360 0 : .spawn()?
361 0 : .wait()
362 0 : .await?;
363 :
364 : // pg_ctl status returns this exit code if postgres is not running: in this case it is
365 : // fine that stop failed. Otherwise it is an error that stop failed.
366 : const PG_STATUS_NOT_RUNNING: i32 = 3;
367 0 : if Some(PG_STATUS_NOT_RUNNING) == status_exitcode.code() {
368 0 : println!("Storage controller database is already stopped");
369 0 : return Ok(());
370 : } else {
371 0 : anyhow::bail!("Failed to stop storage controller database: {stop_status}")
372 : }
373 0 : }
374 0 :
375 0 : Ok(())
376 0 : }
377 :
378 0 : fn get_claims_for_path(path: &str) -> anyhow::Result<Option<Claims>> {
379 0 : let category = match path.find('/') {
380 0 : Some(idx) => &path[..idx],
381 0 : None => path,
382 : };
383 :
384 0 : match category {
385 0 : "status" | "ready" => Ok(None),
386 0 : "control" | "debug" => Ok(Some(Claims::new(None, Scope::Admin))),
387 0 : "v1" => Ok(Some(Claims::new(None, Scope::PageServerApi))),
388 0 : _ => Err(anyhow::anyhow!("Failed to determine claims for {}", path)),
389 : }
390 0 : }
391 :
392 : /// Simple HTTP request wrapper for calling into storage controller
393 0 : async fn dispatch<RQ, RS>(
394 0 : &self,
395 0 : method: reqwest::Method,
396 0 : path: String,
397 0 : body: Option<RQ>,
398 0 : ) -> anyhow::Result<RS>
399 0 : where
400 0 : RQ: Serialize + Sized,
401 0 : RS: DeserializeOwned + Sized,
402 0 : {
403 0 : // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out
404 0 : // for general purpose API access.
405 0 : let listen_url = self.env.control_plane_api.clone().unwrap();
406 0 : let url = Url::from_str(&format!(
407 0 : "http://{}:{}/{path}",
408 0 : listen_url.host_str().unwrap(),
409 0 : listen_url.port().unwrap()
410 0 : ))
411 0 : .unwrap();
412 0 :
413 0 : let mut builder = self.client.request(method, url);
414 0 : if let Some(body) = body {
415 0 : builder = builder.json(&body)
416 0 : }
417 0 : if let Some(private_key) = &self.private_key {
418 0 : println!("Getting claims for path {}", path);
419 0 : if let Some(required_claims) = Self::get_claims_for_path(&path)? {
420 0 : println!("Got claims {:?} for path {}", required_claims, path);
421 0 : let jwt_token = encode_from_key_file(&required_claims, private_key)?;
422 0 : builder = builder.header(
423 0 : reqwest::header::AUTHORIZATION,
424 0 : format!("Bearer {jwt_token}"),
425 0 : );
426 0 : }
427 0 : }
428 :
429 0 : let response = builder.send().await?;
430 0 : let response = response.error_from_body().await?;
431 :
432 0 : Ok(response
433 0 : .json()
434 0 : .await
435 0 : .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)?)
436 0 : }
437 :
438 : /// Call into the attach_hook API, for use before handing out attachments to pageservers
439 0 : #[instrument(skip(self))]
440 : pub async fn attach_hook(
441 : &self,
442 : tenant_shard_id: TenantShardId,
443 : pageserver_id: NodeId,
444 : ) -> anyhow::Result<Option<u32>> {
445 : let request = AttachHookRequest {
446 : tenant_shard_id,
447 : node_id: Some(pageserver_id),
448 : generation_override: None,
449 : };
450 :
451 : let response = self
452 : .dispatch::<_, AttachHookResponse>(
453 : Method::POST,
454 : "debug/v1/attach-hook".to_string(),
455 : Some(request),
456 : )
457 : .await?;
458 :
459 : Ok(response.gen)
460 : }
461 :
462 0 : #[instrument(skip(self))]
463 : pub async fn inspect(
464 : &self,
465 : tenant_shard_id: TenantShardId,
466 : ) -> anyhow::Result<Option<(u32, NodeId)>> {
467 : let request = InspectRequest { tenant_shard_id };
468 :
469 : let response = self
470 : .dispatch::<_, InspectResponse>(
471 : Method::POST,
472 : "debug/v1/inspect".to_string(),
473 : Some(request),
474 : )
475 : .await?;
476 :
477 : Ok(response.attachment)
478 : }
479 :
480 0 : #[instrument(skip(self))]
481 : pub async fn tenant_create(
482 : &self,
483 : req: TenantCreateRequest,
484 : ) -> anyhow::Result<TenantCreateResponse> {
485 : self.dispatch(Method::POST, "v1/tenant".to_string(), Some(req))
486 : .await
487 : }
488 :
489 0 : #[instrument(skip(self))]
490 : pub async fn tenant_import(&self, tenant_id: TenantId) -> anyhow::Result<TenantCreateResponse> {
491 : self.dispatch::<(), TenantCreateResponse>(
492 : Method::POST,
493 : format!("debug/v1/tenant/{tenant_id}/import"),
494 : None,
495 : )
496 : .await
497 : }
498 :
499 0 : #[instrument(skip(self))]
500 : pub async fn tenant_locate(&self, tenant_id: TenantId) -> anyhow::Result<TenantLocateResponse> {
501 : self.dispatch::<(), _>(
502 : Method::GET,
503 : format!("debug/v1/tenant/{tenant_id}/locate"),
504 : None,
505 : )
506 : .await
507 : }
508 :
509 0 : #[instrument(skip(self))]
510 : pub async fn tenant_migrate(
511 : &self,
512 : tenant_shard_id: TenantShardId,
513 : node_id: NodeId,
514 : ) -> anyhow::Result<TenantShardMigrateResponse> {
515 : self.dispatch(
516 : Method::PUT,
517 : format!("control/v1/tenant/{tenant_shard_id}/migrate"),
518 : Some(TenantShardMigrateRequest {
519 : tenant_shard_id,
520 : node_id,
521 : }),
522 : )
523 : .await
524 : }
525 :
526 0 : #[instrument(skip(self), fields(%tenant_id, %new_shard_count))]
527 : pub async fn tenant_split(
528 : &self,
529 : tenant_id: TenantId,
530 : new_shard_count: u8,
531 : new_stripe_size: Option<ShardStripeSize>,
532 : ) -> anyhow::Result<TenantShardSplitResponse> {
533 : self.dispatch(
534 : Method::PUT,
535 : format!("control/v1/tenant/{tenant_id}/shard_split"),
536 : Some(TenantShardSplitRequest {
537 : new_shard_count,
538 : new_stripe_size,
539 : }),
540 : )
541 : .await
542 : }
543 :
544 0 : #[instrument(skip_all, fields(node_id=%req.node_id))]
545 : pub async fn node_register(&self, req: NodeRegisterRequest) -> anyhow::Result<()> {
546 : self.dispatch::<_, ()>(Method::POST, "control/v1/node".to_string(), Some(req))
547 : .await
548 : }
549 :
550 0 : #[instrument(skip_all, fields(node_id=%req.node_id))]
551 : pub async fn node_configure(&self, req: NodeConfigureRequest) -> anyhow::Result<()> {
552 : self.dispatch::<_, ()>(
553 : Method::PUT,
554 : format!("control/v1/node/{}/config", req.node_id),
555 : Some(req),
556 : )
557 : .await
558 : }
559 :
560 0 : #[instrument(skip(self))]
561 : pub async fn ready(&self) -> anyhow::Result<()> {
562 : self.dispatch::<(), ()>(Method::GET, "ready".to_string(), None)
563 : .await
564 : }
565 :
566 0 : #[instrument(skip_all, fields(%tenant_id, timeline_id=%req.new_timeline_id))]
567 : pub async fn tenant_timeline_create(
568 : &self,
569 : tenant_id: TenantId,
570 : req: TimelineCreateRequest,
571 : ) -> anyhow::Result<TimelineInfo> {
572 : self.dispatch(
573 : Method::POST,
574 : format!("v1/tenant/{tenant_id}/timeline"),
575 : Some(req),
576 : )
577 : .await
578 : }
579 : }
|