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};
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) -> 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 : || self.pg_isready(&pg_bin_dir),
276 0 : )
277 0 : .await?;
278 :
279 : // Run migrations on every startup, in case something changed.
280 0 : let database_url = self.setup_database().await?;
281 :
282 0 : let mut args = vec![
283 0 : "-l",
284 0 : &self.listen,
285 0 : "-p",
286 0 : self.path.as_ref(),
287 0 : "--dev",
288 0 : "--database-url",
289 0 : &database_url,
290 0 : "--max-unavailable-interval",
291 0 : &humantime::Duration::from(self.config.max_unavailable).to_string(),
292 0 : ]
293 0 : .into_iter()
294 0 : .map(|s| s.to_string())
295 0 : .collect::<Vec<_>>();
296 0 : if let Some(private_key) = &self.private_key {
297 0 : let claims = Claims::new(None, Scope::PageServerApi);
298 0 : let jwt_token =
299 0 : encode_from_key_file(&claims, private_key).expect("failed to generate jwt token");
300 0 : args.push(format!("--jwt-token={jwt_token}"));
301 0 : }
302 :
303 0 : if let Some(public_key) = &self.public_key {
304 0 : args.push(format!("--public-key=\"{public_key}\""));
305 0 : }
306 :
307 0 : if let Some(control_plane_compute_hook_api) = &self.env.control_plane_compute_hook_api {
308 0 : args.push(format!(
309 0 : "--compute-hook-url={control_plane_compute_hook_api}"
310 0 : ));
311 0 : }
312 :
313 0 : if let Some(split_threshold) = self.config.split_threshold.as_ref() {
314 0 : args.push(format!("--split-threshold={split_threshold}"))
315 0 : }
316 :
317 0 : args.push(format!(
318 0 : "--neon-local-repo-dir={}",
319 0 : self.env.base_data_dir.display()
320 0 : ));
321 0 :
322 0 : background_process::start_process(
323 0 : COMMAND,
324 0 : &self.env.base_data_dir,
325 0 : &self.env.storage_controller_bin(),
326 0 : args,
327 0 : [],
328 0 : background_process::InitialPidFile::Create(self.pid_file()),
329 0 : || async {
330 0 : match self.ready().await {
331 0 : Ok(_) => Ok(true),
332 0 : Err(_) => Ok(false),
333 0 : }
334 0 : },
335 0 : )
336 0 : .await?;
337 :
338 0 : Ok(())
339 0 : }
340 :
341 0 : pub async fn stop(&self, immediate: bool) -> anyhow::Result<()> {
342 0 : background_process::stop_process(immediate, COMMAND, &self.pid_file())?;
343 :
344 0 : let pg_data_path = self.env.base_data_dir.join("storage_controller_db");
345 0 : let pg_bin_dir = self.get_pg_bin_dir().await?;
346 :
347 0 : println!("Stopping storage controller database...");
348 0 : let pg_stop_args = ["-D", &pg_data_path.to_string_lossy(), "stop"];
349 0 : let stop_status = Command::new(pg_bin_dir.join("pg_ctl"))
350 0 : .args(pg_stop_args)
351 0 : .spawn()?
352 0 : .wait()
353 0 : .await?;
354 0 : if !stop_status.success() {
355 0 : let pg_status_args = ["-D", &pg_data_path.to_string_lossy(), "status"];
356 0 : let status_exitcode = Command::new(pg_bin_dir.join("pg_ctl"))
357 0 : .args(pg_status_args)
358 0 : .spawn()?
359 0 : .wait()
360 0 : .await?;
361 :
362 : // pg_ctl status returns this exit code if postgres is not running: in this case it is
363 : // fine that stop failed. Otherwise it is an error that stop failed.
364 : const PG_STATUS_NOT_RUNNING: i32 = 3;
365 0 : if Some(PG_STATUS_NOT_RUNNING) == status_exitcode.code() {
366 0 : println!("Storage controller database is already stopped");
367 0 : return Ok(());
368 : } else {
369 0 : anyhow::bail!("Failed to stop storage controller database: {stop_status}")
370 : }
371 0 : }
372 0 :
373 0 : Ok(())
374 0 : }
375 :
376 0 : fn get_claims_for_path(path: &str) -> anyhow::Result<Option<Claims>> {
377 0 : let category = match path.find('/') {
378 0 : Some(idx) => &path[..idx],
379 0 : None => path,
380 : };
381 :
382 0 : match category {
383 0 : "status" | "ready" => Ok(None),
384 0 : "control" | "debug" => Ok(Some(Claims::new(None, Scope::Admin))),
385 0 : "v1" => Ok(Some(Claims::new(None, Scope::PageServerApi))),
386 0 : _ => Err(anyhow::anyhow!("Failed to determine claims for {}", path)),
387 : }
388 0 : }
389 :
390 : /// Simple HTTP request wrapper for calling into storage controller
391 0 : async fn dispatch<RQ, RS>(
392 0 : &self,
393 0 : method: reqwest::Method,
394 0 : path: String,
395 0 : body: Option<RQ>,
396 0 : ) -> anyhow::Result<RS>
397 0 : where
398 0 : RQ: Serialize + Sized,
399 0 : RS: DeserializeOwned + Sized,
400 0 : {
401 0 : // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out
402 0 : // for general purpose API access.
403 0 : let listen_url = self.env.control_plane_api.clone().unwrap();
404 0 : let url = Url::from_str(&format!(
405 0 : "http://{}:{}/{path}",
406 0 : listen_url.host_str().unwrap(),
407 0 : listen_url.port().unwrap()
408 0 : ))
409 0 : .unwrap();
410 0 :
411 0 : let mut builder = self.client.request(method, url);
412 0 : if let Some(body) = body {
413 0 : builder = builder.json(&body)
414 0 : }
415 0 : if let Some(private_key) = &self.private_key {
416 0 : println!("Getting claims for path {}", path);
417 0 : if let Some(required_claims) = Self::get_claims_for_path(&path)? {
418 0 : println!("Got claims {:?} for path {}", required_claims, path);
419 0 : let jwt_token = encode_from_key_file(&required_claims, private_key)?;
420 0 : builder = builder.header(
421 0 : reqwest::header::AUTHORIZATION,
422 0 : format!("Bearer {jwt_token}"),
423 0 : );
424 0 : }
425 0 : }
426 :
427 0 : let response = builder.send().await?;
428 0 : let response = response.error_from_body().await?;
429 :
430 0 : Ok(response
431 0 : .json()
432 0 : .await
433 0 : .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)?)
434 0 : }
435 :
436 : /// Call into the attach_hook API, for use before handing out attachments to pageservers
437 0 : #[instrument(skip(self))]
438 : pub async fn attach_hook(
439 : &self,
440 : tenant_shard_id: TenantShardId,
441 : pageserver_id: NodeId,
442 : ) -> anyhow::Result<Option<u32>> {
443 : let request = AttachHookRequest {
444 : tenant_shard_id,
445 : node_id: Some(pageserver_id),
446 : generation_override: None,
447 : };
448 :
449 : let response = self
450 : .dispatch::<_, AttachHookResponse>(
451 : Method::POST,
452 : "debug/v1/attach-hook".to_string(),
453 : Some(request),
454 : )
455 : .await?;
456 :
457 : Ok(response.gen)
458 : }
459 :
460 0 : #[instrument(skip(self))]
461 : pub async fn inspect(
462 : &self,
463 : tenant_shard_id: TenantShardId,
464 : ) -> anyhow::Result<Option<(u32, NodeId)>> {
465 : let request = InspectRequest { tenant_shard_id };
466 :
467 : let response = self
468 : .dispatch::<_, InspectResponse>(
469 : Method::POST,
470 : "debug/v1/inspect".to_string(),
471 : Some(request),
472 : )
473 : .await?;
474 :
475 : Ok(response.attachment)
476 : }
477 :
478 0 : #[instrument(skip(self))]
479 : pub async fn tenant_create(
480 : &self,
481 : req: TenantCreateRequest,
482 : ) -> anyhow::Result<TenantCreateResponse> {
483 : self.dispatch(Method::POST, "v1/tenant".to_string(), Some(req))
484 : .await
485 : }
486 :
487 0 : #[instrument(skip(self))]
488 : pub async fn tenant_import(&self, tenant_id: TenantId) -> anyhow::Result<TenantCreateResponse> {
489 : self.dispatch::<(), TenantCreateResponse>(
490 : Method::POST,
491 : format!("debug/v1/tenant/{tenant_id}/import"),
492 : None,
493 : )
494 : .await
495 : }
496 :
497 0 : #[instrument(skip(self))]
498 : pub async fn tenant_locate(&self, tenant_id: TenantId) -> anyhow::Result<TenantLocateResponse> {
499 : self.dispatch::<(), _>(
500 : Method::GET,
501 : format!("debug/v1/tenant/{tenant_id}/locate"),
502 : None,
503 : )
504 : .await
505 : }
506 :
507 0 : #[instrument(skip(self))]
508 : pub async fn tenant_migrate(
509 : &self,
510 : tenant_shard_id: TenantShardId,
511 : node_id: NodeId,
512 : ) -> anyhow::Result<TenantShardMigrateResponse> {
513 : self.dispatch(
514 : Method::PUT,
515 : format!("control/v1/tenant/{tenant_shard_id}/migrate"),
516 : Some(TenantShardMigrateRequest {
517 : tenant_shard_id,
518 : node_id,
519 : }),
520 : )
521 : .await
522 : }
523 :
524 0 : #[instrument(skip(self), fields(%tenant_id, %new_shard_count))]
525 : pub async fn tenant_split(
526 : &self,
527 : tenant_id: TenantId,
528 : new_shard_count: u8,
529 : new_stripe_size: Option<ShardStripeSize>,
530 : ) -> anyhow::Result<TenantShardSplitResponse> {
531 : self.dispatch(
532 : Method::PUT,
533 : format!("control/v1/tenant/{tenant_id}/shard_split"),
534 : Some(TenantShardSplitRequest {
535 : new_shard_count,
536 : new_stripe_size,
537 : }),
538 : )
539 : .await
540 : }
541 :
542 0 : #[instrument(skip_all, fields(node_id=%req.node_id))]
543 : pub async fn node_register(&self, req: NodeRegisterRequest) -> anyhow::Result<()> {
544 : self.dispatch::<_, ()>(Method::POST, "control/v1/node".to_string(), Some(req))
545 : .await
546 : }
547 :
548 0 : #[instrument(skip_all, fields(node_id=%req.node_id))]
549 : pub async fn node_configure(&self, req: NodeConfigureRequest) -> anyhow::Result<()> {
550 : self.dispatch::<_, ()>(
551 : Method::PUT,
552 : format!("control/v1/node/{}/config", req.node_id),
553 : Some(req),
554 : )
555 : .await
556 : }
557 :
558 0 : #[instrument(skip(self))]
559 : pub async fn ready(&self) -> anyhow::Result<()> {
560 : self.dispatch::<(), ()>(Method::GET, "ready".to_string(), None)
561 : .await
562 : }
563 :
564 0 : #[instrument(skip_all, fields(%tenant_id, timeline_id=%req.new_timeline_id))]
565 : pub async fn tenant_timeline_create(
566 : &self,
567 : tenant_id: TenantId,
568 : req: TimelineCreateRequest,
569 : ) -> anyhow::Result<TimelineInfo> {
570 : self.dispatch(
571 : Method::POST,
572 : format!("v1/tenant/{tenant_id}/timeline"),
573 : Some(req),
574 : )
575 : .await
576 : }
577 : }
|