Line data Source code
1 : //! This module is responsible for locating and loading paths in a local setup.
2 : //!
3 : //! Now it also provides init method which acts like a stub for proper installation
4 : //! script which will use local paths.
5 :
6 : use std::collections::HashMap;
7 : use std::net::SocketAddr;
8 : use std::path::{Path, PathBuf};
9 : use std::process::{Command, Stdio};
10 : use std::time::Duration;
11 : use std::{env, fs};
12 :
13 : use anyhow::{Context, bail};
14 : use clap::ValueEnum;
15 : use pem::Pem;
16 : use postgres_backend::AuthType;
17 : use reqwest::{Certificate, Url};
18 : use serde::{Deserialize, Serialize};
19 : use utils::auth::encode_from_key_file;
20 : use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId};
21 :
22 : use crate::broker::StorageBroker;
23 : use crate::endpoint_storage::{ENDPOINT_STORAGE_REMOTE_STORAGE_DIR, EndpointStorage};
24 : use crate::pageserver::{PAGESERVER_REMOTE_STORAGE_DIR, PageServerNode};
25 : use crate::safekeeper::SafekeeperNode;
26 :
27 : pub const DEFAULT_PG_VERSION: u32 = 17;
28 :
29 : //
30 : // This data structures represents neon_local CLI config
31 : //
32 : // It is deserialized from the .neon/config file, or the config file passed
33 : // to 'neon_local init --config=<path>' option. See control_plane/simple.conf for
34 : // an example.
35 : //
36 : #[derive(PartialEq, Eq, Clone, Debug)]
37 : pub struct LocalEnv {
38 : // Base directory for all the nodes (the pageserver, safekeepers and
39 : // compute endpoints).
40 : //
41 : // This is not stored in the config file. Rather, this is the path where the
42 : // config file itself is. It is read from the NEON_REPO_DIR env variable which
43 : // must be an absolute path. If the env var is not set, $PWD/.neon is used.
44 : pub base_data_dir: PathBuf,
45 :
46 : // Path to postgres distribution. It's expected that "bin", "include",
47 : // "lib", "share" from postgres distribution are there. If at some point
48 : // in time we will be able to run against vanilla postgres we may split that
49 : // to four separate paths and match OS-specific installation layout.
50 : pub pg_distrib_dir: PathBuf,
51 :
52 : // Path to pageserver binary.
53 : pub neon_distrib_dir: PathBuf,
54 :
55 : // Default tenant ID to use with the 'neon_local' command line utility, when
56 : // --tenant_id is not explicitly specified.
57 : pub default_tenant_id: Option<TenantId>,
58 :
59 : // used to issue tokens during e.g pg start
60 : pub private_key_path: PathBuf,
61 : /// Path to environment's public key
62 : pub public_key_path: PathBuf,
63 :
64 : pub broker: NeonBroker,
65 :
66 : // Configuration for the storage controller (1 per neon_local environment)
67 : pub storage_controller: NeonStorageControllerConf,
68 :
69 : /// This Vec must always contain at least one pageserver
70 : /// Populdated by [`Self::load_config`] from the individual `pageserver.toml`s.
71 : /// NB: not used anymore except for informing users that they need to change their `.neon/config`.
72 : pub pageservers: Vec<PageServerConf>,
73 :
74 : pub safekeepers: Vec<SafekeeperConf>,
75 :
76 : pub endpoint_storage: EndpointStorageConf,
77 :
78 : // Control plane upcall API for pageserver: if None, we will not run storage_controller If set, this will
79 : // be propagated into each pageserver's configuration.
80 : pub control_plane_api: Url,
81 :
82 : // Control plane upcall APIs for storage controller. If set, this will be propagated into the
83 : // storage controller's configuration.
84 : pub control_plane_hooks_api: Option<Url>,
85 :
86 : /// Keep human-readable aliases in memory (and persist them to config), to hide ZId hex strings from the user.
87 : // A `HashMap<String, HashMap<TenantId, TimelineId>>` would be more appropriate here,
88 : // but deserialization into a generic toml object as `toml::Value::try_from` fails with an error.
89 : // https://toml.io/en/v1.0.0 does not contain a concept of "a table inside another table".
90 : pub branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
91 :
92 : /// Flag to generate SSL certificates for components that need it.
93 : /// Also generates root CA certificate that is used to sign all other certificates.
94 : pub generate_local_ssl_certs: bool,
95 : }
96 :
97 : /// On-disk state stored in `.neon/config`.
98 0 : #[derive(PartialEq, Eq, Clone, Debug, Default, Serialize, Deserialize)]
99 : #[serde(default, deny_unknown_fields)]
100 : pub struct OnDiskConfig {
101 : pub pg_distrib_dir: PathBuf,
102 : pub neon_distrib_dir: PathBuf,
103 : pub default_tenant_id: Option<TenantId>,
104 : pub private_key_path: PathBuf,
105 : pub public_key_path: PathBuf,
106 : pub broker: NeonBroker,
107 : pub storage_controller: NeonStorageControllerConf,
108 : #[serde(
109 : skip_serializing,
110 : deserialize_with = "fail_if_pageservers_field_specified"
111 : )]
112 : pub pageservers: Vec<PageServerConf>,
113 : pub safekeepers: Vec<SafekeeperConf>,
114 : pub endpoint_storage: EndpointStorageConf,
115 : pub control_plane_api: Option<Url>,
116 : pub control_plane_hooks_api: Option<Url>,
117 : pub control_plane_compute_hook_api: Option<Url>,
118 : branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
119 : // Note: skip serializing because in compat tests old storage controller fails
120 : // to load new config file. May be removed after this field is in release branch.
121 : #[serde(skip_serializing_if = "std::ops::Not::not")]
122 : pub generate_local_ssl_certs: bool,
123 : }
124 :
125 0 : fn fail_if_pageservers_field_specified<'de, D>(_: D) -> Result<Vec<PageServerConf>, D::Error>
126 0 : where
127 0 : D: serde::Deserializer<'de>,
128 0 : {
129 0 : Err(serde::de::Error::custom(
130 0 : "The 'pageservers' field is no longer used; pageserver.toml is now authoritative; \
131 0 : Please remove the `pageservers` from your .neon/config.",
132 0 : ))
133 0 : }
134 :
135 : /// The description of the neon_local env to be initialized by `neon_local init --config`.
136 0 : #[derive(Clone, Debug, Deserialize)]
137 : #[serde(deny_unknown_fields)]
138 : pub struct NeonLocalInitConf {
139 : // TODO: do we need this? Seems unused
140 : pub pg_distrib_dir: Option<PathBuf>,
141 : // TODO: do we need this? Seems unused
142 : pub neon_distrib_dir: Option<PathBuf>,
143 : pub default_tenant_id: TenantId,
144 : pub broker: NeonBroker,
145 : pub storage_controller: Option<NeonStorageControllerConf>,
146 : pub pageservers: Vec<NeonLocalInitPageserverConf>,
147 : pub safekeepers: Vec<SafekeeperConf>,
148 : pub endpoint_storage: EndpointStorageConf,
149 : pub control_plane_api: Option<Url>,
150 : pub control_plane_hooks_api: Option<Url>,
151 : pub generate_local_ssl_certs: bool,
152 : }
153 :
154 0 : #[derive(Serialize, Default, Deserialize, PartialEq, Eq, Clone, Debug)]
155 : #[serde(default)]
156 : pub struct EndpointStorageConf {
157 : pub port: u16,
158 : }
159 :
160 : /// Broker config for cluster internal communication.
161 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Default)]
162 : #[serde(default)]
163 : pub struct NeonBroker {
164 : /// Broker listen HTTP address for storage nodes coordination, e.g. '127.0.0.1:50051'.
165 : /// At least one of listen_addr or listen_https_addr must be set.
166 : pub listen_addr: Option<SocketAddr>,
167 : /// Broker listen HTTPS address for storage nodes coordination, e.g. '127.0.0.1:50051'.
168 : /// At least one of listen_addr or listen_https_addr must be set.
169 : /// listen_https_addr is preferred over listen_addr in neon_local.
170 : pub listen_https_addr: Option<SocketAddr>,
171 : }
172 :
173 : /// A part of storage controller's config the neon_local knows about.
174 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
175 : #[serde(default)]
176 : pub struct NeonStorageControllerConf {
177 : /// Heartbeat timeout before marking a node offline
178 : #[serde(with = "humantime_serde")]
179 : pub max_offline: Duration,
180 :
181 : #[serde(with = "humantime_serde")]
182 : pub max_warming_up: Duration,
183 :
184 : pub start_as_candidate: bool,
185 :
186 : /// Database url used when running multiple storage controller instances
187 : pub database_url: Option<SocketAddr>,
188 :
189 : /// Thresholds for auto-splitting a tenant into shards.
190 : pub split_threshold: Option<u64>,
191 : pub max_split_shards: Option<u8>,
192 : pub initial_split_threshold: Option<u64>,
193 : pub initial_split_shards: Option<u8>,
194 :
195 : pub max_secondary_lag_bytes: Option<u64>,
196 :
197 : #[serde(with = "humantime_serde")]
198 : pub heartbeat_interval: Duration,
199 :
200 : #[serde(with = "humantime_serde")]
201 : pub long_reconcile_threshold: Option<Duration>,
202 :
203 : pub use_https_pageserver_api: bool,
204 :
205 : pub timelines_onto_safekeepers: bool,
206 :
207 : pub use_https_safekeeper_api: bool,
208 :
209 : pub use_local_compute_notifications: bool,
210 : }
211 :
212 : impl NeonStorageControllerConf {
213 : // Use a shorter pageserver unavailability interval than the default to speed up tests.
214 : const DEFAULT_MAX_OFFLINE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);
215 :
216 : const DEFAULT_MAX_WARMING_UP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
217 :
218 : // Very tight heartbeat interval to speed up tests
219 : const DEFAULT_HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000);
220 : }
221 :
222 : impl Default for NeonStorageControllerConf {
223 0 : fn default() -> Self {
224 0 : Self {
225 0 : max_offline: Self::DEFAULT_MAX_OFFLINE_INTERVAL,
226 0 : max_warming_up: Self::DEFAULT_MAX_WARMING_UP_INTERVAL,
227 0 : start_as_candidate: false,
228 0 : database_url: None,
229 0 : split_threshold: None,
230 0 : max_split_shards: None,
231 0 : initial_split_threshold: None,
232 0 : initial_split_shards: None,
233 0 : max_secondary_lag_bytes: None,
234 0 : heartbeat_interval: Self::DEFAULT_HEARTBEAT_INTERVAL,
235 0 : long_reconcile_threshold: None,
236 0 : use_https_pageserver_api: false,
237 0 : timelines_onto_safekeepers: false,
238 0 : use_https_safekeeper_api: false,
239 0 : use_local_compute_notifications: true,
240 0 : }
241 0 : }
242 : }
243 :
244 : impl NeonBroker {
245 0 : pub fn client_url(&self) -> Url {
246 0 : let url = if let Some(addr) = self.listen_https_addr {
247 0 : format!("https://{}", addr)
248 : } else {
249 0 : format!(
250 0 : "http://{}",
251 0 : self.listen_addr
252 0 : .expect("at least one address should be set")
253 0 : )
254 : };
255 :
256 0 : Url::parse(&url).expect("failed to construct url")
257 0 : }
258 : }
259 :
260 : // neon_local needs to know this subset of pageserver configuration.
261 : // For legacy reasons, this information is duplicated from `pageserver.toml` into `.neon/config`.
262 : // It can get stale if `pageserver.toml` is changed.
263 : // TODO(christian): don't store this at all in `.neon/config`, always load it from `pageserver.toml`
264 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
265 : #[serde(default, deny_unknown_fields)]
266 : pub struct PageServerConf {
267 : pub id: NodeId,
268 : pub listen_pg_addr: String,
269 : pub listen_http_addr: String,
270 : pub listen_https_addr: Option<String>,
271 : pub pg_auth_type: AuthType,
272 : pub http_auth_type: AuthType,
273 : pub no_sync: bool,
274 : }
275 :
276 : impl Default for PageServerConf {
277 0 : fn default() -> Self {
278 0 : Self {
279 0 : id: NodeId(0),
280 0 : listen_pg_addr: String::new(),
281 0 : listen_http_addr: String::new(),
282 0 : listen_https_addr: None,
283 0 : pg_auth_type: AuthType::Trust,
284 0 : http_auth_type: AuthType::Trust,
285 0 : no_sync: false,
286 0 : }
287 0 : }
288 : }
289 :
290 : /// The toml that can be passed to `neon_local init --config`.
291 : /// This is a subset of the `pageserver.toml` configuration.
292 : // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656)
293 0 : #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
294 : pub struct NeonLocalInitPageserverConf {
295 : pub id: NodeId,
296 : pub listen_pg_addr: String,
297 : pub listen_http_addr: String,
298 : pub listen_https_addr: Option<String>,
299 : pub pg_auth_type: AuthType,
300 : pub http_auth_type: AuthType,
301 : #[serde(default, skip_serializing_if = "std::ops::Not::not")]
302 : pub no_sync: bool,
303 : #[serde(flatten)]
304 : pub other: HashMap<String, toml::Value>,
305 : }
306 :
307 : impl From<&NeonLocalInitPageserverConf> for PageServerConf {
308 0 : fn from(conf: &NeonLocalInitPageserverConf) -> Self {
309 0 : let NeonLocalInitPageserverConf {
310 0 : id,
311 0 : listen_pg_addr,
312 0 : listen_http_addr,
313 0 : listen_https_addr,
314 0 : pg_auth_type,
315 0 : http_auth_type,
316 0 : no_sync,
317 0 : other: _,
318 0 : } = conf;
319 0 : Self {
320 0 : id: *id,
321 0 : listen_pg_addr: listen_pg_addr.clone(),
322 0 : listen_http_addr: listen_http_addr.clone(),
323 0 : listen_https_addr: listen_https_addr.clone(),
324 0 : pg_auth_type: *pg_auth_type,
325 0 : http_auth_type: *http_auth_type,
326 0 : no_sync: *no_sync,
327 0 : }
328 0 : }
329 : }
330 :
331 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
332 : #[serde(default)]
333 : pub struct SafekeeperConf {
334 : pub id: NodeId,
335 : pub pg_port: u16,
336 : pub pg_tenant_only_port: Option<u16>,
337 : pub http_port: u16,
338 : pub https_port: Option<u16>,
339 : pub sync: bool,
340 : pub remote_storage: Option<String>,
341 : pub backup_threads: Option<u32>,
342 : pub auth_enabled: bool,
343 : pub listen_addr: Option<String>,
344 : }
345 :
346 : impl Default for SafekeeperConf {
347 0 : fn default() -> Self {
348 0 : Self {
349 0 : id: NodeId(0),
350 0 : pg_port: 0,
351 0 : pg_tenant_only_port: None,
352 0 : http_port: 0,
353 0 : https_port: None,
354 0 : sync: true,
355 0 : remote_storage: None,
356 0 : backup_threads: None,
357 0 : auth_enabled: false,
358 0 : listen_addr: None,
359 0 : }
360 0 : }
361 : }
362 :
363 : #[derive(Clone, Copy)]
364 : pub enum InitForceMode {
365 : MustNotExist,
366 : EmptyDirOk,
367 : RemoveAllContents,
368 : }
369 :
370 : impl ValueEnum for InitForceMode {
371 0 : fn value_variants<'a>() -> &'a [Self] {
372 0 : &[
373 0 : Self::MustNotExist,
374 0 : Self::EmptyDirOk,
375 0 : Self::RemoveAllContents,
376 0 : ]
377 0 : }
378 :
379 0 : fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
380 0 : Some(clap::builder::PossibleValue::new(match self {
381 0 : InitForceMode::MustNotExist => "must-not-exist",
382 0 : InitForceMode::EmptyDirOk => "empty-dir-ok",
383 0 : InitForceMode::RemoveAllContents => "remove-all-contents",
384 : }))
385 0 : }
386 : }
387 :
388 : impl SafekeeperConf {
389 : /// Compute is served by port on which only tenant scoped tokens allowed, if
390 : /// it is configured.
391 0 : pub fn get_compute_port(&self) -> u16 {
392 0 : self.pg_tenant_only_port.unwrap_or(self.pg_port)
393 0 : }
394 : }
395 :
396 : impl LocalEnv {
397 0 : pub fn pg_distrib_dir_raw(&self) -> PathBuf {
398 0 : self.pg_distrib_dir.clone()
399 0 : }
400 :
401 0 : pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
402 0 : let path = self.pg_distrib_dir.clone();
403 0 :
404 0 : #[allow(clippy::manual_range_patterns)]
405 0 : match pg_version {
406 0 : 14 | 15 | 16 | 17 => Ok(path.join(format!("v{pg_version}"))),
407 0 : _ => bail!("Unsupported postgres version: {}", pg_version),
408 : }
409 0 : }
410 :
411 0 : pub fn pg_dir(&self, pg_version: u32, dir_name: &str) -> anyhow::Result<PathBuf> {
412 0 : Ok(self.pg_distrib_dir(pg_version)?.join(dir_name))
413 0 : }
414 :
415 0 : pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
416 0 : self.pg_dir(pg_version, "bin")
417 0 : }
418 :
419 0 : pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
420 0 : self.pg_dir(pg_version, "lib")
421 0 : }
422 :
423 0 : pub fn endpoint_storage_bin(&self) -> PathBuf {
424 0 : self.neon_distrib_dir.join("endpoint_storage")
425 0 : }
426 :
427 0 : pub fn pageserver_bin(&self) -> PathBuf {
428 0 : self.neon_distrib_dir.join("pageserver")
429 0 : }
430 :
431 0 : pub fn storage_controller_bin(&self) -> PathBuf {
432 0 : // Irrespective of configuration, storage controller binary is always
433 0 : // run from the same location as neon_local. This means that for compatibility
434 0 : // tests that run old pageserver/safekeeper, they still run latest storage controller.
435 0 : let neon_local_bin_dir = env::current_exe().unwrap().parent().unwrap().to_owned();
436 0 : neon_local_bin_dir.join("storage_controller")
437 0 : }
438 :
439 0 : pub fn safekeeper_bin(&self) -> PathBuf {
440 0 : self.neon_distrib_dir.join("safekeeper")
441 0 : }
442 :
443 0 : pub fn storage_broker_bin(&self) -> PathBuf {
444 0 : self.neon_distrib_dir.join("storage_broker")
445 0 : }
446 :
447 0 : pub fn endpoints_path(&self) -> PathBuf {
448 0 : self.base_data_dir.join("endpoints")
449 0 : }
450 :
451 0 : pub fn storage_broker_data_dir(&self) -> PathBuf {
452 0 : self.base_data_dir.join("storage_broker")
453 0 : }
454 :
455 0 : pub fn pageserver_data_dir(&self, pageserver_id: NodeId) -> PathBuf {
456 0 : self.base_data_dir
457 0 : .join(format!("pageserver_{pageserver_id}"))
458 0 : }
459 :
460 0 : pub fn safekeeper_data_dir(&self, data_dir_name: &str) -> PathBuf {
461 0 : self.base_data_dir.join("safekeepers").join(data_dir_name)
462 0 : }
463 :
464 0 : pub fn endpoint_storage_data_dir(&self) -> PathBuf {
465 0 : self.base_data_dir.join("endpoint_storage")
466 0 : }
467 :
468 0 : pub fn get_pageserver_conf(&self, id: NodeId) -> anyhow::Result<&PageServerConf> {
469 0 : if let Some(conf) = self.pageservers.iter().find(|node| node.id == id) {
470 0 : Ok(conf)
471 : } else {
472 0 : let have_ids = self
473 0 : .pageservers
474 0 : .iter()
475 0 : .map(|node| format!("{}:{}", node.id, node.listen_http_addr))
476 0 : .collect::<Vec<_>>();
477 0 : let joined = have_ids.join(",");
478 0 : bail!("could not find pageserver {id}, have ids {joined}")
479 : }
480 0 : }
481 :
482 0 : pub fn ssl_ca_cert_path(&self) -> Option<PathBuf> {
483 0 : if self.generate_local_ssl_certs {
484 0 : Some(self.base_data_dir.join("rootCA.crt"))
485 : } else {
486 0 : None
487 : }
488 0 : }
489 :
490 0 : pub fn ssl_ca_key_path(&self) -> Option<PathBuf> {
491 0 : if self.generate_local_ssl_certs {
492 0 : Some(self.base_data_dir.join("rootCA.key"))
493 : } else {
494 0 : None
495 : }
496 0 : }
497 :
498 0 : pub fn generate_ssl_ca_cert(&self) -> anyhow::Result<()> {
499 0 : let cert_path = self.ssl_ca_cert_path().unwrap();
500 0 : let key_path = self.ssl_ca_key_path().unwrap();
501 0 : if !fs::exists(cert_path.as_path())? {
502 0 : generate_ssl_ca_cert(cert_path.as_path(), key_path.as_path())?;
503 0 : }
504 0 : Ok(())
505 0 : }
506 :
507 0 : pub fn generate_ssl_cert(&self, cert_path: &Path, key_path: &Path) -> anyhow::Result<()> {
508 0 : self.generate_ssl_ca_cert()?;
509 0 : generate_ssl_cert(
510 0 : cert_path,
511 0 : key_path,
512 0 : self.ssl_ca_cert_path().unwrap().as_path(),
513 0 : self.ssl_ca_key_path().unwrap().as_path(),
514 0 : )
515 0 : }
516 :
517 : /// Creates HTTP client with local SSL CA certificates.
518 0 : pub fn create_http_client(&self) -> reqwest::Client {
519 0 : let ssl_ca_certs = self.ssl_ca_cert_path().map(|ssl_ca_file| {
520 0 : let buf = std::fs::read(ssl_ca_file).expect("SSL CA file should exist");
521 0 : Certificate::from_pem_bundle(&buf).expect("SSL CA file should be valid")
522 0 : });
523 0 :
524 0 : let mut http_client = reqwest::Client::builder();
525 0 : for ssl_ca_cert in ssl_ca_certs.unwrap_or_default() {
526 0 : http_client = http_client.add_root_certificate(ssl_ca_cert);
527 0 : }
528 :
529 0 : http_client
530 0 : .build()
531 0 : .expect("HTTP client should construct with no error")
532 0 : }
533 :
534 : /// Inspect the base data directory and extract the instance id and instance directory path
535 : /// for all storage controller instances
536 0 : pub async fn storage_controller_instances(&self) -> std::io::Result<Vec<(u8, PathBuf)>> {
537 0 : let mut instances = Vec::default();
538 :
539 0 : let dir = std::fs::read_dir(self.base_data_dir.clone())?;
540 0 : for dentry in dir {
541 0 : let dentry = dentry?;
542 0 : let is_dir = dentry.metadata()?.is_dir();
543 0 : let filename = dentry.file_name().into_string().unwrap();
544 0 : let parsed_instance_id = match filename.strip_prefix("storage_controller_") {
545 0 : Some(suffix) => suffix.parse::<u8>().ok(),
546 0 : None => None,
547 : };
548 :
549 0 : let is_instance_dir = is_dir && parsed_instance_id.is_some();
550 :
551 0 : if !is_instance_dir {
552 0 : continue;
553 0 : }
554 0 :
555 0 : instances.push((
556 0 : parsed_instance_id.expect("Checked previously"),
557 0 : dentry.path(),
558 0 : ));
559 : }
560 :
561 0 : Ok(instances)
562 0 : }
563 :
564 0 : pub fn register_branch_mapping(
565 0 : &mut self,
566 0 : branch_name: String,
567 0 : tenant_id: TenantId,
568 0 : timeline_id: TimelineId,
569 0 : ) -> anyhow::Result<()> {
570 0 : let existing_values = self
571 0 : .branch_name_mappings
572 0 : .entry(branch_name.clone())
573 0 : .or_default();
574 0 :
575 0 : let existing_ids = existing_values
576 0 : .iter()
577 0 : .find(|(existing_tenant_id, _)| existing_tenant_id == &tenant_id);
578 :
579 0 : if let Some((_, old_timeline_id)) = existing_ids {
580 0 : if old_timeline_id == &timeline_id {
581 0 : Ok(())
582 : } else {
583 0 : bail!(
584 0 : "branch '{branch_name}' is already mapped to timeline {old_timeline_id}, cannot map to another timeline {timeline_id}"
585 0 : );
586 : }
587 : } else {
588 0 : existing_values.push((tenant_id, timeline_id));
589 0 : Ok(())
590 : }
591 0 : }
592 :
593 0 : pub fn get_branch_timeline_id(
594 0 : &self,
595 0 : branch_name: &str,
596 0 : tenant_id: TenantId,
597 0 : ) -> Option<TimelineId> {
598 0 : self.branch_name_mappings
599 0 : .get(branch_name)?
600 0 : .iter()
601 0 : .find(|(mapped_tenant_id, _)| mapped_tenant_id == &tenant_id)
602 0 : .map(|&(_, timeline_id)| timeline_id)
603 0 : }
604 :
605 0 : pub fn timeline_name_mappings(&self) -> HashMap<TenantTimelineId, String> {
606 0 : self.branch_name_mappings
607 0 : .iter()
608 0 : .flat_map(|(name, tenant_timelines)| {
609 0 : tenant_timelines.iter().map(|&(tenant_id, timeline_id)| {
610 0 : (TenantTimelineId::new(tenant_id, timeline_id), name.clone())
611 0 : })
612 0 : })
613 0 : .collect()
614 0 : }
615 :
616 : /// Construct `Self` from on-disk state.
617 0 : pub fn load_config(repopath: &Path) -> anyhow::Result<Self> {
618 0 : if !repopath.exists() {
619 0 : bail!(
620 0 : "Neon config is not found in {}. You need to run 'neon_local init' first",
621 0 : repopath.to_str().unwrap()
622 0 : );
623 0 : }
624 :
625 : // TODO: check that it looks like a neon repository
626 :
627 : // load and parse file
628 0 : let config_file_contents = fs::read_to_string(repopath.join("config"))?;
629 0 : let on_disk_config: OnDiskConfig = toml::from_str(config_file_contents.as_str())?;
630 0 : let mut env = {
631 0 : let OnDiskConfig {
632 0 : pg_distrib_dir,
633 0 : neon_distrib_dir,
634 0 : default_tenant_id,
635 0 : private_key_path,
636 0 : public_key_path,
637 0 : broker,
638 0 : storage_controller,
639 0 : pageservers,
640 0 : safekeepers,
641 0 : control_plane_api,
642 0 : control_plane_hooks_api,
643 0 : control_plane_compute_hook_api: _,
644 0 : branch_name_mappings,
645 0 : generate_local_ssl_certs,
646 0 : endpoint_storage,
647 0 : } = on_disk_config;
648 0 : LocalEnv {
649 0 : base_data_dir: repopath.to_owned(),
650 0 : pg_distrib_dir,
651 0 : neon_distrib_dir,
652 0 : default_tenant_id,
653 0 : private_key_path,
654 0 : public_key_path,
655 0 : broker,
656 0 : storage_controller,
657 0 : pageservers,
658 0 : safekeepers,
659 0 : control_plane_api: control_plane_api.unwrap(),
660 0 : control_plane_hooks_api,
661 0 : branch_name_mappings,
662 0 : generate_local_ssl_certs,
663 0 : endpoint_storage,
664 0 : }
665 0 : };
666 0 :
667 0 : // The source of truth for pageserver configuration is the pageserver.toml.
668 0 : assert!(
669 0 : env.pageservers.is_empty(),
670 0 : "we ensure this during deserialization"
671 : );
672 0 : env.pageservers = {
673 0 : let iter = std::fs::read_dir(repopath).context("open dir")?;
674 0 : let mut pageservers = Vec::new();
675 0 : for res in iter {
676 0 : let dentry = res?;
677 : const PREFIX: &str = "pageserver_";
678 0 : let dentry_name = dentry
679 0 : .file_name()
680 0 : .into_string()
681 0 : .ok()
682 0 : .with_context(|| format!("non-utf8 dentry: {:?}", dentry.path()))
683 0 : .unwrap();
684 0 : if !dentry_name.starts_with(PREFIX) {
685 0 : continue;
686 0 : }
687 0 : if !dentry.file_type().context("determine file type")?.is_dir() {
688 0 : anyhow::bail!("expected a directory, got {:?}", dentry.path());
689 0 : }
690 0 : let id = dentry_name[PREFIX.len()..]
691 0 : .parse::<NodeId>()
692 0 : .with_context(|| format!("parse id from {:?}", dentry.path()))?;
693 : // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656)
694 0 : #[derive(serde::Serialize, serde::Deserialize)]
695 : // (allow unknown fields, unlike PageServerConf)
696 : struct PageserverConfigTomlSubset {
697 : listen_pg_addr: String,
698 : listen_http_addr: String,
699 : listen_https_addr: Option<String>,
700 : pg_auth_type: AuthType,
701 : http_auth_type: AuthType,
702 : #[serde(default)]
703 : no_sync: bool,
704 : }
705 0 : let config_toml_path = dentry.path().join("pageserver.toml");
706 0 : let config_toml: PageserverConfigTomlSubset = toml_edit::de::from_str(
707 0 : &std::fs::read_to_string(&config_toml_path)
708 0 : .with_context(|| format!("read {:?}", config_toml_path))?,
709 : )
710 0 : .context("parse pageserver.toml")?;
711 0 : let identity_toml_path = dentry.path().join("identity.toml");
712 0 : #[derive(serde::Serialize, serde::Deserialize)]
713 : struct IdentityTomlSubset {
714 : id: NodeId,
715 : }
716 0 : let identity_toml: IdentityTomlSubset = toml_edit::de::from_str(
717 0 : &std::fs::read_to_string(&identity_toml_path)
718 0 : .with_context(|| format!("read {:?}", identity_toml_path))?,
719 : )
720 0 : .context("parse identity.toml")?;
721 : let PageserverConfigTomlSubset {
722 0 : listen_pg_addr,
723 0 : listen_http_addr,
724 0 : listen_https_addr,
725 0 : pg_auth_type,
726 0 : http_auth_type,
727 0 : no_sync,
728 0 : } = config_toml;
729 0 : let IdentityTomlSubset {
730 0 : id: identity_toml_id,
731 0 : } = identity_toml;
732 0 : let conf = PageServerConf {
733 : id: {
734 0 : anyhow::ensure!(
735 0 : identity_toml_id == id,
736 0 : "id mismatch: identity.toml:id={identity_toml_id} pageserver_(.*) id={id}",
737 : );
738 0 : id
739 0 : },
740 0 : listen_pg_addr,
741 0 : listen_http_addr,
742 0 : listen_https_addr,
743 0 : pg_auth_type,
744 0 : http_auth_type,
745 0 : no_sync,
746 0 : };
747 0 : pageservers.push(conf);
748 : }
749 0 : pageservers
750 0 : };
751 0 :
752 0 : Ok(env)
753 0 : }
754 :
755 0 : pub fn persist_config(&self) -> anyhow::Result<()> {
756 0 : Self::persist_config_impl(
757 0 : &self.base_data_dir,
758 0 : &OnDiskConfig {
759 0 : pg_distrib_dir: self.pg_distrib_dir.clone(),
760 0 : neon_distrib_dir: self.neon_distrib_dir.clone(),
761 0 : default_tenant_id: self.default_tenant_id,
762 0 : private_key_path: self.private_key_path.clone(),
763 0 : public_key_path: self.public_key_path.clone(),
764 0 : broker: self.broker.clone(),
765 0 : storage_controller: self.storage_controller.clone(),
766 0 : pageservers: vec![], // it's skip_serializing anyway
767 0 : safekeepers: self.safekeepers.clone(),
768 0 : control_plane_api: Some(self.control_plane_api.clone()),
769 0 : control_plane_hooks_api: self.control_plane_hooks_api.clone(),
770 0 : control_plane_compute_hook_api: None,
771 0 : branch_name_mappings: self.branch_name_mappings.clone(),
772 0 : generate_local_ssl_certs: self.generate_local_ssl_certs,
773 0 : endpoint_storage: self.endpoint_storage.clone(),
774 0 : },
775 0 : )
776 0 : }
777 :
778 0 : pub fn persist_config_impl(base_path: &Path, config: &OnDiskConfig) -> anyhow::Result<()> {
779 0 : let conf_content = &toml::to_string_pretty(config)?;
780 0 : let target_config_path = base_path.join("config");
781 0 : fs::write(&target_config_path, conf_content).with_context(|| {
782 0 : format!(
783 0 : "Failed to write config file into path '{}'",
784 0 : target_config_path.display()
785 0 : )
786 0 : })
787 0 : }
788 :
789 : // this function is used only for testing purposes in CLI e g generate tokens during init
790 0 : pub fn generate_auth_token<S: Serialize>(&self, claims: &S) -> anyhow::Result<String> {
791 0 : let key = self.read_private_key()?;
792 0 : encode_from_key_file(claims, &key)
793 0 : }
794 :
795 : /// Get the path to the private key.
796 0 : pub fn get_private_key_path(&self) -> PathBuf {
797 0 : if self.private_key_path.is_absolute() {
798 0 : self.private_key_path.to_path_buf()
799 : } else {
800 0 : self.base_data_dir.join(&self.private_key_path)
801 : }
802 0 : }
803 :
804 : /// Get the path to the public key.
805 0 : pub fn get_public_key_path(&self) -> PathBuf {
806 0 : if self.public_key_path.is_absolute() {
807 0 : self.public_key_path.to_path_buf()
808 : } else {
809 0 : self.base_data_dir.join(&self.public_key_path)
810 : }
811 0 : }
812 :
813 : /// Read the contents of the private key file.
814 0 : pub fn read_private_key(&self) -> anyhow::Result<Pem> {
815 0 : let private_key_path = self.get_private_key_path();
816 0 : let pem = pem::parse(fs::read(private_key_path)?)?;
817 0 : Ok(pem)
818 0 : }
819 :
820 : /// Read the contents of the public key file.
821 0 : pub fn read_public_key(&self) -> anyhow::Result<Pem> {
822 0 : let public_key_path = self.get_public_key_path();
823 0 : let pem = pem::parse(fs::read(public_key_path)?)?;
824 0 : Ok(pem)
825 0 : }
826 :
827 : /// Materialize the [`NeonLocalInitConf`] to disk. Called during [`neon_local init`].
828 0 : pub fn init(conf: NeonLocalInitConf, force: &InitForceMode) -> anyhow::Result<()> {
829 0 : let base_path = base_path();
830 0 : assert_ne!(base_path, Path::new(""));
831 0 : let base_path = &base_path;
832 0 :
833 0 : // create base_path dir
834 0 : if base_path.exists() {
835 0 : match force {
836 : InitForceMode::MustNotExist => {
837 0 : bail!(
838 0 : "directory '{}' already exists. Perhaps already initialized?",
839 0 : base_path.display()
840 0 : );
841 : }
842 : InitForceMode::EmptyDirOk => {
843 0 : if let Some(res) = std::fs::read_dir(base_path)?.next() {
844 0 : res.context("check if directory is empty")?;
845 0 : anyhow::bail!("directory not empty: {base_path:?}");
846 0 : }
847 : }
848 : InitForceMode::RemoveAllContents => {
849 0 : println!("removing all contents of '{}'", base_path.display());
850 : // instead of directly calling `remove_dir_all`, we keep the original dir but removing
851 : // all contents inside. This helps if the developer symbol links another directory (i.e.,
852 : // S3 local SSD) to the `.neon` base directory.
853 0 : for entry in std::fs::read_dir(base_path)? {
854 0 : let entry = entry?;
855 0 : let path = entry.path();
856 0 : if path.is_dir() {
857 0 : fs::remove_dir_all(&path)?;
858 : } else {
859 0 : fs::remove_file(&path)?;
860 : }
861 : }
862 : }
863 : }
864 0 : }
865 0 : if !base_path.exists() {
866 0 : fs::create_dir(base_path)?;
867 0 : }
868 :
869 : let NeonLocalInitConf {
870 0 : pg_distrib_dir,
871 0 : neon_distrib_dir,
872 0 : default_tenant_id,
873 0 : broker,
874 0 : storage_controller,
875 0 : pageservers,
876 0 : safekeepers,
877 0 : control_plane_api,
878 0 : generate_local_ssl_certs,
879 0 : control_plane_hooks_api,
880 0 : endpoint_storage,
881 0 : } = conf;
882 0 :
883 0 : // Find postgres binaries.
884 0 : // Follow POSTGRES_DISTRIB_DIR if set, otherwise look in "pg_install".
885 0 : // Note that later in the code we assume, that distrib dirs follow the same pattern
886 0 : // for all postgres versions.
887 0 : let pg_distrib_dir = pg_distrib_dir.unwrap_or_else(|| {
888 0 : if let Some(postgres_bin) = env::var_os("POSTGRES_DISTRIB_DIR") {
889 0 : postgres_bin.into()
890 : } else {
891 0 : let cwd = env::current_dir().unwrap();
892 0 : cwd.join("pg_install")
893 : }
894 0 : });
895 0 :
896 0 : // Find neon binaries.
897 0 : let neon_distrib_dir = neon_distrib_dir
898 0 : .unwrap_or_else(|| env::current_exe().unwrap().parent().unwrap().to_owned());
899 0 :
900 0 : // Generate keypair for JWT.
901 0 : //
902 0 : // The keypair is only needed if authentication is enabled in any of the
903 0 : // components. For convenience, we generate the keypair even if authentication
904 0 : // is not enabled, so that you can easily enable it after the initialization
905 0 : // step.
906 0 : generate_auth_keys(
907 0 : base_path.join("auth_private_key.pem").as_path(),
908 0 : base_path.join("auth_public_key.pem").as_path(),
909 0 : )
910 0 : .context("generate auth keys")?;
911 0 : let private_key_path = PathBuf::from("auth_private_key.pem");
912 0 : let public_key_path = PathBuf::from("auth_public_key.pem");
913 0 :
914 0 : // create the runtime type because the remaining initialization code below needs
915 0 : // a LocalEnv instance op operation
916 0 : // TODO: refactor to avoid this, LocalEnv should only be constructed from on-disk state
917 0 : let env = LocalEnv {
918 0 : base_data_dir: base_path.clone(),
919 0 : pg_distrib_dir,
920 0 : neon_distrib_dir,
921 0 : default_tenant_id: Some(default_tenant_id),
922 0 : private_key_path,
923 0 : public_key_path,
924 0 : broker,
925 0 : storage_controller: storage_controller.unwrap_or_default(),
926 0 : pageservers: pageservers.iter().map(Into::into).collect(),
927 0 : safekeepers,
928 0 : control_plane_api: control_plane_api.unwrap(),
929 0 : control_plane_hooks_api,
930 0 : branch_name_mappings: Default::default(),
931 0 : generate_local_ssl_certs,
932 0 : endpoint_storage,
933 0 : };
934 0 :
935 0 : if generate_local_ssl_certs {
936 0 : env.generate_ssl_ca_cert()?;
937 0 : }
938 :
939 : // create endpoints dir
940 0 : fs::create_dir_all(env.endpoints_path())?;
941 :
942 : // create storage broker dir
943 0 : fs::create_dir_all(env.storage_broker_data_dir())?;
944 0 : StorageBroker::from_env(&env)
945 0 : .initialize()
946 0 : .context("storage broker init failed")?;
947 :
948 : // create safekeeper dirs
949 0 : for safekeeper in &env.safekeepers {
950 0 : fs::create_dir_all(SafekeeperNode::datadir_path_by_id(&env, safekeeper.id))?;
951 0 : SafekeeperNode::from_env(&env, safekeeper)
952 0 : .initialize()
953 0 : .context("safekeeper init failed")?;
954 : }
955 :
956 : // initialize pageserver state
957 0 : for (i, ps) in pageservers.into_iter().enumerate() {
958 0 : let runtime_ps = &env.pageservers[i];
959 0 : assert_eq!(&PageServerConf::from(&ps), runtime_ps);
960 0 : fs::create_dir(env.pageserver_data_dir(ps.id))?;
961 0 : PageServerNode::from_env(&env, runtime_ps)
962 0 : .initialize(ps)
963 0 : .context("pageserver init failed")?;
964 : }
965 :
966 0 : EndpointStorage::from_env(&env)
967 0 : .init()
968 0 : .context("object storage init failed")?;
969 :
970 : // setup remote remote location for default LocalFs remote storage
971 0 : std::fs::create_dir_all(env.base_data_dir.join(PAGESERVER_REMOTE_STORAGE_DIR))?;
972 0 : std::fs::create_dir_all(env.base_data_dir.join(ENDPOINT_STORAGE_REMOTE_STORAGE_DIR))?;
973 :
974 0 : env.persist_config()
975 0 : }
976 : }
977 :
978 0 : pub fn base_path() -> PathBuf {
979 0 : let path = match std::env::var_os("NEON_REPO_DIR") {
980 0 : Some(val) => {
981 0 : let path = PathBuf::from(val);
982 0 : if !path.is_absolute() {
983 : // repeat the env var in the error because our default is always absolute
984 0 : panic!("NEON_REPO_DIR must be an absolute path, got {path:?}");
985 0 : }
986 0 : path
987 : }
988 : None => {
989 0 : let pwd = std::env::current_dir()
990 0 : // technically this can fail but it's quite unlikeley
991 0 : .expect("determine current directory");
992 0 : let pwd_abs = pwd.canonicalize().expect("canonicalize current directory");
993 0 : pwd_abs.join(".neon")
994 : }
995 : };
996 0 : assert!(path.is_absolute());
997 0 : path
998 0 : }
999 :
1000 : /// Generate a public/private key pair for JWT authentication
1001 0 : fn generate_auth_keys(private_key_path: &Path, public_key_path: &Path) -> anyhow::Result<()> {
1002 : // Generate the key pair
1003 : //
1004 : // openssl genpkey -algorithm ed25519 -out auth_private_key.pem
1005 0 : let keygen_output = Command::new("openssl")
1006 0 : .arg("genpkey")
1007 0 : .args(["-algorithm", "ed25519"])
1008 0 : .args(["-out", private_key_path.to_str().unwrap()])
1009 0 : .stdout(Stdio::null())
1010 0 : .output()
1011 0 : .context("failed to generate auth private key")?;
1012 0 : if !keygen_output.status.success() {
1013 0 : bail!(
1014 0 : "openssl failed: '{}'",
1015 0 : String::from_utf8_lossy(&keygen_output.stderr)
1016 0 : );
1017 0 : }
1018 :
1019 : // Extract the public key from the private key file
1020 : //
1021 : // openssl pkey -in auth_private_key.pem -pubout -out auth_public_key.pem
1022 0 : let keygen_output = Command::new("openssl")
1023 0 : .arg("pkey")
1024 0 : .args(["-in", private_key_path.to_str().unwrap()])
1025 0 : .arg("-pubout")
1026 0 : .args(["-out", public_key_path.to_str().unwrap()])
1027 0 : .output()
1028 0 : .context("failed to extract public key from private key")?;
1029 0 : if !keygen_output.status.success() {
1030 0 : bail!(
1031 0 : "openssl failed: '{}'",
1032 0 : String::from_utf8_lossy(&keygen_output.stderr)
1033 0 : );
1034 0 : }
1035 0 :
1036 0 : Ok(())
1037 0 : }
1038 :
1039 0 : fn generate_ssl_ca_cert(cert_path: &Path, key_path: &Path) -> anyhow::Result<()> {
1040 : // openssl req -x509 -newkey rsa:2048 -nodes -subj "/CN=Neon Local CA" -days 36500 \
1041 : // -out rootCA.crt -keyout rootCA.key
1042 0 : let keygen_output = Command::new("openssl")
1043 0 : .args([
1044 0 : "req", "-x509", "-newkey", "ed25519", "-nodes", "-days", "36500",
1045 0 : ])
1046 0 : .args(["-subj", "/CN=Neon Local CA"])
1047 0 : .args(["-out", cert_path.to_str().unwrap()])
1048 0 : .args(["-keyout", key_path.to_str().unwrap()])
1049 0 : .output()
1050 0 : .context("failed to generate CA certificate")?;
1051 0 : if !keygen_output.status.success() {
1052 0 : bail!(
1053 0 : "openssl failed: '{}'",
1054 0 : String::from_utf8_lossy(&keygen_output.stderr)
1055 0 : );
1056 0 : }
1057 0 : Ok(())
1058 0 : }
1059 :
1060 0 : fn generate_ssl_cert(
1061 0 : cert_path: &Path,
1062 0 : key_path: &Path,
1063 0 : ca_cert_path: &Path,
1064 0 : ca_key_path: &Path,
1065 0 : ) -> anyhow::Result<()> {
1066 0 : // Generate Certificate Signing Request (CSR).
1067 0 : let mut csr_path = cert_path.to_path_buf();
1068 0 : csr_path.set_extension(".csr");
1069 :
1070 : // openssl req -new -nodes -newkey rsa:2048 -keyout server.key -out server.csr \
1071 : // -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
1072 0 : let keygen_output = Command::new("openssl")
1073 0 : .args(["req", "-new", "-nodes"])
1074 0 : .args(["-newkey", "ed25519"])
1075 0 : .args(["-subj", "/CN=localhost"])
1076 0 : .args(["-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"])
1077 0 : .args(["-keyout", key_path.to_str().unwrap()])
1078 0 : .args(["-out", csr_path.to_str().unwrap()])
1079 0 : .output()
1080 0 : .context("failed to generate CSR")?;
1081 0 : if !keygen_output.status.success() {
1082 0 : bail!(
1083 0 : "openssl failed: '{}'",
1084 0 : String::from_utf8_lossy(&keygen_output.stderr)
1085 0 : );
1086 0 : }
1087 :
1088 : // Sign CSR with CA key.
1089 : //
1090 : // openssl x509 -req -in server.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial \
1091 : // -out server.crt -days 36500 -copy_extensions copyall
1092 0 : let keygen_output = Command::new("openssl")
1093 0 : .args(["x509", "-req"])
1094 0 : .args(["-in", csr_path.to_str().unwrap()])
1095 0 : .args(["-CA", ca_cert_path.to_str().unwrap()])
1096 0 : .args(["-CAkey", ca_key_path.to_str().unwrap()])
1097 0 : .arg("-CAcreateserial")
1098 0 : .args(["-out", cert_path.to_str().unwrap()])
1099 0 : .args(["-days", "36500"])
1100 0 : .args(["-copy_extensions", "copyall"])
1101 0 : .output()
1102 0 : .context("failed to sign CSR")?;
1103 0 : if !keygen_output.status.success() {
1104 0 : bail!(
1105 0 : "openssl failed: '{}'",
1106 0 : String::from_utf8_lossy(&keygen_output.stderr)
1107 0 : );
1108 0 : }
1109 0 :
1110 0 : // Remove CSR file as it's not needed anymore.
1111 0 : fs::remove_file(csr_path)?;
1112 :
1113 0 : Ok(())
1114 0 : }
|