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