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