Line data Source code
1 : //! Code to manage compute endpoints
2 : //!
3 : //! In the local test environment, the data for each endpoint is stored in
4 : //!
5 : //! ```text
6 : //! .neon/endpoints/<endpoint id>
7 : //! ```
8 : //!
9 : //! Some basic information about the endpoint, like the tenant and timeline IDs,
10 : //! are stored in the `endpoint.json` file. The `endpoint.json` file is created
11 : //! when the endpoint is created, and doesn't change afterwards.
12 : //!
13 : //! The endpoint is managed by the `compute_ctl` binary. When an endpoint is
14 : //! started, we launch `compute_ctl` It synchronizes the safekeepers, downloads
15 : //! the basebackup from the pageserver to initialize the data directory, and
16 : //! finally launches the PostgreSQL process. It watches the PostgreSQL process
17 : //! until it exits.
18 : //!
19 : //! When an endpoint is created, a `postgresql.conf` file is also created in
20 : //! the endpoint's directory. The file can be modified before starting PostgreSQL.
21 : //! However, the `postgresql.conf` file in the endpoint directory is not used directly
22 : //! by PostgreSQL. It is passed to `compute_ctl`, and `compute_ctl` writes another
23 : //! copy of it in the data directory.
24 : //!
25 : //! Directory contents:
26 : //!
27 : //! ```text
28 : //! .neon/endpoints/main/
29 : //! compute.log - log output of `compute_ctl` and `postgres`
30 : //! endpoint.json - serialized `EndpointConf` struct
31 : //! postgresql.conf - postgresql settings
32 : //! config.json - passed to `compute_ctl`
33 : //! pgdata/
34 : //! postgresql.conf - copy of postgresql.conf created by `compute_ctl`
35 : //! zenith.signal
36 : //! <other PostgreSQL files>
37 : //! ```
38 : //!
39 : use std::collections::BTreeMap;
40 : use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
41 : use std::path::PathBuf;
42 : use std::process::Command;
43 : use std::str::FromStr;
44 : use std::sync::Arc;
45 : use std::time::{Duration, Instant};
46 :
47 : use anyhow::{Context, Result, anyhow, bail};
48 : use compute_api::requests::{ComputeClaims, ConfigurationRequest};
49 : use compute_api::responses::{
50 : ComputeConfig, ComputeCtlConfig, ComputeStatus, ComputeStatusResponse, TlsConfig,
51 : };
52 : use compute_api::spec::{
53 : Cluster, ComputeAudit, ComputeFeature, ComputeMode, ComputeSpec, Database, PgIdent,
54 : RemoteExtSpec, Role,
55 : };
56 : use jsonwebtoken::jwk::{
57 : AlgorithmParameters, CommonParameters, EllipticCurve, Jwk, JwkSet, KeyAlgorithm, KeyOperations,
58 : OctetKeyPairParameters, OctetKeyPairType, PublicKeyUse,
59 : };
60 : use nix::sys::signal::{Signal, kill};
61 : use pageserver_api::shard::ShardStripeSize;
62 : use pem::Pem;
63 : use reqwest::header::CONTENT_TYPE;
64 : use safekeeper_api::membership::SafekeeperGeneration;
65 : use serde::{Deserialize, Serialize};
66 : use sha2::{Digest, Sha256};
67 : use spki::der::Decode;
68 : use spki::{SubjectPublicKeyInfo, SubjectPublicKeyInfoRef};
69 : use tracing::debug;
70 : use url::Host;
71 : use utils::id::{NodeId, TenantId, TimelineId};
72 :
73 : use crate::local_env::LocalEnv;
74 : use crate::postgresql_conf::PostgresConf;
75 : use crate::storage_controller::StorageController;
76 :
77 : // contents of a endpoint.json file
78 0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
79 : pub struct EndpointConf {
80 : endpoint_id: String,
81 : tenant_id: TenantId,
82 : timeline_id: TimelineId,
83 : mode: ComputeMode,
84 : pg_port: u16,
85 : external_http_port: u16,
86 : internal_http_port: u16,
87 : pg_version: u32,
88 : skip_pg_catalog_updates: bool,
89 : reconfigure_concurrency: usize,
90 : drop_subscriptions_before_start: bool,
91 : features: Vec<ComputeFeature>,
92 : cluster: Option<Cluster>,
93 : compute_ctl_config: ComputeCtlConfig,
94 : }
95 :
96 : //
97 : // ComputeControlPlane
98 : //
99 : pub struct ComputeControlPlane {
100 : base_port: u16,
101 :
102 : // endpoint ID is the key
103 : pub endpoints: BTreeMap<String, Arc<Endpoint>>,
104 :
105 : env: LocalEnv,
106 : }
107 :
108 : impl ComputeControlPlane {
109 : // Load current endpoints from the endpoints/ subdirectories
110 0 : pub fn load(env: LocalEnv) -> Result<ComputeControlPlane> {
111 0 : let mut endpoints = BTreeMap::default();
112 0 : for endpoint_dir in std::fs::read_dir(env.endpoints_path())
113 0 : .with_context(|| format!("failed to list {}", env.endpoints_path().display()))?
114 : {
115 0 : let ep_res = Endpoint::from_dir_entry(endpoint_dir?, &env);
116 0 : let ep = match ep_res {
117 0 : Ok(ep) => ep,
118 0 : Err(e) => match e.downcast::<std::io::Error>() {
119 0 : Ok(e) => {
120 0 : // A parallel task could delete an endpoint while we have just scanned the directory
121 0 : if e.kind() == std::io::ErrorKind::NotFound {
122 0 : continue;
123 : } else {
124 0 : Err(e)?
125 : }
126 : }
127 0 : Err(e) => Err(e)?,
128 : },
129 : };
130 0 : endpoints.insert(ep.endpoint_id.clone(), Arc::new(ep));
131 : }
132 :
133 0 : Ok(ComputeControlPlane {
134 0 : base_port: 55431,
135 0 : endpoints,
136 0 : env,
137 0 : })
138 0 : }
139 :
140 0 : fn get_port(&mut self) -> u16 {
141 0 : 1 + self
142 0 : .endpoints
143 0 : .values()
144 0 : .map(|ep| std::cmp::max(ep.pg_address.port(), ep.external_http_address.port()))
145 0 : .max()
146 0 : .unwrap_or(self.base_port)
147 0 : }
148 :
149 : /// Create a JSON Web Key Set. This ideally matches the way we create a JWKS
150 : /// from the production control plane.
151 0 : fn create_jwks_from_pem(pem: &Pem) -> Result<JwkSet> {
152 0 : let spki: SubjectPublicKeyInfoRef = SubjectPublicKeyInfo::from_der(pem.contents())?;
153 0 : let public_key = spki.subject_public_key.raw_bytes();
154 0 :
155 0 : let mut hasher = Sha256::new();
156 0 : hasher.update(public_key);
157 0 : let key_hash = hasher.finalize();
158 0 :
159 0 : Ok(JwkSet {
160 0 : keys: vec![Jwk {
161 0 : common: CommonParameters {
162 0 : public_key_use: Some(PublicKeyUse::Signature),
163 0 : key_operations: Some(vec![KeyOperations::Verify]),
164 0 : key_algorithm: Some(KeyAlgorithm::EdDSA),
165 0 : key_id: Some(base64::encode_config(key_hash, base64::URL_SAFE_NO_PAD)),
166 0 : x509_url: None::<String>,
167 0 : x509_chain: None::<Vec<String>>,
168 0 : x509_sha1_fingerprint: None::<String>,
169 0 : x509_sha256_fingerprint: None::<String>,
170 0 : },
171 0 : algorithm: AlgorithmParameters::OctetKeyPair(OctetKeyPairParameters {
172 0 : key_type: OctetKeyPairType::OctetKeyPair,
173 0 : curve: EllipticCurve::Ed25519,
174 0 : x: base64::encode_config(public_key, base64::URL_SAFE_NO_PAD),
175 0 : }),
176 0 : }],
177 0 : })
178 0 : }
179 :
180 : #[allow(clippy::too_many_arguments)]
181 0 : pub fn new_endpoint(
182 0 : &mut self,
183 0 : endpoint_id: &str,
184 0 : tenant_id: TenantId,
185 0 : timeline_id: TimelineId,
186 0 : pg_port: Option<u16>,
187 0 : external_http_port: Option<u16>,
188 0 : internal_http_port: Option<u16>,
189 0 : pg_version: u32,
190 0 : mode: ComputeMode,
191 0 : skip_pg_catalog_updates: bool,
192 0 : drop_subscriptions_before_start: bool,
193 0 : ) -> Result<Arc<Endpoint>> {
194 0 : let pg_port = pg_port.unwrap_or_else(|| self.get_port());
195 0 : let external_http_port = external_http_port.unwrap_or_else(|| self.get_port() + 1);
196 0 : let internal_http_port = internal_http_port.unwrap_or_else(|| external_http_port + 1);
197 0 : let compute_ctl_config = ComputeCtlConfig {
198 0 : jwks: Self::create_jwks_from_pem(&self.env.read_public_key()?)?,
199 0 : tls: None::<TlsConfig>,
200 0 : };
201 0 : let ep = Arc::new(Endpoint {
202 0 : endpoint_id: endpoint_id.to_owned(),
203 0 : pg_address: SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), pg_port),
204 0 : external_http_address: SocketAddr::new(
205 0 : IpAddr::from(Ipv4Addr::UNSPECIFIED),
206 0 : external_http_port,
207 0 : ),
208 0 : internal_http_address: SocketAddr::new(
209 0 : IpAddr::from(Ipv4Addr::LOCALHOST),
210 0 : internal_http_port,
211 0 : ),
212 0 : env: self.env.clone(),
213 0 : timeline_id,
214 0 : mode,
215 0 : tenant_id,
216 0 : pg_version,
217 0 : // We don't setup roles and databases in the spec locally, so we don't need to
218 0 : // do catalog updates. Catalog updates also include check availability
219 0 : // data creation. Yet, we have tests that check that size and db dump
220 0 : // before and after start are the same. So, skip catalog updates,
221 0 : // with this we basically test a case of waking up an idle compute, where
222 0 : // we also skip catalog updates in the cloud.
223 0 : skip_pg_catalog_updates,
224 0 : drop_subscriptions_before_start,
225 0 : reconfigure_concurrency: 1,
226 0 : features: vec![],
227 0 : cluster: None,
228 0 : compute_ctl_config: compute_ctl_config.clone(),
229 0 : });
230 0 :
231 0 : ep.create_endpoint_dir()?;
232 : std::fs::write(
233 0 : ep.endpoint_path().join("endpoint.json"),
234 0 : serde_json::to_string_pretty(&EndpointConf {
235 0 : endpoint_id: endpoint_id.to_string(),
236 0 : tenant_id,
237 0 : timeline_id,
238 0 : mode,
239 0 : external_http_port,
240 0 : internal_http_port,
241 0 : pg_port,
242 0 : pg_version,
243 0 : skip_pg_catalog_updates,
244 0 : drop_subscriptions_before_start,
245 0 : reconfigure_concurrency: 1,
246 0 : features: vec![],
247 0 : cluster: None,
248 0 : compute_ctl_config,
249 0 : })?,
250 0 : )?;
251 : std::fs::write(
252 0 : ep.endpoint_path().join("postgresql.conf"),
253 0 : ep.setup_pg_conf()?.to_string(),
254 0 : )?;
255 :
256 0 : self.endpoints
257 0 : .insert(ep.endpoint_id.clone(), Arc::clone(&ep));
258 0 :
259 0 : Ok(ep)
260 0 : }
261 :
262 0 : pub fn check_conflicting_endpoints(
263 0 : &self,
264 0 : mode: ComputeMode,
265 0 : tenant_id: TenantId,
266 0 : timeline_id: TimelineId,
267 0 : ) -> Result<()> {
268 0 : if matches!(mode, ComputeMode::Primary) {
269 : // this check is not complete, as you could have a concurrent attempt at
270 : // creating another primary, both reading the state before checking it here,
271 : // but it's better than nothing.
272 0 : let mut duplicates = self.endpoints.iter().filter(|(_k, v)| {
273 0 : v.tenant_id == tenant_id
274 0 : && v.timeline_id == timeline_id
275 0 : && v.mode == mode
276 0 : && v.status() != EndpointStatus::Stopped
277 0 : });
278 :
279 0 : if let Some((key, _)) = duplicates.next() {
280 0 : bail!(
281 0 : "attempting to create a duplicate primary endpoint on tenant {tenant_id}, timeline {timeline_id}: endpoint {key:?} exists already. please don't do this, it is not supported."
282 0 : );
283 0 : }
284 0 : }
285 0 : Ok(())
286 0 : }
287 : }
288 :
289 : ///////////////////////////////////////////////////////////////////////////////
290 :
291 : pub struct Endpoint {
292 : /// used as the directory name
293 : endpoint_id: String,
294 : pub tenant_id: TenantId,
295 : pub timeline_id: TimelineId,
296 : pub mode: ComputeMode,
297 :
298 : // port and address of the Postgres server and `compute_ctl`'s HTTP APIs
299 : pub pg_address: SocketAddr,
300 : pub external_http_address: SocketAddr,
301 : pub internal_http_address: SocketAddr,
302 :
303 : // postgres major version in the format: 14, 15, etc.
304 : pg_version: u32,
305 :
306 : // These are not part of the endpoint as such, but the environment
307 : // the endpoint runs in.
308 : pub env: LocalEnv,
309 :
310 : // Optimizations
311 : skip_pg_catalog_updates: bool,
312 :
313 : drop_subscriptions_before_start: bool,
314 : reconfigure_concurrency: usize,
315 : // Feature flags
316 : features: Vec<ComputeFeature>,
317 : // Cluster settings
318 : cluster: Option<Cluster>,
319 :
320 : /// The compute_ctl config for the endpoint's compute.
321 : compute_ctl_config: ComputeCtlConfig,
322 : }
323 :
324 : #[derive(PartialEq, Eq)]
325 : pub enum EndpointStatus {
326 : Running,
327 : Stopped,
328 : Crashed,
329 : RunningNoPidfile,
330 : }
331 :
332 : impl std::fmt::Display for EndpointStatus {
333 0 : fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
334 0 : let s = match self {
335 0 : Self::Running => "running",
336 0 : Self::Stopped => "stopped",
337 0 : Self::Crashed => "crashed",
338 0 : Self::RunningNoPidfile => "running, no pidfile",
339 : };
340 0 : write!(writer, "{}", s)
341 0 : }
342 : }
343 :
344 : impl Endpoint {
345 0 : fn from_dir_entry(entry: std::fs::DirEntry, env: &LocalEnv) -> Result<Endpoint> {
346 0 : if !entry.file_type()?.is_dir() {
347 0 : anyhow::bail!(
348 0 : "Endpoint::from_dir_entry failed: '{}' is not a directory",
349 0 : entry.path().display()
350 0 : );
351 0 : }
352 0 :
353 0 : // parse data directory name
354 0 : let fname = entry.file_name();
355 0 : let endpoint_id = fname.to_str().unwrap().to_string();
356 :
357 : // Read the endpoint.json file
358 0 : let conf: EndpointConf =
359 0 : serde_json::from_slice(&std::fs::read(entry.path().join("endpoint.json"))?)?;
360 :
361 0 : debug!("serialized endpoint conf: {:?}", conf);
362 :
363 0 : Ok(Endpoint {
364 0 : pg_address: SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), conf.pg_port),
365 0 : external_http_address: SocketAddr::new(
366 0 : IpAddr::from(Ipv4Addr::UNSPECIFIED),
367 0 : conf.external_http_port,
368 0 : ),
369 0 : internal_http_address: SocketAddr::new(
370 0 : IpAddr::from(Ipv4Addr::LOCALHOST),
371 0 : conf.internal_http_port,
372 0 : ),
373 0 : endpoint_id,
374 0 : env: env.clone(),
375 0 : timeline_id: conf.timeline_id,
376 0 : mode: conf.mode,
377 0 : tenant_id: conf.tenant_id,
378 0 : pg_version: conf.pg_version,
379 0 : skip_pg_catalog_updates: conf.skip_pg_catalog_updates,
380 0 : reconfigure_concurrency: conf.reconfigure_concurrency,
381 0 : drop_subscriptions_before_start: conf.drop_subscriptions_before_start,
382 0 : features: conf.features,
383 0 : cluster: conf.cluster,
384 0 : compute_ctl_config: conf.compute_ctl_config,
385 0 : })
386 0 : }
387 :
388 0 : fn create_endpoint_dir(&self) -> Result<()> {
389 0 : std::fs::create_dir_all(self.endpoint_path()).with_context(|| {
390 0 : format!(
391 0 : "could not create endpoint directory {}",
392 0 : self.endpoint_path().display()
393 0 : )
394 0 : })
395 0 : }
396 :
397 : // Generate postgresql.conf with default configuration
398 0 : fn setup_pg_conf(&self) -> Result<PostgresConf> {
399 0 : let mut conf = PostgresConf::new();
400 0 : conf.append("max_wal_senders", "10");
401 0 : conf.append("wal_log_hints", "off");
402 0 : conf.append("max_replication_slots", "10");
403 0 : conf.append("hot_standby", "on");
404 0 : // Set to 1MB to both exercise getPage requests/LFC, and still have enough room for
405 0 : // Postgres to operate. Everything smaller might be not enough for Postgres under load,
406 0 : // and can cause errors like 'no unpinned buffers available', see
407 0 : // <https://github.com/neondatabase/neon/issues/9956>
408 0 : conf.append("shared_buffers", "1MB");
409 0 : // Postgres defaults to effective_io_concurrency=1, which does not exercise the pageserver's
410 0 : // batching logic. Set this to 2 so that we exercise the code a bit without letting
411 0 : // individual tests do a lot of concurrent work on underpowered test machines
412 0 : conf.append("effective_io_concurrency", "2");
413 0 : conf.append("fsync", "off");
414 0 : conf.append("max_connections", "100");
415 0 : conf.append("wal_level", "logical");
416 0 : // wal_sender_timeout is the maximum time to wait for WAL replication.
417 0 : // It also defines how often the walreciever will send a feedback message to the wal sender.
418 0 : conf.append("wal_sender_timeout", "5s");
419 0 : conf.append("listen_addresses", &self.pg_address.ip().to_string());
420 0 : conf.append("port", &self.pg_address.port().to_string());
421 0 : conf.append("wal_keep_size", "0");
422 0 : // walproposer panics when basebackup is invalid, it is pointless to restart in this case.
423 0 : conf.append("restart_after_crash", "off");
424 0 :
425 0 : // Load the 'neon' extension
426 0 : conf.append("shared_preload_libraries", "neon");
427 0 :
428 0 : conf.append_line("");
429 0 : // Replication-related configurations, such as WAL sending
430 0 : match &self.mode {
431 : ComputeMode::Primary => {
432 : // Configure backpressure
433 : // - Replication write lag depends on how fast the walreceiver can process incoming WAL.
434 : // This lag determines latency of get_page_at_lsn. Speed of applying WAL is about 10MB/sec,
435 : // so to avoid expiration of 1 minute timeout, this lag should not be larger than 600MB.
436 : // Actually latency should be much smaller (better if < 1sec). But we assume that recently
437 : // updates pages are not requested from pageserver.
438 : // - Replication flush lag depends on speed of persisting data by checkpointer (creation of
439 : // delta/image layers) and advancing disk_consistent_lsn. Safekeepers are able to
440 : // remove/archive WAL only beyond disk_consistent_lsn. Too large a lag can cause long
441 : // recovery time (in case of pageserver crash) and disk space overflow at safekeepers.
442 : // - Replication apply lag depends on speed of uploading changes to S3 by uploader thread.
443 : // To be able to restore database in case of pageserver node crash, safekeeper should not
444 : // remove WAL beyond this point. Too large lag can cause space exhaustion in safekeepers
445 : // (if they are not able to upload WAL to S3).
446 0 : conf.append("max_replication_write_lag", "15MB");
447 0 : conf.append("max_replication_flush_lag", "10GB");
448 0 :
449 0 : if !self.env.safekeepers.is_empty() {
450 0 : // Configure Postgres to connect to the safekeepers
451 0 : conf.append("synchronous_standby_names", "walproposer");
452 0 :
453 0 : let safekeepers = self
454 0 : .env
455 0 : .safekeepers
456 0 : .iter()
457 0 : .map(|sk| format!("localhost:{}", sk.get_compute_port()))
458 0 : .collect::<Vec<String>>()
459 0 : .join(",");
460 0 : conf.append("neon.safekeepers", &safekeepers);
461 0 : } else {
462 0 : // We only use setup without safekeepers for tests,
463 0 : // and don't care about data durability on pageserver,
464 0 : // so set more relaxed synchronous_commit.
465 0 : conf.append("synchronous_commit", "remote_write");
466 0 :
467 0 : // Configure the node to stream WAL directly to the pageserver
468 0 : // This isn't really a supported configuration, but can be useful for
469 0 : // testing.
470 0 : conf.append("synchronous_standby_names", "pageserver");
471 0 : }
472 : }
473 0 : ComputeMode::Static(lsn) => {
474 0 : conf.append("recovery_target_lsn", &lsn.to_string());
475 0 : }
476 : ComputeMode::Replica => {
477 0 : assert!(!self.env.safekeepers.is_empty());
478 :
479 : // TODO: use future host field from safekeeper spec
480 : // Pass the list of safekeepers to the replica so that it can connect to any of them,
481 : // whichever is available.
482 0 : let sk_ports = self
483 0 : .env
484 0 : .safekeepers
485 0 : .iter()
486 0 : .map(|x| x.get_compute_port().to_string())
487 0 : .collect::<Vec<_>>()
488 0 : .join(",");
489 0 : let sk_hosts = vec!["localhost"; self.env.safekeepers.len()].join(",");
490 0 :
491 0 : let connstr = format!(
492 0 : "host={} port={} options='-c timeline_id={} tenant_id={}' application_name=replica replication=true",
493 0 : sk_hosts,
494 0 : sk_ports,
495 0 : &self.timeline_id.to_string(),
496 0 : &self.tenant_id.to_string(),
497 0 : );
498 0 :
499 0 : let slot_name = format!("repl_{}_", self.timeline_id);
500 0 : conf.append("primary_conninfo", connstr.as_str());
501 0 : conf.append("primary_slot_name", slot_name.as_str());
502 0 : conf.append("hot_standby", "on");
503 0 : // prefetching of blocks referenced in WAL doesn't make sense for us
504 0 : // Neon hot standby ignores pages that are not in the shared_buffers
505 0 : if self.pg_version >= 15 {
506 0 : conf.append("recovery_prefetch", "off");
507 0 : }
508 : }
509 : }
510 :
511 0 : Ok(conf)
512 0 : }
513 :
514 0 : pub fn endpoint_path(&self) -> PathBuf {
515 0 : self.env.endpoints_path().join(&self.endpoint_id)
516 0 : }
517 :
518 0 : pub fn pgdata(&self) -> PathBuf {
519 0 : self.endpoint_path().join("pgdata")
520 0 : }
521 :
522 0 : pub fn status(&self) -> EndpointStatus {
523 0 : let timeout = Duration::from_millis(300);
524 0 : let has_pidfile = self.pgdata().join("postmaster.pid").exists();
525 0 : let can_connect = TcpStream::connect_timeout(&self.pg_address, timeout).is_ok();
526 0 :
527 0 : match (has_pidfile, can_connect) {
528 0 : (true, true) => EndpointStatus::Running,
529 0 : (false, false) => EndpointStatus::Stopped,
530 0 : (true, false) => EndpointStatus::Crashed,
531 0 : (false, true) => EndpointStatus::RunningNoPidfile,
532 : }
533 0 : }
534 :
535 0 : fn pg_ctl(&self, args: &[&str], auth_token: &Option<String>) -> Result<()> {
536 0 : let pg_ctl_path = self.env.pg_bin_dir(self.pg_version)?.join("pg_ctl");
537 0 : let mut cmd = Command::new(&pg_ctl_path);
538 0 : cmd.args(
539 0 : [
540 0 : &[
541 0 : "-D",
542 0 : self.pgdata().to_str().unwrap(),
543 0 : "-w", //wait till pg_ctl actually does what was asked
544 0 : ],
545 0 : args,
546 0 : ]
547 0 : .concat(),
548 0 : )
549 0 : .env_clear()
550 0 : .env(
551 0 : "LD_LIBRARY_PATH",
552 0 : self.env.pg_lib_dir(self.pg_version)?.to_str().unwrap(),
553 0 : )
554 0 : .env(
555 0 : "DYLD_LIBRARY_PATH",
556 0 : self.env.pg_lib_dir(self.pg_version)?.to_str().unwrap(),
557 : );
558 :
559 : // Pass authentication token used for the connections to pageserver and safekeepers
560 0 : if let Some(token) = auth_token {
561 0 : cmd.env("NEON_AUTH_TOKEN", token);
562 0 : }
563 :
564 0 : let pg_ctl = cmd
565 0 : .output()
566 0 : .context(format!("{} failed", pg_ctl_path.display()))?;
567 0 : if !pg_ctl.status.success() {
568 0 : anyhow::bail!(
569 0 : "pg_ctl failed, exit code: {}, stdout: {}, stderr: {}",
570 0 : pg_ctl.status,
571 0 : String::from_utf8_lossy(&pg_ctl.stdout),
572 0 : String::from_utf8_lossy(&pg_ctl.stderr),
573 0 : );
574 0 : }
575 0 :
576 0 : Ok(())
577 0 : }
578 :
579 0 : fn wait_for_compute_ctl_to_exit(&self, send_sigterm: bool) -> Result<()> {
580 0 : // TODO use background_process::stop_process instead: https://github.com/neondatabase/neon/pull/6482
581 0 : let pidfile_path = self.endpoint_path().join("compute_ctl.pid");
582 0 : let pid: u32 = std::fs::read_to_string(pidfile_path)?.parse()?;
583 0 : let pid = nix::unistd::Pid::from_raw(pid as i32);
584 0 : if send_sigterm {
585 0 : kill(pid, Signal::SIGTERM).ok();
586 0 : }
587 0 : crate::background_process::wait_until_stopped("compute_ctl", pid)?;
588 0 : Ok(())
589 0 : }
590 :
591 0 : fn read_postgresql_conf(&self) -> Result<String> {
592 0 : // Slurp the endpoints/<endpoint id>/postgresql.conf file into
593 0 : // memory. We will include it in the spec file that we pass to
594 0 : // `compute_ctl`, and `compute_ctl` will write it to the postgresql.conf
595 0 : // in the data directory.
596 0 : let postgresql_conf_path = self.endpoint_path().join("postgresql.conf");
597 0 : match std::fs::read(&postgresql_conf_path) {
598 0 : Ok(content) => Ok(String::from_utf8(content)?),
599 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok("".to_string()),
600 0 : Err(e) => Err(anyhow::Error::new(e).context(format!(
601 0 : "failed to read config file in {}",
602 0 : postgresql_conf_path.to_str().unwrap()
603 0 : ))),
604 : }
605 0 : }
606 :
607 0 : fn build_pageserver_connstr(pageservers: &[(Host, u16)]) -> String {
608 0 : pageservers
609 0 : .iter()
610 0 : .map(|(host, port)| format!("postgresql://no_user@{host}:{port}"))
611 0 : .collect::<Vec<_>>()
612 0 : .join(",")
613 0 : }
614 :
615 : /// Map safekeepers ids to the actual connection strings.
616 0 : fn build_safekeepers_connstrs(&self, sk_ids: Vec<NodeId>) -> Result<Vec<String>> {
617 0 : let mut safekeeper_connstrings = Vec::new();
618 0 : if self.mode == ComputeMode::Primary {
619 0 : for sk_id in sk_ids {
620 0 : let sk = self
621 0 : .env
622 0 : .safekeepers
623 0 : .iter()
624 0 : .find(|node| node.id == sk_id)
625 0 : .ok_or_else(|| anyhow!("safekeeper {sk_id} does not exist"))?;
626 0 : safekeeper_connstrings.push(format!("127.0.0.1:{}", sk.get_compute_port()));
627 : }
628 0 : }
629 0 : Ok(safekeeper_connstrings)
630 0 : }
631 :
632 : /// Generate a JWT with the correct claims.
633 0 : pub fn generate_jwt(&self) -> Result<String> {
634 0 : self.env.generate_auth_token(&ComputeClaims {
635 0 : compute_id: self.endpoint_id.clone(),
636 0 : })
637 0 : }
638 :
639 : #[allow(clippy::too_many_arguments)]
640 0 : pub async fn start(
641 0 : &self,
642 0 : auth_token: &Option<String>,
643 0 : safekeepers_generation: Option<SafekeeperGeneration>,
644 0 : safekeepers: Vec<NodeId>,
645 0 : pageservers: Vec<(Host, u16)>,
646 0 : remote_ext_config: Option<&String>,
647 0 : shard_stripe_size: usize,
648 0 : create_test_user: bool,
649 0 : start_timeout: Duration,
650 0 : ) -> Result<()> {
651 0 : if self.status() == EndpointStatus::Running {
652 0 : anyhow::bail!("The endpoint is already running");
653 0 : }
654 :
655 0 : let postgresql_conf = self.read_postgresql_conf()?;
656 :
657 : // We always start the compute node from scratch, so if the Postgres
658 : // data dir exists from a previous launch, remove it first.
659 0 : if self.pgdata().exists() {
660 0 : std::fs::remove_dir_all(self.pgdata())?;
661 0 : }
662 :
663 0 : let pageserver_connstring = Self::build_pageserver_connstr(&pageservers);
664 0 : assert!(!pageserver_connstring.is_empty());
665 :
666 0 : let safekeeper_connstrings = self.build_safekeepers_connstrs(safekeepers)?;
667 :
668 : // check for file remote_extensions_spec.json
669 : // if it is present, read it and pass to compute_ctl
670 0 : let remote_extensions_spec_path = self.endpoint_path().join("remote_extensions_spec.json");
671 0 : let remote_extensions_spec = std::fs::File::open(remote_extensions_spec_path);
672 : let remote_extensions: Option<RemoteExtSpec>;
673 :
674 0 : if let Ok(spec_file) = remote_extensions_spec {
675 0 : remote_extensions = serde_json::from_reader(spec_file).ok();
676 0 : } else {
677 0 : remote_extensions = None;
678 0 : };
679 :
680 : // Create config file
681 0 : let config = {
682 0 : let mut spec = ComputeSpec {
683 0 : skip_pg_catalog_updates: self.skip_pg_catalog_updates,
684 0 : format_version: 1.0,
685 0 : operation_uuid: None,
686 0 : features: self.features.clone(),
687 0 : swap_size_bytes: None,
688 0 : disk_quota_bytes: None,
689 0 : disable_lfc_resizing: None,
690 0 : cluster: Cluster {
691 0 : cluster_id: None, // project ID: not used
692 0 : name: None, // project name: not used
693 0 : state: None,
694 0 : roles: if create_test_user {
695 0 : vec![Role {
696 0 : name: PgIdent::from_str("test").unwrap(),
697 0 : encrypted_password: None,
698 0 : options: None,
699 0 : }]
700 : } else {
701 0 : Vec::new()
702 : },
703 0 : databases: if create_test_user {
704 0 : vec![Database {
705 0 : name: PgIdent::from_str("neondb").unwrap(),
706 0 : owner: PgIdent::from_str("test").unwrap(),
707 0 : options: None,
708 0 : restrict_conn: false,
709 0 : invalid: false,
710 0 : }]
711 : } else {
712 0 : Vec::new()
713 : },
714 0 : settings: None,
715 0 : postgresql_conf: Some(postgresql_conf.clone()),
716 0 : },
717 0 : delta_operations: None,
718 0 : tenant_id: Some(self.tenant_id),
719 0 : timeline_id: Some(self.timeline_id),
720 0 : project_id: None,
721 0 : branch_id: None,
722 0 : endpoint_id: Some(self.endpoint_id.clone()),
723 0 : mode: self.mode,
724 0 : pageserver_connstring: Some(pageserver_connstring),
725 0 : safekeepers_generation: safekeepers_generation.map(|g| g.into_inner()),
726 0 : safekeeper_connstrings,
727 0 : storage_auth_token: auth_token.clone(),
728 0 : remote_extensions,
729 0 : pgbouncer_settings: None,
730 0 : shard_stripe_size: Some(shard_stripe_size),
731 0 : local_proxy_config: None,
732 0 : reconfigure_concurrency: self.reconfigure_concurrency,
733 0 : drop_subscriptions_before_start: self.drop_subscriptions_before_start,
734 0 : audit_log_level: ComputeAudit::Disabled,
735 0 : logs_export_host: None::<String>,
736 0 : };
737 0 :
738 0 : // this strange code is needed to support respec() in tests
739 0 : if self.cluster.is_some() {
740 0 : debug!("Cluster is already set in the endpoint spec, using it");
741 0 : spec.cluster = self.cluster.clone().unwrap();
742 0 :
743 0 : debug!("spec.cluster {:?}", spec.cluster);
744 :
745 : // fill missing fields again
746 0 : if create_test_user {
747 0 : spec.cluster.roles.push(Role {
748 0 : name: PgIdent::from_str("test").unwrap(),
749 0 : encrypted_password: None,
750 0 : options: None,
751 0 : });
752 0 : spec.cluster.databases.push(Database {
753 0 : name: PgIdent::from_str("neondb").unwrap(),
754 0 : owner: PgIdent::from_str("test").unwrap(),
755 0 : options: None,
756 0 : restrict_conn: false,
757 0 : invalid: false,
758 0 : });
759 0 : }
760 0 : spec.cluster.postgresql_conf = Some(postgresql_conf);
761 0 : }
762 :
763 0 : ComputeConfig {
764 0 : spec: Some(spec),
765 0 : compute_ctl_config: self.compute_ctl_config.clone(),
766 0 : }
767 0 : };
768 0 :
769 0 : let config_path = self.endpoint_path().join("config.json");
770 0 : std::fs::write(config_path, serde_json::to_string_pretty(&config)?)?;
771 :
772 : // Open log file. We'll redirect the stdout and stderr of `compute_ctl` to it.
773 0 : let logfile = std::fs::OpenOptions::new()
774 0 : .create(true)
775 0 : .append(true)
776 0 : .open(self.endpoint_path().join("compute.log"))?;
777 :
778 : // Launch compute_ctl
779 0 : let conn_str = self.connstr("cloud_admin", "postgres");
780 0 : println!("Starting postgres node at '{}'", conn_str);
781 0 : if create_test_user {
782 0 : let conn_str = self.connstr("test", "neondb");
783 0 : println!("Also at '{}'", conn_str);
784 0 : }
785 0 : let mut cmd = Command::new(self.env.neon_distrib_dir.join("compute_ctl"));
786 0 : cmd.args([
787 0 : "--external-http-port",
788 0 : &self.external_http_address.port().to_string(),
789 0 : ])
790 0 : .args([
791 0 : "--internal-http-port",
792 0 : &self.internal_http_address.port().to_string(),
793 0 : ])
794 0 : .args(["--pgdata", self.pgdata().to_str().unwrap()])
795 0 : .args(["--connstr", &conn_str])
796 0 : .arg("--config")
797 0 : .arg(self.endpoint_path().join("config.json").as_os_str())
798 0 : .args([
799 0 : "--pgbin",
800 0 : self.env
801 0 : .pg_bin_dir(self.pg_version)?
802 0 : .join("postgres")
803 0 : .to_str()
804 0 : .unwrap(),
805 0 : ])
806 0 : // TODO: It would be nice if we generated compute IDs with the same
807 0 : // algorithm as the real control plane.
808 0 : .args(["--compute-id", &self.endpoint_id])
809 0 : .stdin(std::process::Stdio::null())
810 0 : .stderr(logfile.try_clone()?)
811 0 : .stdout(logfile);
812 :
813 0 : if let Some(remote_ext_config) = remote_ext_config {
814 0 : cmd.args(["--remote-ext-config", remote_ext_config]);
815 0 : }
816 :
817 0 : let child = cmd.spawn()?;
818 : // set up a scopeguard to kill & wait for the child in case we panic or bail below
819 0 : let child = scopeguard::guard(child, |mut child| {
820 0 : println!("SIGKILL & wait the started process");
821 0 : (|| {
822 0 : // TODO: use another signal that can be caught by the child so it can clean up any children it spawned
823 0 : child.kill().context("SIGKILL child")?;
824 0 : child.wait().context("wait() for child process")?;
825 0 : anyhow::Ok(())
826 0 : })()
827 0 : .with_context(|| format!("scopeguard kill&wait child {child:?}"))
828 0 : .unwrap();
829 0 : });
830 0 :
831 0 : // Write down the pid so we can wait for it when we want to stop
832 0 : // TODO use background_process::start_process instead: https://github.com/neondatabase/neon/pull/6482
833 0 : let pid = child.id();
834 0 : let pidfile_path = self.endpoint_path().join("compute_ctl.pid");
835 0 : std::fs::write(pidfile_path, pid.to_string())?;
836 :
837 : // Wait for it to start
838 : const ATTEMPT_INTERVAL: Duration = Duration::from_millis(100);
839 0 : let start_at = Instant::now();
840 : loop {
841 0 : match self.get_status().await {
842 0 : Ok(state) => {
843 0 : match state.status {
844 : ComputeStatus::Init => {
845 0 : if Instant::now().duration_since(start_at) > start_timeout {
846 0 : bail!(
847 0 : "compute startup timed out {:?}; still in Init state",
848 0 : start_timeout
849 0 : );
850 0 : }
851 : // keep retrying
852 : }
853 : ComputeStatus::Running => {
854 : // All good!
855 0 : break;
856 : }
857 : ComputeStatus::Failed => {
858 0 : bail!(
859 0 : "compute startup failed: {}",
860 0 : state
861 0 : .error
862 0 : .as_deref()
863 0 : .unwrap_or("<no error from compute_ctl>")
864 0 : );
865 : }
866 : ComputeStatus::Empty
867 : | ComputeStatus::ConfigurationPending
868 : | ComputeStatus::Configuration
869 : | ComputeStatus::TerminationPending
870 : | ComputeStatus::Terminated => {
871 0 : bail!("unexpected compute status: {:?}", state.status)
872 : }
873 : }
874 : }
875 0 : Err(e) => {
876 0 : if Instant::now().duration_since(start_at) > start_timeout {
877 0 : return Err(e).context(format!(
878 0 : "timed out {:?} waiting to connect to compute_ctl HTTP",
879 0 : start_timeout,
880 0 : ));
881 0 : }
882 : }
883 : }
884 0 : tokio::time::sleep(ATTEMPT_INTERVAL).await;
885 : }
886 :
887 : // disarm the scopeguard, let the child outlive this function (and neon_local invoction)
888 0 : drop(scopeguard::ScopeGuard::into_inner(child));
889 0 :
890 0 : Ok(())
891 0 : }
892 :
893 : // Call the /status HTTP API
894 0 : pub async fn get_status(&self) -> Result<ComputeStatusResponse> {
895 0 : let client = reqwest::Client::new();
896 :
897 0 : let response = client
898 0 : .request(
899 0 : reqwest::Method::GET,
900 0 : format!(
901 0 : "http://{}:{}/status",
902 0 : self.external_http_address.ip(),
903 0 : self.external_http_address.port()
904 0 : ),
905 0 : )
906 0 : .bearer_auth(self.generate_jwt()?)
907 0 : .send()
908 0 : .await?;
909 :
910 : // Interpret the response
911 0 : let status = response.status();
912 0 : if !(status.is_client_error() || status.is_server_error()) {
913 0 : Ok(response.json().await?)
914 : } else {
915 : // reqwest does not export its error construction utility functions, so let's craft the message ourselves
916 0 : let url = response.url().to_owned();
917 0 : let msg = match response.text().await {
918 0 : Ok(err_body) => format!("Error: {}", err_body),
919 0 : Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
920 : };
921 0 : Err(anyhow::anyhow!(msg))
922 : }
923 0 : }
924 :
925 0 : pub async fn reconfigure(
926 0 : &self,
927 0 : mut pageservers: Vec<(Host, u16)>,
928 0 : stripe_size: Option<ShardStripeSize>,
929 0 : safekeepers: Option<Vec<NodeId>>,
930 0 : ) -> Result<()> {
931 0 : let (mut spec, compute_ctl_config) = {
932 0 : let config_path = self.endpoint_path().join("config.json");
933 0 : let file = std::fs::File::open(config_path)?;
934 0 : let config: ComputeConfig = serde_json::from_reader(file)?;
935 :
936 0 : (config.spec.unwrap(), config.compute_ctl_config)
937 : };
938 :
939 0 : let postgresql_conf = self.read_postgresql_conf()?;
940 0 : spec.cluster.postgresql_conf = Some(postgresql_conf);
941 0 :
942 0 : // If we weren't given explicit pageservers, query the storage controller
943 0 : if pageservers.is_empty() {
944 0 : let storage_controller = StorageController::from_env(&self.env);
945 0 : let locate_result = storage_controller.tenant_locate(self.tenant_id).await?;
946 0 : pageservers = locate_result
947 0 : .shards
948 0 : .into_iter()
949 0 : .map(|shard| {
950 0 : (
951 0 : Host::parse(&shard.listen_pg_addr)
952 0 : .expect("Storage controller reported bad hostname"),
953 0 : shard.listen_pg_port,
954 0 : )
955 0 : })
956 0 : .collect::<Vec<_>>();
957 0 : }
958 :
959 0 : let pageserver_connstr = Self::build_pageserver_connstr(&pageservers);
960 0 : assert!(!pageserver_connstr.is_empty());
961 0 : spec.pageserver_connstring = Some(pageserver_connstr);
962 0 : if stripe_size.is_some() {
963 0 : spec.shard_stripe_size = stripe_size.map(|s| s.0 as usize);
964 0 : }
965 :
966 : // If safekeepers are not specified, don't change them.
967 0 : if let Some(safekeepers) = safekeepers {
968 0 : let safekeeper_connstrings = self.build_safekeepers_connstrs(safekeepers)?;
969 0 : spec.safekeeper_connstrings = safekeeper_connstrings;
970 0 : }
971 :
972 0 : let client = reqwest::Client::builder()
973 0 : .timeout(Duration::from_secs(120))
974 0 : .build()
975 0 : .unwrap();
976 0 : let response = client
977 0 : .post(format!(
978 0 : "http://{}:{}/configure",
979 0 : self.external_http_address.ip(),
980 0 : self.external_http_address.port()
981 0 : ))
982 0 : .header(CONTENT_TYPE.as_str(), "application/json")
983 0 : .bearer_auth(self.generate_jwt()?)
984 0 : .body(
985 0 : serde_json::to_string(&ConfigurationRequest {
986 0 : spec,
987 0 : compute_ctl_config,
988 0 : })
989 0 : .unwrap(),
990 0 : )
991 0 : .send()
992 0 : .await?;
993 :
994 0 : let status = response.status();
995 0 : if !(status.is_client_error() || status.is_server_error()) {
996 0 : Ok(())
997 : } else {
998 0 : let url = response.url().to_owned();
999 0 : let msg = match response.text().await {
1000 0 : Ok(err_body) => format!("Error: {}", err_body),
1001 0 : Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
1002 : };
1003 0 : Err(anyhow::anyhow!(msg))
1004 : }
1005 0 : }
1006 :
1007 0 : pub fn stop(&self, mode: &str, destroy: bool) -> Result<()> {
1008 0 : self.pg_ctl(&["-m", mode, "stop"], &None)?;
1009 :
1010 : // Also wait for the compute_ctl process to die. It might have some
1011 : // cleanup work to do after postgres stops, like syncing safekeepers,
1012 : // etc.
1013 : //
1014 : // If destroying or stop mode is immediate, send it SIGTERM before
1015 : // waiting. Sometimes we do *not* want this cleanup: tests intentionally
1016 : // do stop when majority of safekeepers is down, so sync-safekeepers
1017 : // would hang otherwise. This could be a separate flag though.
1018 0 : let send_sigterm = destroy || mode == "immediate";
1019 0 : self.wait_for_compute_ctl_to_exit(send_sigterm)?;
1020 0 : if destroy {
1021 0 : println!(
1022 0 : "Destroying postgres data directory '{}'",
1023 0 : self.pgdata().to_str().unwrap()
1024 0 : );
1025 0 : std::fs::remove_dir_all(self.endpoint_path())?;
1026 0 : }
1027 0 : Ok(())
1028 0 : }
1029 :
1030 0 : pub fn connstr(&self, user: &str, db_name: &str) -> String {
1031 0 : format!(
1032 0 : "postgresql://{}@{}:{}/{}",
1033 0 : user,
1034 0 : self.pg_address.ip(),
1035 0 : self.pg_address.port(),
1036 0 : db_name
1037 0 : )
1038 0 : }
1039 : }
|