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