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