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