Line data Source code
1 : use anyhow::{Context, Result};
2 : use chrono::{DateTime, Utc};
3 : use compute_api::privilege::Privilege;
4 : use compute_api::responses::{
5 : ComputeConfig, ComputeCtlConfig, ComputeMetrics, ComputeStatus, LfcOffloadState,
6 : LfcPrewarmState, PromoteState, TlsConfig,
7 : };
8 : use compute_api::spec::{
9 : ComputeAudit, ComputeFeature, ComputeMode, ComputeSpec, ExtVersion, PageserverProtocol, PgIdent,
10 : };
11 : use futures::StreamExt;
12 : use futures::future::join_all;
13 : use futures::stream::FuturesUnordered;
14 : use itertools::Itertools;
15 : use nix::sys::signal::{Signal, kill};
16 : use nix::unistd::Pid;
17 : use once_cell::sync::Lazy;
18 : use pageserver_page_api::{self as page_api, BaseBackupCompression};
19 : use postgres;
20 : use postgres::NoTls;
21 : use postgres::error::SqlState;
22 : use remote_storage::{DownloadError, RemotePath};
23 : use std::collections::{HashMap, HashSet};
24 : use std::os::unix::fs::{PermissionsExt, symlink};
25 : use std::path::Path;
26 : use std::process::{Command, Stdio};
27 : use std::str::FromStr;
28 : use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
29 : use std::sync::{Arc, Condvar, Mutex, RwLock};
30 : use std::time::{Duration, Instant};
31 : use std::{env, fs};
32 : use tokio::{spawn, sync::watch, task::JoinHandle, time};
33 : use tracing::{Instrument, debug, error, info, instrument, warn};
34 : use url::Url;
35 : use utils::id::{TenantId, TimelineId};
36 : use utils::lsn::Lsn;
37 : use utils::measured_stream::MeasuredReader;
38 : use utils::pid_file;
39 : use utils::shard::{ShardCount, ShardIndex, ShardNumber};
40 :
41 : use crate::configurator::launch_configurator;
42 : use crate::disk_quota::set_disk_quota;
43 : use crate::installed_extensions::get_installed_extensions;
44 : use crate::logger::startup_context_from_env;
45 : use crate::lsn_lease::launch_lsn_lease_bg_task_for_static;
46 : use crate::metrics::COMPUTE_CTL_UP;
47 : use crate::monitor::launch_monitor;
48 : use crate::pg_helpers::*;
49 : use crate::pgbouncer::*;
50 : use crate::rsyslog::{
51 : PostgresLogsRsyslogConfig, configure_audit_rsyslog, configure_postgres_logs_export,
52 : launch_pgaudit_gc,
53 : };
54 : use crate::spec::*;
55 : use crate::swap::resize_swap;
56 : use crate::sync_sk::{check_if_synced, ping_safekeeper};
57 : use crate::tls::watch_cert_for_changes;
58 : use crate::{config, extension_server, local_proxy};
59 :
60 : pub static SYNC_SAFEKEEPERS_PID: AtomicU32 = AtomicU32::new(0);
61 : pub static PG_PID: AtomicU32 = AtomicU32::new(0);
62 : // This is an arbitrary build tag. Fine as a default / for testing purposes
63 : // in-case of not-set environment var
64 : const BUILD_TAG_DEFAULT: &str = "latest";
65 : /// Build tag/version of the compute node binaries/image. It's tricky and ugly
66 : /// to pass it everywhere as a part of `ComputeNodeParams`, so we use a
67 : /// global static variable.
68 0 : pub static BUILD_TAG: Lazy<String> = Lazy::new(|| {
69 0 : option_env!("BUILD_TAG")
70 0 : .unwrap_or(BUILD_TAG_DEFAULT)
71 0 : .to_string()
72 0 : });
73 : const DEFAULT_INSTALLED_EXTENSIONS_COLLECTION_INTERVAL: u64 = 3600;
74 :
75 : /// Static configuration params that don't change after startup. These mostly
76 : /// come from the CLI args, or are derived from them.
77 : #[derive(Clone, Debug)]
78 : pub struct ComputeNodeParams {
79 : /// The ID of the compute
80 : pub compute_id: String,
81 :
82 : /// Url type maintains proper escaping
83 : pub connstr: url::Url,
84 :
85 : /// The name of the 'weak' superuser role, which we give to the users.
86 : /// It follows the allow list approach, i.e., we take a standard role
87 : /// and grant it extra permissions with explicit GRANTs here and there,
88 : /// and core patches.
89 : pub privileged_role_name: String,
90 :
91 : pub resize_swap_on_bind: bool,
92 : pub set_disk_quota_for_fs: Option<String>,
93 :
94 : // VM monitor parameters
95 : #[cfg(target_os = "linux")]
96 : pub filecache_connstr: String,
97 : #[cfg(target_os = "linux")]
98 : pub cgroup: String,
99 : #[cfg(target_os = "linux")]
100 : pub vm_monitor_addr: String,
101 :
102 : pub pgdata: String,
103 : pub pgbin: String,
104 : pub pgversion: String,
105 :
106 : /// The port that the compute's external HTTP server listens on
107 : pub external_http_port: u16,
108 : /// The port that the compute's internal HTTP server listens on
109 : pub internal_http_port: u16,
110 :
111 : /// the address of extension storage proxy gateway
112 : pub remote_ext_base_url: Option<Url>,
113 :
114 : /// Interval for installed extensions collection
115 : pub installed_extensions_collection_interval: Arc<AtomicU64>,
116 :
117 : /// Timeout of PG compute startup in the Init state.
118 : pub pg_init_timeout: Option<Duration>,
119 :
120 : pub lakebase_mode: bool,
121 : }
122 :
123 : type TaskHandle = Mutex<Option<JoinHandle<()>>>;
124 :
125 : /// Compute node info shared across several `compute_ctl` threads.
126 : pub struct ComputeNode {
127 : pub params: ComputeNodeParams,
128 :
129 : // We connect to Postgres from many different places, so build configs once
130 : // and reuse them where needed. These are derived from 'params.connstr'
131 : pub conn_conf: postgres::config::Config,
132 : pub tokio_conn_conf: tokio_postgres::config::Config,
133 :
134 : /// Volatile part of the `ComputeNode`, which should be used under `Mutex`.
135 : /// To allow HTTP API server to serving status requests, while configuration
136 : /// is in progress, lock should be held only for short periods of time to do
137 : /// read/write, not the whole configuration process.
138 : pub state: Mutex<ComputeState>,
139 : /// `Condvar` to allow notifying waiters about state changes.
140 : pub state_changed: Condvar,
141 :
142 : // key: ext_archive_name, value: started download time, download_completed?
143 : pub ext_download_progress: RwLock<HashMap<String, (DateTime<Utc>, bool)>>,
144 : pub compute_ctl_config: ComputeCtlConfig,
145 :
146 : /// Handle to the extension stats collection task
147 : extension_stats_task: TaskHandle,
148 : lfc_offload_task: TaskHandle,
149 : }
150 :
151 : // store some metrics about download size that might impact startup time
152 : #[derive(Clone, Debug)]
153 : pub struct RemoteExtensionMetrics {
154 : num_ext_downloaded: u64,
155 : largest_ext_size: u64,
156 : total_ext_download_size: u64,
157 : }
158 :
159 : #[derive(Clone, Debug)]
160 : pub struct ComputeState {
161 : pub start_time: DateTime<Utc>,
162 : pub pg_start_time: Option<DateTime<Utc>>,
163 : pub status: ComputeStatus,
164 : /// Timestamp of the last Postgres activity. It could be `None` if
165 : /// compute wasn't used since start.
166 : pub last_active: Option<DateTime<Utc>>,
167 : pub error: Option<String>,
168 :
169 : /// Compute spec. This can be received from the CLI or - more likely -
170 : /// passed by the control plane with a /configure HTTP request.
171 : pub pspec: Option<ParsedSpec>,
172 :
173 : /// If the spec is passed by a /configure request, 'startup_span' is the
174 : /// /configure request's tracing span. The main thread enters it when it
175 : /// processes the compute startup, so that the compute startup is considered
176 : /// to be part of the /configure request for tracing purposes.
177 : ///
178 : /// If the request handling thread/task called startup_compute() directly,
179 : /// it would automatically be a child of the request handling span, and we
180 : /// wouldn't need this. But because we use the main thread to perform the
181 : /// startup, and the /configure task just waits for it to finish, we need to
182 : /// set up the span relationship ourselves.
183 : pub startup_span: Option<tracing::span::Span>,
184 :
185 : pub lfc_prewarm_state: LfcPrewarmState,
186 : pub lfc_offload_state: LfcOffloadState,
187 :
188 : /// WAL flush LSN that is set after terminating Postgres and syncing safekeepers if
189 : /// mode == ComputeMode::Primary. None otherwise
190 : pub terminate_flush_lsn: Option<Lsn>,
191 : pub promote_state: Option<watch::Receiver<PromoteState>>,
192 :
193 : pub metrics: ComputeMetrics,
194 : }
195 :
196 : impl ComputeState {
197 0 : pub fn new() -> Self {
198 0 : Self {
199 0 : start_time: Utc::now(),
200 0 : pg_start_time: None,
201 0 : status: ComputeStatus::Empty,
202 0 : last_active: None,
203 0 : error: None,
204 0 : pspec: None,
205 0 : startup_span: None,
206 0 : metrics: ComputeMetrics::default(),
207 0 : lfc_prewarm_state: LfcPrewarmState::default(),
208 0 : lfc_offload_state: LfcOffloadState::default(),
209 0 : terminate_flush_lsn: None,
210 0 : promote_state: None,
211 0 : }
212 0 : }
213 :
214 0 : pub fn set_status(&mut self, status: ComputeStatus, state_changed: &Condvar) {
215 0 : let prev = self.status;
216 0 : info!("Changing compute status from {} to {}", prev, status);
217 0 : self.status = status;
218 0 : state_changed.notify_all();
219 :
220 0 : COMPUTE_CTL_UP.reset();
221 0 : COMPUTE_CTL_UP
222 0 : .with_label_values(&[&BUILD_TAG, status.to_string().as_str()])
223 0 : .set(1);
224 0 : }
225 :
226 0 : pub fn set_failed_status(&mut self, err: anyhow::Error, state_changed: &Condvar) {
227 0 : self.error = Some(format!("{err:?}"));
228 0 : self.set_status(ComputeStatus::Failed, state_changed);
229 0 : }
230 : }
231 :
232 : impl Default for ComputeState {
233 0 : fn default() -> Self {
234 0 : Self::new()
235 0 : }
236 : }
237 :
238 : #[derive(Clone, Debug)]
239 : pub struct ParsedSpec {
240 : pub spec: ComputeSpec,
241 : pub tenant_id: TenantId,
242 : pub timeline_id: TimelineId,
243 : pub pageserver_connstr: String,
244 : pub safekeeper_connstrings: Vec<String>,
245 : pub storage_auth_token: Option<String>,
246 : /// k8s dns name and port
247 : pub endpoint_storage_addr: Option<String>,
248 : pub endpoint_storage_token: Option<String>,
249 : }
250 :
251 : impl ParsedSpec {
252 1 : pub fn validate(&self) -> Result<(), String> {
253 : // Only Primary nodes are using safekeeper_connstrings, and at the moment
254 : // this method only validates that part of the specs.
255 1 : if self.spec.mode != ComputeMode::Primary {
256 0 : return Ok(());
257 1 : }
258 :
259 : // While it seems like a good idea to check for an odd number of entries in
260 : // the safekeepers connection string, changes to the list of safekeepers might
261 : // incur appending a new server to a list of 3, in which case a list of 4
262 : // entries is okay in production.
263 : //
264 : // Still we want unique entries, and at least one entry in the vector
265 1 : if self.safekeeper_connstrings.is_empty() {
266 0 : return Err(String::from("safekeeper_connstrings is empty"));
267 1 : }
268 :
269 : // check for uniqueness of the connection strings in the set
270 1 : let mut connstrings = self.safekeeper_connstrings.clone();
271 :
272 1 : connstrings.sort();
273 1 : let mut previous = &connstrings[0];
274 :
275 2 : for current in connstrings.iter().skip(1) {
276 : // duplicate entry?
277 2 : if current == previous {
278 1 : return Err(format!(
279 1 : "duplicate entry in safekeeper_connstrings: {current}!",
280 1 : ));
281 1 : }
282 :
283 1 : previous = current;
284 : }
285 :
286 0 : Ok(())
287 1 : }
288 : }
289 :
290 : impl TryFrom<ComputeSpec> for ParsedSpec {
291 : type Error = String;
292 1 : fn try_from(spec: ComputeSpec) -> Result<Self, String> {
293 : // Extract the options from the spec file that are needed to connect to
294 : // the storage system.
295 : //
296 : // For backwards-compatibility, the top-level fields in the spec file
297 : // may be empty. In that case, we need to dig them from the GUCs in the
298 : // cluster.settings field.
299 1 : let pageserver_connstr = spec
300 1 : .pageserver_connstring
301 1 : .clone()
302 1 : .or_else(|| spec.cluster.settings.find("neon.pageserver_connstring"))
303 1 : .ok_or("pageserver connstr should be provided")?;
304 1 : let safekeeper_connstrings = if spec.safekeeper_connstrings.is_empty() {
305 1 : if matches!(spec.mode, ComputeMode::Primary) {
306 1 : spec.cluster
307 1 : .settings
308 1 : .find("neon.safekeepers")
309 1 : .ok_or("safekeeper connstrings should be provided")?
310 1 : .split(',')
311 4 : .map(|str| str.to_string())
312 1 : .collect()
313 : } else {
314 0 : vec![]
315 : }
316 : } else {
317 0 : spec.safekeeper_connstrings.clone()
318 : };
319 :
320 1 : let storage_auth_token = spec.storage_auth_token.clone();
321 1 : let tenant_id: TenantId = if let Some(tenant_id) = spec.tenant_id {
322 0 : tenant_id
323 : } else {
324 1 : spec.cluster
325 1 : .settings
326 1 : .find("neon.tenant_id")
327 1 : .ok_or("tenant id should be provided")
328 1 : .map(|s| TenantId::from_str(&s))?
329 1 : .or(Err("invalid tenant id"))?
330 : };
331 1 : let timeline_id: TimelineId = if let Some(timeline_id) = spec.timeline_id {
332 0 : timeline_id
333 : } else {
334 1 : spec.cluster
335 1 : .settings
336 1 : .find("neon.timeline_id")
337 1 : .ok_or("timeline id should be provided")
338 1 : .map(|s| TimelineId::from_str(&s))?
339 1 : .or(Err("invalid timeline id"))?
340 : };
341 :
342 1 : let endpoint_storage_addr: Option<String> = spec
343 1 : .endpoint_storage_addr
344 1 : .clone()
345 1 : .or_else(|| spec.cluster.settings.find("neon.endpoint_storage_addr"));
346 1 : let endpoint_storage_token = spec
347 1 : .endpoint_storage_token
348 1 : .clone()
349 1 : .or_else(|| spec.cluster.settings.find("neon.endpoint_storage_token"));
350 :
351 1 : let res = ParsedSpec {
352 1 : spec,
353 1 : pageserver_connstr,
354 1 : safekeeper_connstrings,
355 1 : storage_auth_token,
356 1 : tenant_id,
357 1 : timeline_id,
358 1 : endpoint_storage_addr,
359 1 : endpoint_storage_token,
360 1 : };
361 :
362 : // Now check validity of the parsed specification
363 1 : res.validate()?;
364 0 : Ok(res)
365 1 : }
366 : }
367 :
368 : /// If we are a VM, returns a [`Command`] that will run in the `neon-postgres`
369 : /// cgroup. Otherwise returns the default `Command::new(cmd)`
370 : ///
371 : /// This function should be used to start postgres, as it will start it in the
372 : /// neon-postgres cgroup if we are a VM. This allows autoscaling to control
373 : /// postgres' resource usage. The cgroup will exist in VMs because vm-builder
374 : /// creates it during the sysinit phase of its inittab.
375 0 : fn maybe_cgexec(cmd: &str) -> Command {
376 : // The cplane sets this env var for autoscaling computes.
377 : // use `var_os` so we don't have to worry about the variable being valid
378 : // unicode. Should never be an concern . . . but just in case
379 0 : if env::var_os("AUTOSCALING").is_some() {
380 0 : let mut command = Command::new("cgexec");
381 0 : command.args(["-g", "memory:neon-postgres"]);
382 0 : command.arg(cmd);
383 0 : command
384 : } else {
385 0 : Command::new(cmd)
386 : }
387 0 : }
388 :
389 : struct PostgresHandle {
390 : postgres: std::process::Child,
391 : log_collector: JoinHandle<Result<()>>,
392 : }
393 :
394 : impl PostgresHandle {
395 : /// Return PID of the postgres (postmaster) process
396 0 : fn pid(&self) -> Pid {
397 0 : Pid::from_raw(self.postgres.id() as i32)
398 0 : }
399 : }
400 :
401 : struct StartVmMonitorResult {
402 : #[cfg(target_os = "linux")]
403 : token: tokio_util::sync::CancellationToken,
404 : #[cfg(target_os = "linux")]
405 : vm_monitor: Option<JoinHandle<Result<()>>>,
406 : }
407 :
408 : impl ComputeNode {
409 0 : pub fn new(params: ComputeNodeParams, config: ComputeConfig) -> Result<Self> {
410 0 : let connstr = params.connstr.as_str();
411 0 : let mut conn_conf = postgres::config::Config::from_str(connstr)
412 0 : .context("cannot build postgres config from connstr")?;
413 0 : let mut tokio_conn_conf = tokio_postgres::config::Config::from_str(connstr)
414 0 : .context("cannot build tokio postgres config from connstr")?;
415 :
416 : // Users can set some configuration parameters per database with
417 : // ALTER DATABASE ... SET ...
418 : //
419 : // There are at least these parameters:
420 : //
421 : // - role=some_other_role
422 : // - default_transaction_read_only=on
423 : // - statement_timeout=1, i.e., 1ms, which will cause most of the queries to fail
424 : // - search_path=non_public_schema, this should be actually safe because
425 : // we don't call any functions in user databases, but better to always reset
426 : // it to public.
427 : //
428 : // that can affect `compute_ctl` and prevent it from properly configuring the database schema.
429 : // Unset them via connection string options before connecting to the database.
430 : // N.B. keep it in sync with `ZENITH_OPTIONS` in `get_maintenance_client()`.
431 : const EXTRA_OPTIONS: &str = "-c role=cloud_admin -c default_transaction_read_only=off -c search_path=public -c statement_timeout=0 -c pgaudit.log=none";
432 0 : let options = match conn_conf.get_options() {
433 : // Allow the control plane to override any options set by the
434 : // compute
435 0 : Some(options) => format!("{EXTRA_OPTIONS} {options}"),
436 0 : None => EXTRA_OPTIONS.to_string(),
437 : };
438 0 : conn_conf.options(&options);
439 0 : tokio_conn_conf.options(&options);
440 :
441 0 : let mut new_state = ComputeState::new();
442 0 : if let Some(spec) = config.spec {
443 0 : let pspec = ParsedSpec::try_from(spec).map_err(|msg| anyhow::anyhow!(msg))?;
444 0 : new_state.pspec = Some(pspec);
445 0 : }
446 :
447 0 : Ok(ComputeNode {
448 0 : params,
449 0 : conn_conf,
450 0 : tokio_conn_conf,
451 0 : state: Mutex::new(new_state),
452 0 : state_changed: Condvar::new(),
453 0 : ext_download_progress: RwLock::new(HashMap::new()),
454 0 : compute_ctl_config: config.compute_ctl_config,
455 0 : extension_stats_task: Mutex::new(None),
456 0 : lfc_offload_task: Mutex::new(None),
457 0 : })
458 0 : }
459 :
460 : /// Top-level control flow of compute_ctl. Returns a process exit code we should
461 : /// exit with.
462 0 : pub fn run(self) -> Result<Option<i32>> {
463 0 : let this = Arc::new(self);
464 :
465 0 : let cli_spec = this.state.lock().unwrap().pspec.clone();
466 :
467 : // If this is a pooled VM, prewarm before starting HTTP server and becoming
468 : // available for binding. Prewarming helps Postgres start quicker later,
469 : // because QEMU will already have its memory allocated from the host, and
470 : // the necessary binaries will already be cached.
471 0 : if cli_spec.is_none() {
472 0 : this.prewarm_postgres_vm_memory()?;
473 0 : }
474 :
475 : // Set the up metric with Empty status before starting the HTTP server.
476 : // That way on the first metric scrape, an external observer will see us
477 : // as 'up' and 'empty' (unless the compute was started with a spec or
478 : // already configured by control plane).
479 0 : COMPUTE_CTL_UP
480 0 : .with_label_values(&[&BUILD_TAG, ComputeStatus::Empty.to_string().as_str()])
481 0 : .set(1);
482 :
483 : // Launch the external HTTP server first, so that we can serve control plane
484 : // requests while configuration is still in progress.
485 0 : crate::http::server::Server::External {
486 0 : port: this.params.external_http_port,
487 0 : config: this.compute_ctl_config.clone(),
488 0 : compute_id: this.params.compute_id.clone(),
489 0 : }
490 0 : .launch(&this);
491 :
492 : // The internal HTTP server could be launched later, but there isn't much
493 : // sense in waiting.
494 0 : crate::http::server::Server::Internal {
495 0 : port: this.params.internal_http_port,
496 0 : }
497 0 : .launch(&this);
498 :
499 : // If we got a spec from the CLI already, use that. Otherwise wait for the
500 : // control plane to pass it to us with a /configure HTTP request
501 0 : let pspec = if let Some(cli_spec) = cli_spec {
502 0 : cli_spec
503 : } else {
504 0 : this.wait_spec()?
505 : };
506 :
507 0 : launch_lsn_lease_bg_task_for_static(&this);
508 :
509 : // We have a spec, start the compute
510 0 : let mut delay_exit = false;
511 0 : let mut vm_monitor = None;
512 0 : let mut pg_process: Option<PostgresHandle> = None;
513 :
514 0 : match this.start_compute(&mut pg_process) {
515 0 : Ok(()) => {
516 0 : // Success! Launch remaining services (just vm-monitor currently)
517 0 : vm_monitor =
518 0 : Some(this.start_vm_monitor(pspec.spec.disable_lfc_resizing.unwrap_or(false)));
519 0 : }
520 0 : Err(err) => {
521 : // Something went wrong with the startup. Log it and expose the error to
522 : // HTTP status requests.
523 0 : error!("could not start the compute node: {:#}", err);
524 0 : this.set_failed_status(err);
525 0 : delay_exit = true;
526 :
527 : // If the error happened after starting PostgreSQL, kill it
528 0 : if let Some(ref pg_process) = pg_process {
529 0 : kill(pg_process.pid(), Signal::SIGQUIT).ok();
530 0 : }
531 : }
532 : }
533 :
534 : // If startup was successful, or it failed in the late stages,
535 : // PostgreSQL is now running. Wait until it exits.
536 0 : let exit_code = if let Some(pg_handle) = pg_process {
537 0 : let exit_status = this.wait_postgres(pg_handle);
538 0 : info!("Postgres exited with code {}, shutting down", exit_status);
539 0 : exit_status.code()
540 : } else {
541 0 : None
542 : };
543 :
544 0 : this.terminate_extension_stats_task();
545 0 : this.terminate_lfc_offload_task();
546 :
547 : // Terminate the vm_monitor so it releases the file watcher on
548 : // /sys/fs/cgroup/neon-postgres.
549 : // Note: the vm-monitor only runs on linux because it requires cgroups.
550 0 : if let Some(vm_monitor) = vm_monitor {
551 : cfg_if::cfg_if! {
552 : if #[cfg(target_os = "linux")] {
553 : // Kills all threads spawned by the monitor
554 0 : vm_monitor.token.cancel();
555 0 : if let Some(handle) = vm_monitor.vm_monitor {
556 0 : // Kills the actual task running the monitor
557 0 : handle.abort();
558 0 : }
559 : } else {
560 : _ = vm_monitor; // appease unused lint on macOS
561 : }
562 : }
563 0 : }
564 :
565 : // Reap the postgres process
566 0 : delay_exit |= this.cleanup_after_postgres_exit()?;
567 :
568 : // /terminate returns LSN. If we don't sleep at all, connection will break and we
569 : // won't get result. If we sleep too much, tests will take significantly longer
570 : // and Github Action run will error out
571 0 : let sleep_duration = if delay_exit {
572 0 : Duration::from_secs(30)
573 : } else {
574 0 : Duration::from_millis(300)
575 : };
576 :
577 : // If launch failed, keep serving HTTP requests for a while, so the cloud
578 : // control plane can get the actual error.
579 0 : if delay_exit {
580 0 : info!("giving control plane 30s to collect the error before shutdown");
581 0 : }
582 0 : std::thread::sleep(sleep_duration);
583 0 : Ok(exit_code)
584 0 : }
585 :
586 0 : pub fn wait_spec(&self) -> Result<ParsedSpec> {
587 0 : info!("no compute spec provided, waiting");
588 0 : let mut state = self.state.lock().unwrap();
589 0 : while state.status != ComputeStatus::ConfigurationPending {
590 0 : state = self.state_changed.wait(state).unwrap();
591 0 : }
592 :
593 0 : info!("got spec, continue configuration");
594 0 : let spec = state.pspec.as_ref().unwrap().clone();
595 :
596 : // Record for how long we slept waiting for the spec.
597 0 : let now = Utc::now();
598 0 : state.metrics.wait_for_spec_ms = now
599 0 : .signed_duration_since(state.start_time)
600 0 : .to_std()
601 0 : .unwrap()
602 0 : .as_millis() as u64;
603 :
604 : // Reset start time, so that the total startup time that is calculated later will
605 : // not include the time that we waited for the spec.
606 0 : state.start_time = now;
607 :
608 0 : Ok(spec)
609 0 : }
610 :
611 : /// Start compute.
612 : ///
613 : /// Prerequisites:
614 : /// - the compute spec has been placed in self.state.pspec
615 : ///
616 : /// On success:
617 : /// - status is set to ComputeStatus::Running
618 : /// - self.running_postgres is set
619 : ///
620 : /// On error:
621 : /// - status is left in ComputeStatus::Init. The caller is responsible for setting it to Failed
622 : /// - if Postgres was started before the fatal error happened, self.running_postgres is
623 : /// set. The caller is responsible for killing it.
624 : ///
625 : /// Note that this is in the critical path of a compute cold start. Keep this fast.
626 : /// Try to do things concurrently, to hide the latencies.
627 0 : fn start_compute(self: &Arc<Self>, pg_handle: &mut Option<PostgresHandle>) -> Result<()> {
628 : let compute_state: ComputeState;
629 :
630 : let start_compute_span;
631 : let _this_entered;
632 : {
633 0 : let mut state_guard = self.state.lock().unwrap();
634 :
635 : // Create a tracing span for the startup operation.
636 : //
637 : // We could otherwise just annotate the function with #[instrument], but if
638 : // we're being configured from a /configure HTTP request, we want the
639 : // startup to be considered part of the /configure request.
640 : //
641 : // Similarly, if a trace ID was passed in env variables, attach it to the span.
642 0 : start_compute_span = {
643 : // Temporarily enter the parent span, so that the new span becomes its child.
644 0 : if let Some(p) = state_guard.startup_span.take() {
645 0 : let _parent_entered = p.entered();
646 0 : tracing::info_span!("start_compute")
647 0 : } else if let Some(otel_context) = startup_context_from_env() {
648 : use tracing_opentelemetry::OpenTelemetrySpanExt;
649 0 : let span = tracing::info_span!("start_compute");
650 0 : span.set_parent(otel_context);
651 0 : span
652 : } else {
653 0 : tracing::info_span!("start_compute")
654 : }
655 : };
656 0 : _this_entered = start_compute_span.enter();
657 :
658 : // Hadron: Record postgres start time (used to enforce pg_init_timeout).
659 0 : state_guard.pg_start_time.replace(Utc::now());
660 :
661 0 : state_guard.set_status(ComputeStatus::Init, &self.state_changed);
662 0 : compute_state = state_guard.clone()
663 : }
664 :
665 0 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
666 0 : info!(
667 0 : "starting compute for project {}, operation {}, tenant {}, timeline {}, project {}, branch {}, endpoint {}, features {:?}, spec.remote_extensions {:?}",
668 0 : pspec.spec.cluster.cluster_id.as_deref().unwrap_or("None"),
669 0 : pspec.spec.operation_uuid.as_deref().unwrap_or("None"),
670 : pspec.tenant_id,
671 : pspec.timeline_id,
672 0 : pspec.spec.project_id.as_deref().unwrap_or("None"),
673 0 : pspec.spec.branch_id.as_deref().unwrap_or("None"),
674 0 : pspec.spec.endpoint_id.as_deref().unwrap_or("None"),
675 : pspec.spec.features,
676 : pspec.spec.remote_extensions,
677 : );
678 :
679 : ////// PRE-STARTUP PHASE: things that need to be finished before we start the Postgres process
680 :
681 : // Collect all the tasks that must finish here
682 0 : let mut pre_tasks = tokio::task::JoinSet::new();
683 :
684 : // Make sure TLS certificates are properly loaded and in the right place.
685 0 : if self.compute_ctl_config.tls.is_some() {
686 0 : let this = self.clone();
687 0 : pre_tasks.spawn(async move {
688 0 : this.watch_cert_for_changes().await;
689 :
690 0 : Ok::<(), anyhow::Error>(())
691 0 : });
692 0 : }
693 :
694 0 : let tls_config = self.tls_config(&pspec.spec);
695 :
696 : // If there are any remote extensions in shared_preload_libraries, start downloading them
697 0 : if pspec.spec.remote_extensions.is_some() {
698 0 : let (this, spec) = (self.clone(), pspec.spec.clone());
699 0 : pre_tasks.spawn(async move {
700 0 : this.download_preload_extensions(&spec)
701 0 : .in_current_span()
702 0 : .await
703 0 : });
704 0 : }
705 :
706 : // Prepare pgdata directory. This downloads the basebackup, among other things.
707 : {
708 0 : let (this, cs) = (self.clone(), compute_state.clone());
709 0 : pre_tasks.spawn_blocking_child(move || this.prepare_pgdata(&cs));
710 : }
711 :
712 : // Resize swap to the desired size if the compute spec says so
713 0 : if let (Some(size_bytes), true) =
714 0 : (pspec.spec.swap_size_bytes, self.params.resize_swap_on_bind)
715 : {
716 0 : pre_tasks.spawn_blocking_child(move || {
717 : // To avoid 'swapoff' hitting postgres startup, we need to run resize-swap to completion
718 : // *before* starting postgres.
719 : //
720 : // In theory, we could do this asynchronously if SkipSwapon was enabled for VMs, but this
721 : // carries a risk of introducing hard-to-debug issues - e.g. if postgres sometimes gets
722 : // OOM-killed during startup because swap wasn't available yet.
723 0 : resize_swap(size_bytes).context("failed to resize swap")?;
724 0 : let size_mib = size_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
725 0 : info!(%size_bytes, %size_mib, "resized swap");
726 :
727 0 : Ok::<(), anyhow::Error>(())
728 0 : });
729 0 : }
730 :
731 : // Set disk quota if the compute spec says so
732 0 : if let (Some(disk_quota_bytes), Some(disk_quota_fs_mountpoint)) = (
733 0 : pspec.spec.disk_quota_bytes,
734 0 : self.params.set_disk_quota_for_fs.as_ref(),
735 : ) {
736 0 : let disk_quota_fs_mountpoint = disk_quota_fs_mountpoint.clone();
737 0 : pre_tasks.spawn_blocking_child(move || {
738 0 : set_disk_quota(disk_quota_bytes, &disk_quota_fs_mountpoint)
739 0 : .context("failed to set disk quota")?;
740 0 : let size_mib = disk_quota_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
741 0 : info!(%disk_quota_bytes, %size_mib, "set disk quota");
742 :
743 0 : Ok::<(), anyhow::Error>(())
744 0 : });
745 0 : }
746 :
747 : // tune pgbouncer
748 0 : if let Some(pgbouncer_settings) = &pspec.spec.pgbouncer_settings {
749 0 : info!("tuning pgbouncer");
750 :
751 0 : let pgbouncer_settings = pgbouncer_settings.clone();
752 0 : let tls_config = tls_config.clone();
753 :
754 : // Spawn a background task to do the tuning,
755 : // so that we don't block the main thread that starts Postgres.
756 0 : let _handle = tokio::spawn(async move {
757 0 : let res = tune_pgbouncer(pgbouncer_settings, tls_config).await;
758 0 : if let Err(err) = res {
759 0 : error!("error while tuning pgbouncer: {err:?}");
760 : // Continue with the startup anyway
761 0 : }
762 0 : });
763 0 : }
764 :
765 : // configure local_proxy
766 0 : if let Some(local_proxy) = &pspec.spec.local_proxy_config {
767 0 : info!("configuring local_proxy");
768 :
769 : // Spawn a background task to do the configuration,
770 : // so that we don't block the main thread that starts Postgres.
771 :
772 0 : let mut local_proxy = local_proxy.clone();
773 0 : local_proxy.tls = tls_config.clone();
774 :
775 0 : let _handle = tokio::spawn(async move {
776 0 : if let Err(err) = local_proxy::configure(&local_proxy) {
777 0 : error!("error while configuring local_proxy: {err:?}");
778 : // Continue with the startup anyway
779 0 : }
780 0 : });
781 0 : }
782 :
783 : // Configure and start rsyslog for compliance audit logging
784 0 : match pspec.spec.audit_log_level {
785 : ComputeAudit::Hipaa | ComputeAudit::Extended | ComputeAudit::Full => {
786 0 : let remote_tls_endpoint =
787 0 : std::env::var("AUDIT_LOGGING_TLS_ENDPOINT").unwrap_or("".to_string());
788 0 : let remote_plain_endpoint =
789 0 : std::env::var("AUDIT_LOGGING_ENDPOINT").unwrap_or("".to_string());
790 :
791 0 : if remote_plain_endpoint.is_empty() && remote_tls_endpoint.is_empty() {
792 0 : anyhow::bail!(
793 0 : "AUDIT_LOGGING_ENDPOINT and AUDIT_LOGGING_TLS_ENDPOINT are both empty"
794 : );
795 0 : }
796 :
797 0 : let log_directory_path = Path::new(&self.params.pgdata).join("log");
798 0 : let log_directory_path = log_directory_path.to_string_lossy().to_string();
799 :
800 : // Add project_id,endpoint_id to identify the logs.
801 : //
802 : // These ids are passed from cplane,
803 0 : let endpoint_id = pspec.spec.endpoint_id.as_deref().unwrap_or("");
804 0 : let project_id = pspec.spec.project_id.as_deref().unwrap_or("");
805 :
806 0 : configure_audit_rsyslog(
807 0 : log_directory_path.clone(),
808 0 : endpoint_id,
809 0 : project_id,
810 0 : &remote_plain_endpoint,
811 0 : &remote_tls_endpoint,
812 0 : )?;
813 :
814 : // Launch a background task to clean up the audit logs
815 0 : launch_pgaudit_gc(log_directory_path);
816 : }
817 0 : _ => {}
818 : }
819 :
820 : // Configure and start rsyslog for Postgres logs export
821 0 : let conf = PostgresLogsRsyslogConfig::new(pspec.spec.logs_export_host.as_deref());
822 0 : configure_postgres_logs_export(conf)?;
823 :
824 : // Launch remaining service threads
825 0 : let _monitor_handle = launch_monitor(self);
826 0 : let _configurator_handle = launch_configurator(self);
827 :
828 : // Wait for all the pre-tasks to finish before starting postgres
829 0 : let rt = tokio::runtime::Handle::current();
830 0 : while let Some(res) = rt.block_on(pre_tasks.join_next()) {
831 0 : res??;
832 : }
833 :
834 : ////// START POSTGRES
835 0 : let start_time = Utc::now();
836 0 : let pg_process = self.start_postgres(pspec.storage_auth_token.clone())?;
837 0 : let postmaster_pid = pg_process.pid();
838 0 : *pg_handle = Some(pg_process);
839 :
840 : // If this is a primary endpoint, perform some post-startup configuration before
841 : // opening it up for the world.
842 0 : let config_time = Utc::now();
843 0 : if pspec.spec.mode == ComputeMode::Primary {
844 0 : self.configure_as_primary(&compute_state)?;
845 :
846 0 : let conf = self.get_tokio_conn_conf(None);
847 0 : tokio::task::spawn(async {
848 0 : let _ = installed_extensions(conf).await;
849 0 : });
850 0 : }
851 :
852 : // All done!
853 0 : let startup_end_time = Utc::now();
854 0 : let metrics = {
855 0 : let mut state = self.state.lock().unwrap();
856 0 : state.metrics.start_postgres_ms = config_time
857 0 : .signed_duration_since(start_time)
858 0 : .to_std()
859 0 : .unwrap()
860 0 : .as_millis() as u64;
861 0 : state.metrics.config_ms = startup_end_time
862 0 : .signed_duration_since(config_time)
863 0 : .to_std()
864 0 : .unwrap()
865 0 : .as_millis() as u64;
866 0 : state.metrics.total_startup_ms = startup_end_time
867 0 : .signed_duration_since(compute_state.start_time)
868 0 : .to_std()
869 0 : .unwrap()
870 0 : .as_millis() as u64;
871 0 : state.metrics.clone()
872 : };
873 0 : self.set_status(ComputeStatus::Running);
874 :
875 : // Log metrics so that we can search for slow operations in logs
876 0 : info!(?metrics, postmaster_pid = %postmaster_pid, "compute start finished");
877 :
878 0 : self.spawn_extension_stats_task();
879 :
880 0 : if pspec.spec.autoprewarm {
881 0 : info!("autoprewarming on startup as requested");
882 0 : self.prewarm_lfc(None);
883 0 : }
884 0 : if let Some(seconds) = pspec.spec.offload_lfc_interval_seconds {
885 0 : self.spawn_lfc_offload_task(Duration::from_secs(seconds.into()));
886 0 : };
887 0 : Ok(())
888 0 : }
889 :
890 : #[instrument(skip_all)]
891 : async fn download_preload_extensions(&self, spec: &ComputeSpec) -> Result<()> {
892 : let remote_extensions = if let Some(remote_extensions) = &spec.remote_extensions {
893 : remote_extensions
894 : } else {
895 : return Ok(());
896 : };
897 :
898 : // First, create control files for all available extensions
899 : extension_server::create_control_files(remote_extensions, &self.params.pgbin);
900 :
901 : let library_load_start_time = Utc::now();
902 : let remote_ext_metrics = self.prepare_preload_libraries(spec).await?;
903 :
904 : let library_load_time = Utc::now()
905 : .signed_duration_since(library_load_start_time)
906 : .to_std()
907 : .unwrap()
908 : .as_millis() as u64;
909 : let mut state = self.state.lock().unwrap();
910 : state.metrics.load_ext_ms = library_load_time;
911 : state.metrics.num_ext_downloaded = remote_ext_metrics.num_ext_downloaded;
912 : state.metrics.largest_ext_size = remote_ext_metrics.largest_ext_size;
913 : state.metrics.total_ext_download_size = remote_ext_metrics.total_ext_download_size;
914 : info!(
915 : "Loading shared_preload_libraries took {:?}ms",
916 : library_load_time
917 : );
918 : info!("{:?}", remote_ext_metrics);
919 :
920 : Ok(())
921 : }
922 :
923 : /// Start the vm-monitor if directed to. The vm-monitor only runs on linux
924 : /// because it requires cgroups.
925 0 : fn start_vm_monitor(&self, disable_lfc_resizing: bool) -> StartVmMonitorResult {
926 : cfg_if::cfg_if! {
927 : if #[cfg(target_os = "linux")] {
928 : use std::env;
929 : use tokio_util::sync::CancellationToken;
930 :
931 : // This token is used internally by the monitor to clean up all threads
932 0 : let token = CancellationToken::new();
933 :
934 : // don't pass postgres connection string to vm-monitor if we don't want it to resize LFC
935 0 : let pgconnstr = if disable_lfc_resizing {
936 0 : None
937 : } else {
938 0 : Some(self.params.filecache_connstr.clone())
939 : };
940 :
941 0 : let vm_monitor = if env::var_os("AUTOSCALING").is_some() {
942 0 : let vm_monitor = tokio::spawn(vm_monitor::start(
943 0 : Box::leak(Box::new(vm_monitor::Args {
944 0 : cgroup: Some(self.params.cgroup.clone()),
945 0 : pgconnstr,
946 0 : addr: self.params.vm_monitor_addr.clone(),
947 0 : })),
948 0 : token.clone(),
949 : ));
950 0 : Some(vm_monitor)
951 : } else {
952 0 : None
953 : };
954 0 : StartVmMonitorResult { token, vm_monitor }
955 : } else {
956 : _ = disable_lfc_resizing; // appease unused lint on macOS
957 : StartVmMonitorResult { }
958 : }
959 : }
960 0 : }
961 :
962 0 : fn cleanup_after_postgres_exit(&self) -> Result<bool> {
963 : // Maybe sync safekeepers again, to speed up next startup
964 0 : let compute_state = self.state.lock().unwrap().clone();
965 0 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
966 0 : let lsn = if matches!(pspec.spec.mode, compute_api::spec::ComputeMode::Primary) {
967 0 : info!("syncing safekeepers on shutdown");
968 0 : let storage_auth_token = pspec.storage_auth_token.clone();
969 0 : let lsn = self.sync_safekeepers(storage_auth_token)?;
970 0 : info!(%lsn, "synced safekeepers");
971 0 : Some(lsn)
972 : } else {
973 0 : info!("not primary, not syncing safekeepers");
974 0 : None
975 : };
976 :
977 0 : let mut state = self.state.lock().unwrap();
978 0 : state.terminate_flush_lsn = lsn;
979 :
980 0 : let delay_exit = state.status == ComputeStatus::TerminationPendingFast;
981 0 : if state.status == ComputeStatus::TerminationPendingFast
982 0 : || state.status == ComputeStatus::TerminationPendingImmediate
983 : {
984 0 : info!(
985 0 : "Changing compute status from {} to {}",
986 0 : state.status,
987 : ComputeStatus::Terminated
988 : );
989 0 : state.status = ComputeStatus::Terminated;
990 0 : self.state_changed.notify_all();
991 0 : }
992 0 : drop(state);
993 :
994 0 : if let Err(err) = self.check_for_core_dumps() {
995 0 : error!("error while checking for core dumps: {err:?}");
996 0 : }
997 :
998 0 : Ok(delay_exit)
999 0 : }
1000 :
1001 : /// Check that compute node has corresponding feature enabled.
1002 0 : pub fn has_feature(&self, feature: ComputeFeature) -> bool {
1003 0 : let state = self.state.lock().unwrap();
1004 :
1005 0 : if let Some(s) = state.pspec.as_ref() {
1006 0 : s.spec.features.contains(&feature)
1007 : } else {
1008 0 : false
1009 : }
1010 0 : }
1011 :
1012 0 : pub fn set_status(&self, status: ComputeStatus) {
1013 0 : let mut state = self.state.lock().unwrap();
1014 0 : state.set_status(status, &self.state_changed);
1015 0 : }
1016 :
1017 0 : pub fn set_failed_status(&self, err: anyhow::Error) {
1018 0 : let mut state = self.state.lock().unwrap();
1019 0 : state.set_failed_status(err, &self.state_changed);
1020 0 : }
1021 :
1022 0 : pub fn get_status(&self) -> ComputeStatus {
1023 0 : self.state.lock().unwrap().status
1024 0 : }
1025 :
1026 0 : pub fn get_timeline_id(&self) -> Option<TimelineId> {
1027 0 : self.state
1028 0 : .lock()
1029 0 : .unwrap()
1030 0 : .pspec
1031 0 : .as_ref()
1032 0 : .map(|s| s.timeline_id)
1033 0 : }
1034 :
1035 : // Remove `pgdata` directory and create it again with right permissions.
1036 0 : fn create_pgdata(&self) -> Result<()> {
1037 : // Ignore removal error, likely it is a 'No such file or directory (os error 2)'.
1038 : // If it is something different then create_dir() will error out anyway.
1039 0 : let pgdata = &self.params.pgdata;
1040 0 : let _ok = fs::remove_dir_all(pgdata);
1041 0 : fs::create_dir(pgdata)?;
1042 0 : fs::set_permissions(pgdata, fs::Permissions::from_mode(0o700))?;
1043 :
1044 0 : Ok(())
1045 0 : }
1046 :
1047 : /// Fetches a basebackup from the Pageserver using the compute state's Pageserver connstring and
1048 : /// unarchives it to `pgdata` directory, replacing any existing contents.
1049 : #[instrument(skip_all, fields(%lsn))]
1050 : fn try_get_basebackup(&self, compute_state: &ComputeState, lsn: Lsn) -> Result<()> {
1051 : let spec = compute_state.pspec.as_ref().expect("spec must be set");
1052 :
1053 : let shard0_connstr = spec.pageserver_connstr.split(',').next().unwrap();
1054 : let started = Instant::now();
1055 :
1056 : let (connected, size) = match PageserverProtocol::from_connstring(shard0_connstr)? {
1057 : PageserverProtocol::Libpq => self.try_get_basebackup_libpq(spec, lsn)?,
1058 : PageserverProtocol::Grpc => self.try_get_basebackup_grpc(spec, lsn)?,
1059 : };
1060 :
1061 : self.fix_zenith_signal_neon_signal()?;
1062 :
1063 : let mut state = self.state.lock().unwrap();
1064 : state.metrics.pageserver_connect_micros =
1065 : connected.duration_since(started).as_micros() as u64;
1066 : state.metrics.basebackup_bytes = size as u64;
1067 : state.metrics.basebackup_ms = started.elapsed().as_millis() as u64;
1068 :
1069 : Ok(())
1070 : }
1071 :
1072 : /// Move the Zenith signal file to Neon signal file location.
1073 : /// This makes Compute compatible with older PageServers that don't yet
1074 : /// know about the Zenith->Neon rename.
1075 0 : fn fix_zenith_signal_neon_signal(&self) -> Result<()> {
1076 0 : let datadir = Path::new(&self.params.pgdata);
1077 :
1078 0 : let neonsig = datadir.join("neon.signal");
1079 :
1080 0 : if neonsig.is_file() {
1081 0 : return Ok(());
1082 0 : }
1083 :
1084 0 : let zenithsig = datadir.join("zenith.signal");
1085 :
1086 0 : if zenithsig.is_file() {
1087 0 : fs::copy(zenithsig, neonsig)?;
1088 0 : }
1089 :
1090 0 : Ok(())
1091 0 : }
1092 :
1093 : /// Fetches a basebackup via gRPC. The connstring must use grpc://. Returns the timestamp when
1094 : /// the connection was established, and the (compressed) size of the basebackup.
1095 0 : fn try_get_basebackup_grpc(&self, spec: &ParsedSpec, lsn: Lsn) -> Result<(Instant, usize)> {
1096 0 : let shard0_connstr = spec
1097 0 : .pageserver_connstr
1098 0 : .split(',')
1099 0 : .next()
1100 0 : .unwrap()
1101 0 : .to_string();
1102 0 : let shard_index = match spec.pageserver_connstr.split(',').count() as u8 {
1103 0 : 0 | 1 => ShardIndex::unsharded(),
1104 0 : count => ShardIndex::new(ShardNumber(0), ShardCount(count)),
1105 : };
1106 :
1107 0 : let (reader, connected) = tokio::runtime::Handle::current().block_on(async move {
1108 0 : let mut client = page_api::Client::connect(
1109 0 : shard0_connstr,
1110 0 : spec.tenant_id,
1111 0 : spec.timeline_id,
1112 0 : shard_index,
1113 0 : spec.storage_auth_token.clone(),
1114 0 : None, // NB: base backups use payload compression
1115 0 : )
1116 0 : .await?;
1117 0 : let connected = Instant::now();
1118 0 : let reader = client
1119 0 : .get_base_backup(page_api::GetBaseBackupRequest {
1120 0 : lsn: (lsn != Lsn(0)).then_some(lsn),
1121 0 : compression: BaseBackupCompression::Gzip,
1122 0 : replica: spec.spec.mode != ComputeMode::Primary,
1123 0 : full: false,
1124 0 : })
1125 0 : .await?;
1126 0 : anyhow::Ok((reader, connected))
1127 0 : })?;
1128 :
1129 0 : let mut reader = MeasuredReader::new(tokio_util::io::SyncIoBridge::new(reader));
1130 :
1131 : // Set `ignore_zeros` so that unpack() reads the entire stream and doesn't just stop at the
1132 : // end-of-archive marker. If the server errors, the tar::Builder drop handler will write an
1133 : // end-of-archive marker before the error is emitted, and we would not see the error.
1134 0 : let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&mut reader));
1135 0 : ar.set_ignore_zeros(true);
1136 0 : ar.unpack(&self.params.pgdata)?;
1137 :
1138 0 : Ok((connected, reader.get_byte_count()))
1139 0 : }
1140 :
1141 : /// Fetches a basebackup via libpq. The connstring must use postgresql://. Returns the timestamp
1142 : /// when the connection was established, and the (compressed) size of the basebackup.
1143 0 : fn try_get_basebackup_libpq(&self, spec: &ParsedSpec, lsn: Lsn) -> Result<(Instant, usize)> {
1144 0 : let shard0_connstr = spec.pageserver_connstr.split(',').next().unwrap();
1145 0 : let mut config = postgres::Config::from_str(shard0_connstr)?;
1146 :
1147 : // Use the storage auth token from the config file, if given.
1148 : // Note: this overrides any password set in the connection string.
1149 0 : if let Some(storage_auth_token) = &spec.storage_auth_token {
1150 0 : info!("Got storage auth token from spec file");
1151 0 : config.password(storage_auth_token);
1152 : } else {
1153 0 : info!("Storage auth token not set");
1154 : }
1155 :
1156 0 : config.application_name("compute_ctl");
1157 0 : config.options(&format!(
1158 0 : "-c neon.compute_mode={}",
1159 0 : spec.spec.mode.to_type_str()
1160 0 : ));
1161 :
1162 : // Connect to pageserver
1163 0 : let mut client = config.connect(NoTls)?;
1164 0 : let connected = Instant::now();
1165 :
1166 0 : let basebackup_cmd = match lsn {
1167 : Lsn(0) => {
1168 0 : if spec.spec.mode != ComputeMode::Primary {
1169 0 : format!(
1170 0 : "basebackup {} {} --gzip --replica",
1171 : spec.tenant_id, spec.timeline_id
1172 : )
1173 : } else {
1174 0 : format!("basebackup {} {} --gzip", spec.tenant_id, spec.timeline_id)
1175 : }
1176 : }
1177 : _ => {
1178 0 : if spec.spec.mode != ComputeMode::Primary {
1179 0 : format!(
1180 0 : "basebackup {} {} {} --gzip --replica",
1181 : spec.tenant_id, spec.timeline_id, lsn
1182 : )
1183 : } else {
1184 0 : format!(
1185 0 : "basebackup {} {} {} --gzip",
1186 : spec.tenant_id, spec.timeline_id, lsn
1187 : )
1188 : }
1189 : }
1190 : };
1191 :
1192 0 : let copyreader = client.copy_out(basebackup_cmd.as_str())?;
1193 0 : let mut measured_reader = MeasuredReader::new(copyreader);
1194 0 : let mut bufreader = std::io::BufReader::new(&mut measured_reader);
1195 :
1196 : // Read the archive directly from the `CopyOutReader`
1197 : //
1198 : // Set `ignore_zeros` so that unpack() reads all the Copy data and
1199 : // doesn't stop at the end-of-archive marker. Otherwise, if the server
1200 : // sends an Error after finishing the tarball, we will not notice it.
1201 : // The tar::Builder drop handler will write an end-of-archive marker
1202 : // before emitting the error, and we would not see it otherwise.
1203 0 : let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&mut bufreader));
1204 0 : ar.set_ignore_zeros(true);
1205 0 : ar.unpack(&self.params.pgdata)?;
1206 :
1207 0 : Ok((connected, measured_reader.get_byte_count()))
1208 0 : }
1209 :
1210 : // Gets the basebackup in a retry loop
1211 : #[instrument(skip_all, fields(%lsn))]
1212 : pub fn get_basebackup(&self, compute_state: &ComputeState, lsn: Lsn) -> Result<()> {
1213 : let mut retry_period_ms = 500.0;
1214 : let mut attempts = 0;
1215 : const DEFAULT_ATTEMPTS: u16 = 10;
1216 : #[cfg(feature = "testing")]
1217 : let max_attempts = if let Ok(v) = env::var("NEON_COMPUTE_TESTING_BASEBACKUP_RETRIES") {
1218 : u16::from_str(&v).unwrap()
1219 : } else {
1220 : DEFAULT_ATTEMPTS
1221 : };
1222 : #[cfg(not(feature = "testing"))]
1223 : let max_attempts = DEFAULT_ATTEMPTS;
1224 : loop {
1225 : let result = self.try_get_basebackup(compute_state, lsn);
1226 : match result {
1227 : Ok(_) => {
1228 : return result;
1229 : }
1230 : Err(ref e) if attempts < max_attempts => {
1231 : warn!(
1232 : "Failed to get basebackup: {} (attempt {}/{})",
1233 : e, attempts, max_attempts
1234 : );
1235 : std::thread::sleep(std::time::Duration::from_millis(retry_period_ms as u64));
1236 : retry_period_ms *= 1.5;
1237 : }
1238 : Err(_) => {
1239 : return result;
1240 : }
1241 : }
1242 : attempts += 1;
1243 : }
1244 : }
1245 :
1246 0 : pub async fn check_safekeepers_synced_async(
1247 0 : &self,
1248 0 : compute_state: &ComputeState,
1249 0 : ) -> Result<Option<Lsn>> {
1250 : // Construct a connection config for each safekeeper
1251 0 : let pspec: ParsedSpec = compute_state
1252 0 : .pspec
1253 0 : .as_ref()
1254 0 : .expect("spec must be set")
1255 0 : .clone();
1256 0 : let sk_connstrs: Vec<String> = pspec.safekeeper_connstrings.clone();
1257 0 : let sk_configs = sk_connstrs.into_iter().map(|connstr| {
1258 : // Format connstr
1259 0 : let id = connstr.clone();
1260 0 : let connstr = format!("postgresql://no_user@{connstr}");
1261 0 : let options = format!(
1262 0 : "-c timeline_id={} tenant_id={}",
1263 : pspec.timeline_id, pspec.tenant_id
1264 : );
1265 :
1266 : // Construct client
1267 0 : let mut config = tokio_postgres::Config::from_str(&connstr).unwrap();
1268 0 : config.options(&options);
1269 0 : if let Some(storage_auth_token) = pspec.storage_auth_token.clone() {
1270 0 : config.password(storage_auth_token);
1271 0 : }
1272 :
1273 0 : (id, config)
1274 0 : });
1275 :
1276 : // Create task set to query all safekeepers
1277 0 : let mut tasks = FuturesUnordered::new();
1278 0 : let quorum = sk_configs.len() / 2 + 1;
1279 0 : for (id, config) in sk_configs {
1280 0 : let timeout = tokio::time::Duration::from_millis(100);
1281 0 : let task = tokio::time::timeout(timeout, ping_safekeeper(id, config));
1282 0 : tasks.push(tokio::spawn(task));
1283 0 : }
1284 :
1285 : // Get a quorum of responses or errors
1286 0 : let mut responses = Vec::new();
1287 0 : let mut join_errors = Vec::new();
1288 0 : let mut task_errors = Vec::new();
1289 0 : let mut timeout_errors = Vec::new();
1290 0 : while let Some(response) = tasks.next().await {
1291 0 : match response {
1292 0 : Ok(Ok(Ok(r))) => responses.push(r),
1293 0 : Ok(Ok(Err(e))) => task_errors.push(e),
1294 0 : Ok(Err(e)) => timeout_errors.push(e),
1295 0 : Err(e) => join_errors.push(e),
1296 : };
1297 0 : if responses.len() >= quorum {
1298 0 : break;
1299 0 : }
1300 0 : if join_errors.len() + task_errors.len() + timeout_errors.len() >= quorum {
1301 0 : break;
1302 0 : }
1303 : }
1304 :
1305 : // In case of error, log and fail the check, but don't crash.
1306 : // We're playing it safe because these errors could be transient
1307 : // and we don't yet retry.
1308 0 : if responses.len() < quorum {
1309 0 : error!(
1310 0 : "failed sync safekeepers check {:?} {:?} {:?}",
1311 : join_errors, task_errors, timeout_errors
1312 : );
1313 0 : return Ok(None);
1314 0 : }
1315 :
1316 0 : Ok(check_if_synced(responses))
1317 0 : }
1318 :
1319 : // Fast path for sync_safekeepers. If they're already synced we get the lsn
1320 : // in one roundtrip. If not, we should do a full sync_safekeepers.
1321 : #[instrument(skip_all)]
1322 : pub fn check_safekeepers_synced(&self, compute_state: &ComputeState) -> Result<Option<Lsn>> {
1323 : let start_time = Utc::now();
1324 :
1325 : let rt = tokio::runtime::Handle::current();
1326 : let result = rt.block_on(self.check_safekeepers_synced_async(compute_state));
1327 :
1328 : // Record runtime
1329 : self.state.lock().unwrap().metrics.sync_sk_check_ms = Utc::now()
1330 : .signed_duration_since(start_time)
1331 : .to_std()
1332 : .unwrap()
1333 : .as_millis() as u64;
1334 : result
1335 : }
1336 :
1337 : // Run `postgres` in a special mode with `--sync-safekeepers` argument
1338 : // and return the reported LSN back to the caller.
1339 : #[instrument(skip_all)]
1340 : pub fn sync_safekeepers(&self, storage_auth_token: Option<String>) -> Result<Lsn> {
1341 : let start_time = Utc::now();
1342 :
1343 : let mut sync_handle = maybe_cgexec(&self.params.pgbin)
1344 : .args(["--sync-safekeepers"])
1345 : .env("PGDATA", &self.params.pgdata) // we cannot use -D in this mode
1346 : .envs(if let Some(storage_auth_token) = &storage_auth_token {
1347 : vec![("NEON_AUTH_TOKEN", storage_auth_token)]
1348 : } else {
1349 : vec![]
1350 : })
1351 : .stdout(Stdio::piped())
1352 : .stderr(Stdio::piped())
1353 : .spawn()
1354 : .expect("postgres --sync-safekeepers failed to start");
1355 : SYNC_SAFEKEEPERS_PID.store(sync_handle.id(), Ordering::SeqCst);
1356 :
1357 : // `postgres --sync-safekeepers` will print all log output to stderr and
1358 : // final LSN to stdout. So we leave stdout to collect LSN, while stderr logs
1359 : // will be collected in a child thread.
1360 : let stderr = sync_handle
1361 : .stderr
1362 : .take()
1363 : .expect("stderr should be captured");
1364 : let logs_handle = handle_postgres_logs(stderr);
1365 :
1366 : let sync_output = sync_handle
1367 : .wait_with_output()
1368 : .expect("postgres --sync-safekeepers failed");
1369 : SYNC_SAFEKEEPERS_PID.store(0, Ordering::SeqCst);
1370 :
1371 : // Process has exited, so we can join the logs thread.
1372 : let _ = tokio::runtime::Handle::current()
1373 : .block_on(logs_handle)
1374 0 : .map_err(|e| tracing::error!("log task panicked: {:?}", e));
1375 :
1376 : if !sync_output.status.success() {
1377 : anyhow::bail!(
1378 : "postgres --sync-safekeepers exited with non-zero status: {}. stdout: {}",
1379 : sync_output.status,
1380 : String::from_utf8(sync_output.stdout)
1381 : .expect("postgres --sync-safekeepers exited, and stdout is not utf-8"),
1382 : );
1383 : }
1384 :
1385 : self.state.lock().unwrap().metrics.sync_safekeepers_ms = Utc::now()
1386 : .signed_duration_since(start_time)
1387 : .to_std()
1388 : .unwrap()
1389 : .as_millis() as u64;
1390 :
1391 : let lsn = Lsn::from_str(String::from_utf8(sync_output.stdout)?.trim())?;
1392 :
1393 : Ok(lsn)
1394 : }
1395 :
1396 : /// Do all the preparations like PGDATA directory creation, configuration,
1397 : /// safekeepers sync, basebackup, etc.
1398 : #[instrument(skip_all)]
1399 : pub fn prepare_pgdata(&self, compute_state: &ComputeState) -> Result<()> {
1400 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
1401 : let spec = &pspec.spec;
1402 : let pgdata_path = Path::new(&self.params.pgdata);
1403 :
1404 : let tls_config = self.tls_config(&pspec.spec);
1405 :
1406 : // Remove/create an empty pgdata directory and put configuration there.
1407 : self.create_pgdata()?;
1408 : config::write_postgres_conf(
1409 : pgdata_path,
1410 : &self.params,
1411 : &pspec.spec,
1412 : self.params.internal_http_port,
1413 : tls_config,
1414 : )?;
1415 :
1416 : // Syncing safekeepers is only safe with primary nodes: if a primary
1417 : // is already connected it will be kicked out, so a secondary (standby)
1418 : // cannot sync safekeepers.
1419 : let lsn = match spec.mode {
1420 : ComputeMode::Primary => {
1421 : info!("checking if safekeepers are synced");
1422 : let lsn = if let Ok(Some(lsn)) = self.check_safekeepers_synced(compute_state) {
1423 : lsn
1424 : } else {
1425 : info!("starting safekeepers syncing");
1426 : self.sync_safekeepers(pspec.storage_auth_token.clone())
1427 : .with_context(|| "failed to sync safekeepers")?
1428 : };
1429 : info!("safekeepers synced at LSN {}", lsn);
1430 : lsn
1431 : }
1432 : ComputeMode::Static(lsn) => {
1433 : info!("Starting read-only node at static LSN {}", lsn);
1434 : lsn
1435 : }
1436 : ComputeMode::Replica => {
1437 : info!("Initializing standby from latest Pageserver LSN");
1438 : Lsn(0)
1439 : }
1440 : };
1441 :
1442 : info!(
1443 : "getting basebackup@{} from pageserver {}",
1444 : lsn, &pspec.pageserver_connstr
1445 : );
1446 0 : self.get_basebackup(compute_state, lsn).with_context(|| {
1447 0 : format!(
1448 0 : "failed to get basebackup@{} from pageserver {}",
1449 0 : lsn, &pspec.pageserver_connstr
1450 : )
1451 0 : })?;
1452 :
1453 : // Update pg_hba.conf received with basebackup.
1454 : update_pg_hba(pgdata_path, None)?;
1455 :
1456 : // Place pg_dynshmem under /dev/shm. This allows us to use
1457 : // 'dynamic_shared_memory_type = mmap' so that the files are placed in
1458 : // /dev/shm, similar to how 'dynamic_shared_memory_type = posix' works.
1459 : //
1460 : // Why on earth don't we just stick to the 'posix' default, you might
1461 : // ask. It turns out that making large allocations with 'posix' doesn't
1462 : // work very well with autoscaling. The behavior we want is that:
1463 : //
1464 : // 1. You can make large DSM allocations, larger than the current RAM
1465 : // size of the VM, without errors
1466 : //
1467 : // 2. If the allocated memory is really used, the VM is scaled up
1468 : // automatically to accommodate that
1469 : //
1470 : // We try to make that possible by having swap in the VM. But with the
1471 : // default 'posix' DSM implementation, we fail step 1, even when there's
1472 : // plenty of swap available. PostgreSQL uses posix_fallocate() to create
1473 : // the shmem segment, which is really just a file in /dev/shm in Linux,
1474 : // but posix_fallocate() on tmpfs returns ENOMEM if the size is larger
1475 : // than available RAM.
1476 : //
1477 : // Using 'dynamic_shared_memory_type = mmap' works around that, because
1478 : // the Postgres 'mmap' DSM implementation doesn't use
1479 : // posix_fallocate(). Instead, it uses repeated calls to write(2) to
1480 : // fill the file with zeros. It's weird that that differs between
1481 : // 'posix' and 'mmap', but we take advantage of it. When the file is
1482 : // filled slowly with write(2), the kernel allows it to grow larger, as
1483 : // long as there's swap available.
1484 : //
1485 : // In short, using 'dynamic_shared_memory_type = mmap' allows us one DSM
1486 : // segment to be larger than currently available RAM. But because we
1487 : // don't want to store it on a real file, which the kernel would try to
1488 : // flush to disk, so symlink pg_dynshm to /dev/shm.
1489 : //
1490 : // We don't set 'dynamic_shared_memory_type = mmap' here, we let the
1491 : // control plane control that option. If 'mmap' is not used, this
1492 : // symlink doesn't affect anything.
1493 : //
1494 : // See https://github.com/neondatabase/autoscaling/issues/800
1495 : std::fs::remove_dir(pgdata_path.join("pg_dynshmem"))?;
1496 : symlink("/dev/shm/", pgdata_path.join("pg_dynshmem"))?;
1497 :
1498 : match spec.mode {
1499 : ComputeMode::Primary => {}
1500 : ComputeMode::Replica | ComputeMode::Static(..) => {
1501 : add_standby_signal(pgdata_path)?;
1502 : }
1503 : }
1504 :
1505 : Ok(())
1506 : }
1507 :
1508 : /// Start and stop a postgres process to warm up the VM for startup.
1509 0 : pub fn prewarm_postgres_vm_memory(&self) -> Result<()> {
1510 0 : info!("prewarming VM memory");
1511 :
1512 : // Create pgdata
1513 0 : let pgdata = &format!("{}.warmup", self.params.pgdata);
1514 0 : create_pgdata(pgdata)?;
1515 :
1516 : // Run initdb to completion
1517 0 : info!("running initdb");
1518 0 : let initdb_bin = Path::new(&self.params.pgbin)
1519 0 : .parent()
1520 0 : .unwrap()
1521 0 : .join("initdb");
1522 0 : Command::new(initdb_bin)
1523 0 : .args(["--pgdata", pgdata])
1524 0 : .output()
1525 0 : .expect("cannot start initdb process");
1526 :
1527 : // Write conf
1528 : use std::io::Write;
1529 0 : let conf_path = Path::new(pgdata).join("postgresql.conf");
1530 0 : let mut file = std::fs::File::create(conf_path)?;
1531 0 : writeln!(file, "shared_buffers=65536")?;
1532 0 : writeln!(file, "port=51055")?; // Nobody should be connecting
1533 0 : writeln!(file, "shared_preload_libraries = 'neon'")?;
1534 :
1535 : // Start postgres
1536 0 : info!("starting postgres");
1537 0 : let mut pg = maybe_cgexec(&self.params.pgbin)
1538 0 : .args(["-D", pgdata])
1539 0 : .spawn()
1540 0 : .expect("cannot start postgres process");
1541 :
1542 : // Stop it when it's ready
1543 0 : info!("waiting for postgres");
1544 0 : wait_for_postgres(&mut pg, Path::new(pgdata))?;
1545 : // SIGQUIT orders postgres to exit immediately. We don't want to SIGKILL
1546 : // it to avoid orphaned processes prowling around while datadir is
1547 : // wiped.
1548 0 : let pm_pid = Pid::from_raw(pg.id() as i32);
1549 0 : kill(pm_pid, Signal::SIGQUIT)?;
1550 0 : info!("sent SIGQUIT signal");
1551 0 : pg.wait()?;
1552 0 : info!("done prewarming vm memory");
1553 :
1554 : // clean up
1555 0 : let _ok = fs::remove_dir_all(pgdata);
1556 0 : Ok(())
1557 0 : }
1558 :
1559 : /// Start Postgres as a child process and wait for it to start accepting
1560 : /// connections.
1561 : ///
1562 : /// Returns a handle to the child process and a handle to the logs thread.
1563 : #[instrument(skip_all)]
1564 : pub fn start_postgres(&self, storage_auth_token: Option<String>) -> Result<PostgresHandle> {
1565 : let pgdata_path = Path::new(&self.params.pgdata);
1566 :
1567 : // Run postgres as a child process.
1568 : let mut pg = maybe_cgexec(&self.params.pgbin)
1569 : .args(["-D", &self.params.pgdata])
1570 : .envs(if let Some(storage_auth_token) = &storage_auth_token {
1571 : vec![("NEON_AUTH_TOKEN", storage_auth_token)]
1572 : } else {
1573 : vec![]
1574 : })
1575 : .stderr(Stdio::piped())
1576 : .spawn()
1577 : .expect("cannot start postgres process");
1578 : PG_PID.store(pg.id(), Ordering::SeqCst);
1579 :
1580 : // Start a task to collect logs from stderr.
1581 : let stderr = pg.stderr.take().expect("stderr should be captured");
1582 : let logs_handle = handle_postgres_logs(stderr);
1583 :
1584 : wait_for_postgres(&mut pg, pgdata_path)?;
1585 :
1586 : Ok(PostgresHandle {
1587 : postgres: pg,
1588 : log_collector: logs_handle,
1589 : })
1590 : }
1591 :
1592 : /// Wait for the child Postgres process forever. In this state Ctrl+C will
1593 : /// propagate to Postgres and it will be shut down as well.
1594 0 : fn wait_postgres(&self, mut pg_handle: PostgresHandle) -> std::process::ExitStatus {
1595 0 : info!(postmaster_pid = %pg_handle.postgres.id(), "Waiting for Postgres to exit");
1596 :
1597 0 : let ecode = pg_handle
1598 0 : .postgres
1599 0 : .wait()
1600 0 : .expect("failed to start waiting on Postgres process");
1601 0 : PG_PID.store(0, Ordering::SeqCst);
1602 :
1603 : // Process has exited. Wait for the log collecting task to finish.
1604 0 : let _ = tokio::runtime::Handle::current()
1605 0 : .block_on(pg_handle.log_collector)
1606 0 : .map_err(|e| tracing::error!("log task panicked: {:?}", e));
1607 :
1608 0 : ecode
1609 0 : }
1610 :
1611 : /// Do post configuration of the already started Postgres. This function spawns a background task to
1612 : /// configure the database after applying the compute spec. Currently, it upgrades the neon extension
1613 : /// version. In the future, it may upgrade all 3rd-party extensions.
1614 : #[instrument(skip_all)]
1615 : pub fn post_apply_config(&self) -> Result<()> {
1616 : let conf = self.get_tokio_conn_conf(Some("compute_ctl:post_apply_config"));
1617 0 : tokio::spawn(async move {
1618 0 : let res = async {
1619 0 : let (mut client, connection) = conf.connect(NoTls).await?;
1620 0 : tokio::spawn(async move {
1621 0 : if let Err(e) = connection.await {
1622 0 : eprintln!("connection error: {e}");
1623 0 : }
1624 0 : });
1625 :
1626 0 : handle_neon_extension_upgrade(&mut client)
1627 0 : .await
1628 0 : .context("handle_neon_extension_upgrade")?;
1629 0 : Ok::<_, anyhow::Error>(())
1630 0 : }
1631 0 : .await;
1632 0 : if let Err(err) = res {
1633 0 : error!("error while post_apply_config: {err:#}");
1634 0 : }
1635 0 : });
1636 : Ok(())
1637 : }
1638 :
1639 0 : pub fn get_conn_conf(&self, application_name: Option<&str>) -> postgres::Config {
1640 0 : let mut conf = self.conn_conf.clone();
1641 0 : if let Some(application_name) = application_name {
1642 0 : conf.application_name(application_name);
1643 0 : }
1644 0 : conf
1645 0 : }
1646 :
1647 0 : pub fn get_tokio_conn_conf(&self, application_name: Option<&str>) -> tokio_postgres::Config {
1648 0 : let mut conf = self.tokio_conn_conf.clone();
1649 0 : if let Some(application_name) = application_name {
1650 0 : conf.application_name(application_name);
1651 0 : }
1652 0 : conf
1653 0 : }
1654 :
1655 0 : pub async fn get_maintenance_client(
1656 0 : conf: &tokio_postgres::Config,
1657 0 : ) -> Result<tokio_postgres::Client> {
1658 0 : let mut conf = conf.clone();
1659 0 : conf.application_name("compute_ctl:apply_config");
1660 :
1661 0 : let (client, conn) = match conf.connect(NoTls).await {
1662 : // If connection fails, it may be the old node with `zenith_admin` superuser.
1663 : //
1664 : // In this case we need to connect with old `zenith_admin` name
1665 : // and create new user. We cannot simply rename connected user,
1666 : // but we can create a new one and grant it all privileges.
1667 0 : Err(e) => match e.code() {
1668 : Some(&SqlState::INVALID_PASSWORD)
1669 : | Some(&SqlState::INVALID_AUTHORIZATION_SPECIFICATION) => {
1670 : // Connect with `zenith_admin` if `cloud_admin` could not authenticate
1671 0 : info!(
1672 0 : "cannot connect to Postgres: {}, retrying with 'zenith_admin' username",
1673 : e
1674 : );
1675 0 : let mut zenith_admin_conf = postgres::config::Config::from(conf.clone());
1676 0 : zenith_admin_conf.application_name("compute_ctl:apply_config");
1677 0 : zenith_admin_conf.user("zenith_admin");
1678 :
1679 : // It doesn't matter what were the options before, here we just want
1680 : // to connect and create a new superuser role.
1681 : const ZENITH_OPTIONS: &str = "-c role=zenith_admin -c default_transaction_read_only=off -c search_path=public -c statement_timeout=0";
1682 0 : zenith_admin_conf.options(ZENITH_OPTIONS);
1683 :
1684 0 : let mut client =
1685 0 : zenith_admin_conf.connect(NoTls)
1686 0 : .context("broken cloud_admin credential: tried connecting with cloud_admin but could not authenticate, and zenith_admin does not work either")?;
1687 :
1688 : // Disable forwarding so that users don't get a cloud_admin role
1689 0 : let mut func = || {
1690 0 : client.simple_query("SET neon.forward_ddl = false")?;
1691 0 : client.simple_query("CREATE USER cloud_admin WITH SUPERUSER")?;
1692 0 : client.simple_query("GRANT zenith_admin TO cloud_admin")?;
1693 0 : Ok::<_, anyhow::Error>(())
1694 0 : };
1695 0 : func().context("apply_config setup cloud_admin")?;
1696 :
1697 0 : drop(client);
1698 :
1699 : // Reconnect with connstring with expected name
1700 0 : conf.connect(NoTls).await?
1701 : }
1702 0 : _ => return Err(e.into()),
1703 : },
1704 0 : Ok((client, conn)) => (client, conn),
1705 : };
1706 :
1707 0 : spawn(async move {
1708 0 : if let Err(e) = conn.await {
1709 0 : error!("maintenance client connection error: {}", e);
1710 0 : }
1711 0 : });
1712 :
1713 : // Disable DDL forwarding because control plane already knows about the roles/databases
1714 : // we're about to modify.
1715 0 : client
1716 0 : .simple_query("SET neon.forward_ddl = false")
1717 0 : .await
1718 0 : .context("apply_config SET neon.forward_ddl = false")?;
1719 :
1720 0 : Ok(client)
1721 0 : }
1722 :
1723 : /// Do initial configuration of the already started Postgres.
1724 : #[instrument(skip_all)]
1725 : pub fn apply_config(&self, compute_state: &ComputeState) -> Result<()> {
1726 : let conf = self.get_tokio_conn_conf(Some("compute_ctl:apply_config"));
1727 :
1728 : let conf = Arc::new(conf);
1729 : let spec = Arc::new(
1730 : compute_state
1731 : .pspec
1732 : .as_ref()
1733 : .expect("spec must be set")
1734 : .spec
1735 : .clone(),
1736 : );
1737 :
1738 : let mut tls_config = None::<TlsConfig>;
1739 : if spec.features.contains(&ComputeFeature::TlsExperimental) {
1740 : tls_config = self.compute_ctl_config.tls.clone();
1741 : }
1742 :
1743 : self.update_installed_extensions_collection_interval(&spec);
1744 :
1745 : let max_concurrent_connections = self.max_service_connections(compute_state, &spec);
1746 :
1747 : // Merge-apply spec & changes to PostgreSQL state.
1748 : self.apply_spec_sql(spec.clone(), conf.clone(), max_concurrent_connections)?;
1749 :
1750 : if let Some(local_proxy) = &spec.clone().local_proxy_config {
1751 : let mut local_proxy = local_proxy.clone();
1752 : local_proxy.tls = tls_config.clone();
1753 :
1754 : info!("configuring local_proxy");
1755 : local_proxy::configure(&local_proxy).context("apply_config local_proxy")?;
1756 : }
1757 :
1758 : // Run migrations separately to not hold up cold starts
1759 : let lakebase_mode = self.params.lakebase_mode;
1760 : let params = self.params.clone();
1761 0 : tokio::spawn(async move {
1762 0 : let mut conf = conf.as_ref().clone();
1763 0 : conf.application_name("compute_ctl:migrations");
1764 :
1765 0 : match conf.connect(NoTls).await {
1766 0 : Ok((mut client, connection)) => {
1767 0 : tokio::spawn(async move {
1768 0 : if let Err(e) = connection.await {
1769 0 : eprintln!("connection error: {e}");
1770 0 : }
1771 0 : });
1772 0 : if let Err(e) = handle_migrations(params, &mut client, lakebase_mode).await {
1773 0 : error!("Failed to run migrations: {}", e);
1774 0 : }
1775 : }
1776 0 : Err(e) => {
1777 0 : error!(
1778 0 : "Failed to connect to the compute for running migrations: {}",
1779 : e
1780 : );
1781 : }
1782 : };
1783 0 : });
1784 :
1785 : Ok::<(), anyhow::Error>(())
1786 : }
1787 :
1788 : // Wrapped this around `pg_ctl reload`, but right now we don't use
1789 : // `pg_ctl` for start / stop.
1790 : #[instrument(skip_all)]
1791 : fn pg_reload_conf(&self) -> Result<()> {
1792 : let pgctl_bin = Path::new(&self.params.pgbin)
1793 : .parent()
1794 : .unwrap()
1795 : .join("pg_ctl");
1796 : Command::new(pgctl_bin)
1797 : .args(["reload", "-D", &self.params.pgdata])
1798 : .output()
1799 : .expect("cannot run pg_ctl process");
1800 : Ok(())
1801 : }
1802 :
1803 : /// Similar to `apply_config()`, but does a bit different sequence of operations,
1804 : /// as it's used to reconfigure a previously started and configured Postgres node.
1805 : #[instrument(skip_all)]
1806 : pub fn reconfigure(&self) -> Result<()> {
1807 : let spec = self.state.lock().unwrap().pspec.clone().unwrap().spec;
1808 :
1809 : let tls_config = self.tls_config(&spec);
1810 :
1811 : self.update_installed_extensions_collection_interval(&spec);
1812 :
1813 : if let Some(ref pgbouncer_settings) = spec.pgbouncer_settings {
1814 : info!("tuning pgbouncer");
1815 :
1816 : let pgbouncer_settings = pgbouncer_settings.clone();
1817 : let tls_config = tls_config.clone();
1818 :
1819 : // Spawn a background task to do the tuning,
1820 : // so that we don't block the main thread that starts Postgres.
1821 0 : tokio::spawn(async move {
1822 0 : let res = tune_pgbouncer(pgbouncer_settings, tls_config).await;
1823 0 : if let Err(err) = res {
1824 0 : error!("error while tuning pgbouncer: {err:?}");
1825 0 : }
1826 0 : });
1827 : }
1828 :
1829 : if let Some(ref local_proxy) = spec.local_proxy_config {
1830 : info!("configuring local_proxy");
1831 :
1832 : // Spawn a background task to do the configuration,
1833 : // so that we don't block the main thread that starts Postgres.
1834 : let mut local_proxy = local_proxy.clone();
1835 : local_proxy.tls = tls_config.clone();
1836 0 : tokio::spawn(async move {
1837 0 : if let Err(err) = local_proxy::configure(&local_proxy) {
1838 0 : error!("error while configuring local_proxy: {err:?}");
1839 0 : }
1840 0 : });
1841 : }
1842 :
1843 : // Reconfigure rsyslog for Postgres logs export
1844 : let conf = PostgresLogsRsyslogConfig::new(spec.logs_export_host.as_deref());
1845 : configure_postgres_logs_export(conf)?;
1846 :
1847 : // Write new config
1848 : let pgdata_path = Path::new(&self.params.pgdata);
1849 : config::write_postgres_conf(
1850 : pgdata_path,
1851 : &self.params,
1852 : &spec,
1853 : self.params.internal_http_port,
1854 : tls_config,
1855 : )?;
1856 :
1857 : self.pg_reload_conf()?;
1858 :
1859 : if !spec.skip_pg_catalog_updates {
1860 : let max_concurrent_connections = spec.reconfigure_concurrency;
1861 : // Temporarily reset max_cluster_size in config
1862 : // to avoid the possibility of hitting the limit, while we are reconfiguring:
1863 : // creating new extensions, roles, etc.
1864 0 : config::with_compute_ctl_tmp_override(pgdata_path, "neon.max_cluster_size=-1", || {
1865 0 : self.pg_reload_conf()?;
1866 :
1867 0 : if spec.mode == ComputeMode::Primary {
1868 0 : let conf = self.get_tokio_conn_conf(Some("compute_ctl:reconfigure"));
1869 0 : let conf = Arc::new(conf);
1870 :
1871 0 : let spec = Arc::new(spec.clone());
1872 :
1873 0 : self.apply_spec_sql(spec, conf, max_concurrent_connections)?;
1874 0 : }
1875 :
1876 0 : Ok(())
1877 0 : })?;
1878 : self.pg_reload_conf()?;
1879 : }
1880 :
1881 : let unknown_op = "unknown".to_string();
1882 : let op_id = spec.operation_uuid.as_ref().unwrap_or(&unknown_op);
1883 : info!(
1884 : "finished reconfiguration of compute node for operation {}",
1885 : op_id
1886 : );
1887 :
1888 : Ok(())
1889 : }
1890 :
1891 : #[instrument(skip_all)]
1892 : pub fn configure_as_primary(&self, compute_state: &ComputeState) -> Result<()> {
1893 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
1894 :
1895 : assert!(pspec.spec.mode == ComputeMode::Primary);
1896 : if !pspec.spec.skip_pg_catalog_updates {
1897 : let pgdata_path = Path::new(&self.params.pgdata);
1898 : // temporarily reset max_cluster_size in config
1899 : // to avoid the possibility of hitting the limit, while we are applying config:
1900 : // creating new extensions, roles, etc...
1901 0 : config::with_compute_ctl_tmp_override(pgdata_path, "neon.max_cluster_size=-1", || {
1902 0 : self.pg_reload_conf()?;
1903 :
1904 0 : self.apply_config(compute_state)?;
1905 :
1906 0 : Ok(())
1907 0 : })?;
1908 :
1909 : let postgresql_conf_path = pgdata_path.join("postgresql.conf");
1910 : if config::line_in_file(
1911 : &postgresql_conf_path,
1912 : "neon.disable_logical_replication_subscribers=false",
1913 : )? {
1914 : info!(
1915 : "updated postgresql.conf to set neon.disable_logical_replication_subscribers=false"
1916 : );
1917 : }
1918 : self.pg_reload_conf()?;
1919 : }
1920 : self.post_apply_config()?;
1921 :
1922 : Ok(())
1923 : }
1924 :
1925 0 : pub async fn watch_cert_for_changes(self: Arc<Self>) {
1926 : // update status on cert renewal
1927 0 : if let Some(tls_config) = &self.compute_ctl_config.tls {
1928 0 : let tls_config = tls_config.clone();
1929 :
1930 : // wait until the cert exists.
1931 0 : let mut cert_watch = watch_cert_for_changes(tls_config.cert_path.clone()).await;
1932 :
1933 0 : tokio::task::spawn_blocking(move || {
1934 0 : let handle = tokio::runtime::Handle::current();
1935 : 'cert_update: loop {
1936 : // let postgres/pgbouncer/local_proxy know the new cert/key exists.
1937 : // we need to wait until it's configurable first.
1938 :
1939 0 : let mut state = self.state.lock().unwrap();
1940 : 'status_update: loop {
1941 0 : match state.status {
1942 : // let's update the state to config pending
1943 : ComputeStatus::ConfigurationPending | ComputeStatus::Running => {
1944 0 : state.set_status(
1945 0 : ComputeStatus::ConfigurationPending,
1946 0 : &self.state_changed,
1947 0 : );
1948 0 : break 'status_update;
1949 : }
1950 :
1951 : // exit loop
1952 : ComputeStatus::Failed
1953 : | ComputeStatus::TerminationPendingFast
1954 : | ComputeStatus::TerminationPendingImmediate
1955 0 : | ComputeStatus::Terminated => break 'cert_update,
1956 :
1957 : // wait
1958 : ComputeStatus::Init
1959 : | ComputeStatus::Configuration
1960 0 : | ComputeStatus::Empty => {
1961 0 : state = self.state_changed.wait(state).unwrap();
1962 0 : }
1963 : }
1964 : }
1965 0 : drop(state);
1966 :
1967 : // wait for a new certificate update
1968 0 : if handle.block_on(cert_watch.changed()).is_err() {
1969 0 : break;
1970 0 : }
1971 : }
1972 0 : });
1973 0 : }
1974 0 : }
1975 :
1976 0 : pub fn tls_config(&self, spec: &ComputeSpec) -> &Option<TlsConfig> {
1977 0 : if spec.features.contains(&ComputeFeature::TlsExperimental) {
1978 0 : &self.compute_ctl_config.tls
1979 : } else {
1980 0 : &None::<TlsConfig>
1981 : }
1982 0 : }
1983 :
1984 : /// Update the `last_active` in the shared state, but ensure that it's a more recent one.
1985 0 : pub fn update_last_active(&self, last_active: Option<DateTime<Utc>>) {
1986 0 : let mut state = self.state.lock().unwrap();
1987 : // NB: `Some(<DateTime>)` is always greater than `None`.
1988 0 : if last_active > state.last_active {
1989 0 : state.last_active = last_active;
1990 0 : debug!("set the last compute activity time to: {:?}", last_active);
1991 0 : }
1992 0 : }
1993 :
1994 : // Look for core dumps and collect backtraces.
1995 : //
1996 : // EKS worker nodes have following core dump settings:
1997 : // /proc/sys/kernel/core_pattern -> core
1998 : // /proc/sys/kernel/core_uses_pid -> 1
1999 : // ulimit -c -> unlimited
2000 : // which results in core dumps being written to postgres data directory as core.<pid>.
2001 : //
2002 : // Use that as a default location and pattern, except macos where core dumps are written
2003 : // to /cores/ directory by default.
2004 : //
2005 : // With default Linux settings, the core dump file is called just "core", so check for
2006 : // that too.
2007 0 : pub fn check_for_core_dumps(&self) -> Result<()> {
2008 0 : let core_dump_dir = match std::env::consts::OS {
2009 0 : "macos" => Path::new("/cores/"),
2010 0 : _ => Path::new(&self.params.pgdata),
2011 : };
2012 :
2013 : // Collect core dump paths if any
2014 0 : info!("checking for core dumps in {}", core_dump_dir.display());
2015 0 : let files = fs::read_dir(core_dump_dir)?;
2016 0 : let cores = files.filter_map(|entry| {
2017 0 : let entry = entry.ok()?;
2018 :
2019 0 : let is_core_dump = match entry.file_name().to_str()? {
2020 0 : n if n.starts_with("core.") => true,
2021 0 : "core" => true,
2022 0 : _ => false,
2023 : };
2024 0 : if is_core_dump {
2025 0 : Some(entry.path())
2026 : } else {
2027 0 : None
2028 : }
2029 0 : });
2030 :
2031 : // Print backtrace for each core dump
2032 0 : for core_path in cores {
2033 0 : warn!(
2034 0 : "core dump found: {}, collecting backtrace",
2035 0 : core_path.display()
2036 : );
2037 :
2038 : // Try first with gdb
2039 0 : let backtrace = Command::new("gdb")
2040 0 : .args(["--batch", "-q", "-ex", "bt", &self.params.pgbin])
2041 0 : .arg(&core_path)
2042 0 : .output();
2043 :
2044 : // Try lldb if no gdb is found -- that is handy for local testing on macOS
2045 0 : let backtrace = match backtrace {
2046 0 : Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
2047 0 : warn!("cannot find gdb, trying lldb");
2048 0 : Command::new("lldb")
2049 0 : .arg("-c")
2050 0 : .arg(&core_path)
2051 0 : .args(["--batch", "-o", "bt all", "-o", "quit"])
2052 0 : .output()
2053 : }
2054 0 : _ => backtrace,
2055 0 : }?;
2056 :
2057 0 : warn!(
2058 0 : "core dump backtrace: {}",
2059 0 : String::from_utf8_lossy(&backtrace.stdout)
2060 : );
2061 0 : warn!(
2062 0 : "debugger stderr: {}",
2063 0 : String::from_utf8_lossy(&backtrace.stderr)
2064 : );
2065 : }
2066 :
2067 0 : Ok(())
2068 0 : }
2069 :
2070 : /// Select `pg_stat_statements` data and return it as a stringified JSON
2071 0 : pub async fn collect_insights(&self) -> String {
2072 0 : let mut result_rows: Vec<String> = Vec::new();
2073 0 : let conf = self.get_tokio_conn_conf(Some("compute_ctl:collect_insights"));
2074 0 : let connect_result = conf.connect(NoTls).await;
2075 0 : let (client, connection) = connect_result.unwrap();
2076 0 : tokio::spawn(async move {
2077 0 : if let Err(e) = connection.await {
2078 0 : eprintln!("connection error: {e}");
2079 0 : }
2080 0 : });
2081 0 : let result = client
2082 0 : .simple_query(
2083 0 : "SELECT
2084 0 : row_to_json(pg_stat_statements)
2085 0 : FROM
2086 0 : pg_stat_statements
2087 0 : WHERE
2088 0 : userid != 'cloud_admin'::regrole::oid
2089 0 : ORDER BY
2090 0 : (mean_exec_time + mean_plan_time) DESC
2091 0 : LIMIT 100",
2092 0 : )
2093 0 : .await;
2094 :
2095 0 : if let Ok(raw_rows) = result {
2096 0 : for message in raw_rows.iter() {
2097 0 : if let postgres::SimpleQueryMessage::Row(row) = message {
2098 0 : if let Some(json) = row.get(0) {
2099 0 : result_rows.push(json.to_string());
2100 0 : }
2101 0 : }
2102 : }
2103 :
2104 0 : format!("{{\"pg_stat_statements\": [{}]}}", result_rows.join(","))
2105 : } else {
2106 0 : "{{\"pg_stat_statements\": []}}".to_string()
2107 : }
2108 0 : }
2109 :
2110 : // download an archive, unzip and place files in correct locations
2111 0 : pub async fn download_extension(
2112 0 : &self,
2113 0 : real_ext_name: String,
2114 0 : ext_path: RemotePath,
2115 0 : ) -> Result<u64, DownloadError> {
2116 0 : let remote_ext_base_url =
2117 0 : self.params
2118 0 : .remote_ext_base_url
2119 0 : .as_ref()
2120 0 : .ok_or(DownloadError::BadInput(anyhow::anyhow!(
2121 0 : "Remote extensions storage is not configured",
2122 0 : )))?;
2123 :
2124 0 : let ext_archive_name = ext_path.object_name().expect("bad path");
2125 :
2126 0 : let mut first_try = false;
2127 0 : if !self
2128 0 : .ext_download_progress
2129 0 : .read()
2130 0 : .expect("lock err")
2131 0 : .contains_key(ext_archive_name)
2132 0 : {
2133 0 : self.ext_download_progress
2134 0 : .write()
2135 0 : .expect("lock err")
2136 0 : .insert(ext_archive_name.to_string(), (Utc::now(), false));
2137 0 : first_try = true;
2138 0 : }
2139 0 : let (download_start, download_completed) =
2140 0 : self.ext_download_progress.read().expect("lock err")[ext_archive_name];
2141 0 : let start_time_delta = Utc::now()
2142 0 : .signed_duration_since(download_start)
2143 0 : .to_std()
2144 0 : .unwrap()
2145 0 : .as_millis() as u64;
2146 :
2147 : // how long to wait for extension download if it was started by another process
2148 : const HANG_TIMEOUT: u64 = 3000; // milliseconds
2149 :
2150 0 : if download_completed {
2151 0 : info!("extension already downloaded, skipping re-download");
2152 0 : return Ok(0);
2153 0 : } else if start_time_delta < HANG_TIMEOUT && !first_try {
2154 0 : info!(
2155 0 : "download {ext_archive_name} already started by another process, hanging untill completion or timeout"
2156 : );
2157 0 : let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(500));
2158 : loop {
2159 0 : info!("waiting for download");
2160 0 : interval.tick().await;
2161 0 : let (_, download_completed_now) =
2162 0 : self.ext_download_progress.read().expect("lock")[ext_archive_name];
2163 0 : if download_completed_now {
2164 0 : info!("download finished by whoever else downloaded it");
2165 0 : return Ok(0);
2166 0 : }
2167 : }
2168 : // NOTE: the above loop will get terminated
2169 : // based on the timeout of the download function
2170 0 : }
2171 :
2172 : // if extension hasn't been downloaded before or the previous
2173 : // attempt to download was at least HANG_TIMEOUT ms ago
2174 : // then we try to download it here
2175 0 : info!("downloading new extension {ext_archive_name}");
2176 :
2177 0 : let download_size = extension_server::download_extension(
2178 0 : &real_ext_name,
2179 0 : &ext_path,
2180 0 : remote_ext_base_url,
2181 0 : &self.params.pgbin,
2182 0 : )
2183 0 : .await
2184 0 : .map_err(DownloadError::Other);
2185 :
2186 0 : if download_size.is_ok() {
2187 0 : self.ext_download_progress
2188 0 : .write()
2189 0 : .expect("bad lock")
2190 0 : .insert(ext_archive_name.to_string(), (download_start, true));
2191 0 : }
2192 :
2193 0 : download_size
2194 0 : }
2195 :
2196 0 : pub async fn set_role_grants(
2197 0 : &self,
2198 0 : db_name: &PgIdent,
2199 0 : schema_name: &PgIdent,
2200 0 : privileges: &[Privilege],
2201 0 : role_name: &PgIdent,
2202 0 : ) -> Result<()> {
2203 : use tokio_postgres::NoTls;
2204 :
2205 0 : let mut conf = self.get_tokio_conn_conf(Some("compute_ctl:set_role_grants"));
2206 0 : conf.dbname(db_name);
2207 :
2208 0 : let (db_client, conn) = conf
2209 0 : .connect(NoTls)
2210 0 : .await
2211 0 : .context("Failed to connect to the database")?;
2212 0 : tokio::spawn(conn);
2213 :
2214 : // TODO: support other types of grants apart from schemas?
2215 :
2216 : // check the role grants first - to gracefully handle read-replicas.
2217 0 : let select = "SELECT privilege_type
2218 0 : FROM pg_namespace
2219 0 : JOIN LATERAL (SELECT * FROM aclexplode(nspacl) AS x) acl ON true
2220 0 : JOIN pg_user users ON acl.grantee = users.usesysid
2221 0 : WHERE users.usename = $1
2222 0 : AND nspname = $2";
2223 0 : let rows = db_client
2224 0 : .query(select, &[role_name, schema_name])
2225 0 : .await
2226 0 : .with_context(|| format!("Failed to execute query: {select}"))?;
2227 :
2228 0 : let already_granted: HashSet<String> = rows.into_iter().map(|row| row.get(0)).collect();
2229 :
2230 0 : let grants = privileges
2231 0 : .iter()
2232 0 : .filter(|p| !already_granted.contains(p.as_str()))
2233 : // should not be quoted as it's part of the command.
2234 : // is already sanitized so it's ok
2235 0 : .map(|p| p.as_str())
2236 0 : .join(", ");
2237 :
2238 0 : if !grants.is_empty() {
2239 : // quote the schema and role name as identifiers to sanitize them.
2240 0 : let schema_name = schema_name.pg_quote();
2241 0 : let role_name = role_name.pg_quote();
2242 :
2243 0 : let query = format!("GRANT {grants} ON SCHEMA {schema_name} TO {role_name}",);
2244 0 : db_client
2245 0 : .simple_query(&query)
2246 0 : .await
2247 0 : .with_context(|| format!("Failed to execute query: {query}"))?;
2248 0 : }
2249 :
2250 0 : Ok(())
2251 0 : }
2252 :
2253 0 : pub async fn install_extension(
2254 0 : &self,
2255 0 : ext_name: &PgIdent,
2256 0 : db_name: &PgIdent,
2257 0 : ext_version: ExtVersion,
2258 0 : ) -> Result<ExtVersion> {
2259 : use tokio_postgres::NoTls;
2260 :
2261 0 : let mut conf = self.get_tokio_conn_conf(Some("compute_ctl:install_extension"));
2262 0 : conf.dbname(db_name);
2263 :
2264 0 : let (db_client, conn) = conf
2265 0 : .connect(NoTls)
2266 0 : .await
2267 0 : .context("Failed to connect to the database")?;
2268 0 : tokio::spawn(conn);
2269 :
2270 0 : let version_query = "SELECT extversion FROM pg_extension WHERE extname = $1";
2271 0 : let version: Option<ExtVersion> = db_client
2272 0 : .query_opt(version_query, &[&ext_name])
2273 0 : .await
2274 0 : .with_context(|| format!("Failed to execute query: {version_query}"))?
2275 0 : .map(|row| row.get(0));
2276 :
2277 : // sanitize the inputs as postgres idents.
2278 0 : let ext_name: String = ext_name.pg_quote();
2279 0 : let quoted_version: String = ext_version.pg_quote();
2280 :
2281 0 : if let Some(installed_version) = version {
2282 0 : if installed_version == ext_version {
2283 0 : return Ok(installed_version);
2284 0 : }
2285 0 : let query = format!("ALTER EXTENSION {ext_name} UPDATE TO {quoted_version}");
2286 0 : db_client
2287 0 : .simple_query(&query)
2288 0 : .await
2289 0 : .with_context(|| format!("Failed to execute query: {query}"))?;
2290 : } else {
2291 0 : let query =
2292 0 : format!("CREATE EXTENSION IF NOT EXISTS {ext_name} WITH VERSION {quoted_version}");
2293 0 : db_client
2294 0 : .simple_query(&query)
2295 0 : .await
2296 0 : .with_context(|| format!("Failed to execute query: {query}"))?;
2297 : }
2298 :
2299 0 : Ok(ext_version)
2300 0 : }
2301 :
2302 0 : pub async fn prepare_preload_libraries(
2303 0 : &self,
2304 0 : spec: &ComputeSpec,
2305 0 : ) -> Result<RemoteExtensionMetrics> {
2306 0 : if self.params.remote_ext_base_url.is_none() {
2307 0 : return Ok(RemoteExtensionMetrics {
2308 0 : num_ext_downloaded: 0,
2309 0 : largest_ext_size: 0,
2310 0 : total_ext_download_size: 0,
2311 0 : });
2312 0 : }
2313 0 : let remote_extensions = spec
2314 0 : .remote_extensions
2315 0 : .as_ref()
2316 0 : .ok_or(anyhow::anyhow!("Remote extensions are not configured"))?;
2317 :
2318 0 : info!("parse shared_preload_libraries from spec.cluster.settings");
2319 0 : let mut libs_vec = Vec::new();
2320 0 : if let Some(libs) = spec.cluster.settings.find("shared_preload_libraries") {
2321 0 : libs_vec = libs
2322 0 : .split(&[',', '\'', ' '])
2323 0 : .filter(|s| *s != "neon" && !s.is_empty())
2324 0 : .map(str::to_string)
2325 0 : .collect();
2326 0 : }
2327 0 : info!("parse shared_preload_libraries from provided postgresql.conf");
2328 :
2329 : // that is used in neon_local and python tests
2330 0 : if let Some(conf) = &spec.cluster.postgresql_conf {
2331 0 : let conf_lines = conf.split('\n').collect::<Vec<&str>>();
2332 0 : let mut shared_preload_libraries_line = "";
2333 0 : for line in conf_lines {
2334 0 : if line.starts_with("shared_preload_libraries") {
2335 0 : shared_preload_libraries_line = line;
2336 0 : }
2337 : }
2338 0 : let mut preload_libs_vec = Vec::new();
2339 0 : if let Some(libs) = shared_preload_libraries_line.split("='").nth(1) {
2340 0 : preload_libs_vec = libs
2341 0 : .split(&[',', '\'', ' '])
2342 0 : .filter(|s| *s != "neon" && !s.is_empty())
2343 0 : .map(str::to_string)
2344 0 : .collect();
2345 0 : }
2346 0 : libs_vec.extend(preload_libs_vec);
2347 0 : }
2348 :
2349 : // Don't try to download libraries that are not in the index.
2350 : // Assume that they are already present locally.
2351 0 : libs_vec.retain(|lib| remote_extensions.library_index.contains_key(lib));
2352 :
2353 0 : info!("Downloading to shared preload libraries: {:?}", &libs_vec);
2354 :
2355 0 : let mut download_tasks = Vec::new();
2356 0 : for library in &libs_vec {
2357 0 : let (ext_name, ext_path) =
2358 0 : remote_extensions.get_ext(library, true, &BUILD_TAG, &self.params.pgversion)?;
2359 0 : download_tasks.push(self.download_extension(ext_name, ext_path));
2360 : }
2361 0 : let results = join_all(download_tasks).await;
2362 :
2363 0 : let mut remote_ext_metrics = RemoteExtensionMetrics {
2364 0 : num_ext_downloaded: 0,
2365 0 : largest_ext_size: 0,
2366 0 : total_ext_download_size: 0,
2367 0 : };
2368 0 : for result in results {
2369 0 : let download_size = match result {
2370 0 : Ok(res) => {
2371 0 : remote_ext_metrics.num_ext_downloaded += 1;
2372 0 : res
2373 : }
2374 0 : Err(err) => {
2375 : // if we failed to download an extension, we don't want to fail the whole
2376 : // process, but we do want to log the error
2377 0 : error!("Failed to download extension: {}", err);
2378 0 : 0
2379 : }
2380 : };
2381 :
2382 0 : remote_ext_metrics.largest_ext_size =
2383 0 : std::cmp::max(remote_ext_metrics.largest_ext_size, download_size);
2384 0 : remote_ext_metrics.total_ext_download_size += download_size;
2385 : }
2386 0 : Ok(remote_ext_metrics)
2387 0 : }
2388 :
2389 : /// Waits until current thread receives a state changed notification and
2390 : /// the pageserver connection strings has changed.
2391 : ///
2392 : /// The operation will time out after a specified duration.
2393 0 : pub fn wait_timeout_while_pageserver_connstr_unchanged(&self, duration: Duration) {
2394 0 : let state = self.state.lock().unwrap();
2395 0 : let old_pageserver_connstr = state
2396 0 : .pspec
2397 0 : .as_ref()
2398 0 : .expect("spec must be set")
2399 0 : .pageserver_connstr
2400 0 : .clone();
2401 0 : let mut unchanged = true;
2402 0 : let _ = self
2403 0 : .state_changed
2404 0 : .wait_timeout_while(state, duration, |s| {
2405 0 : let pageserver_connstr = &s
2406 0 : .pspec
2407 0 : .as_ref()
2408 0 : .expect("spec must be set")
2409 0 : .pageserver_connstr;
2410 0 : unchanged = pageserver_connstr == &old_pageserver_connstr;
2411 0 : unchanged
2412 0 : })
2413 0 : .unwrap();
2414 0 : if !unchanged {
2415 0 : info!("Pageserver config changed");
2416 0 : }
2417 0 : }
2418 :
2419 0 : pub fn spawn_extension_stats_task(&self) {
2420 0 : self.terminate_extension_stats_task();
2421 :
2422 0 : let conf = self.tokio_conn_conf.clone();
2423 0 : let atomic_interval = self.params.installed_extensions_collection_interval.clone();
2424 0 : let mut installed_extensions_collection_interval =
2425 0 : 2 * atomic_interval.load(std::sync::atomic::Ordering::SeqCst);
2426 0 : info!(
2427 0 : "[NEON_EXT_SPAWN] Spawning background installed extensions worker with Timeout: {}",
2428 : installed_extensions_collection_interval
2429 : );
2430 0 : let handle = tokio::spawn(async move {
2431 : loop {
2432 0 : info!(
2433 0 : "[NEON_EXT_INT_SLEEP]: Interval: {}",
2434 : installed_extensions_collection_interval
2435 : );
2436 : // Sleep at the start of the loop to ensure that two collections don't happen at the same time.
2437 : // The first collection happens during compute startup.
2438 0 : tokio::time::sleep(tokio::time::Duration::from_secs(
2439 0 : installed_extensions_collection_interval,
2440 0 : ))
2441 0 : .await;
2442 0 : let _ = installed_extensions(conf.clone()).await;
2443 : // Acquire a read lock on the compute spec and then update the interval if necessary
2444 0 : installed_extensions_collection_interval = std::cmp::max(
2445 0 : installed_extensions_collection_interval,
2446 0 : 2 * atomic_interval.load(std::sync::atomic::Ordering::SeqCst),
2447 0 : );
2448 : }
2449 : });
2450 :
2451 : // Store the new task handle
2452 0 : *self.extension_stats_task.lock().unwrap() = Some(handle);
2453 0 : }
2454 :
2455 0 : fn terminate_extension_stats_task(&self) {
2456 0 : if let Some(h) = self.extension_stats_task.lock().unwrap().take() {
2457 0 : h.abort()
2458 0 : }
2459 0 : }
2460 :
2461 0 : pub fn spawn_lfc_offload_task(self: &Arc<Self>, interval: Duration) {
2462 0 : self.terminate_lfc_offload_task();
2463 0 : let secs = interval.as_secs();
2464 0 : let this = self.clone();
2465 :
2466 0 : info!("spawning LFC offload worker with {secs}s interval");
2467 0 : let handle = spawn(async move {
2468 0 : let mut interval = time::interval(interval);
2469 0 : interval.tick().await; // returns immediately
2470 : loop {
2471 0 : interval.tick().await;
2472 :
2473 0 : let prewarm_state = this.state.lock().unwrap().lfc_prewarm_state.clone();
2474 : // Do not offload LFC state if we are currently prewarming or any issue occurred.
2475 : // If we'd do that, we might override the LFC state in endpoint storage with some
2476 : // incomplete state. Imagine a situation:
2477 : // 1. Endpoint started with `autoprewarm: true`
2478 : // 2. While prewarming is not completed, we upload the new incomplete state
2479 : // 3. Compute gets interrupted and restarts
2480 : // 4. We start again and try to prewarm with the state from 2. instead of the previous complete state
2481 0 : if matches!(
2482 0 : prewarm_state,
2483 : LfcPrewarmState::Completed
2484 : | LfcPrewarmState::NotPrewarmed
2485 : | LfcPrewarmState::Skipped
2486 : ) {
2487 0 : this.offload_lfc_async().await;
2488 0 : }
2489 : }
2490 : });
2491 0 : *self.lfc_offload_task.lock().unwrap() = Some(handle);
2492 0 : }
2493 :
2494 0 : fn terminate_lfc_offload_task(&self) {
2495 0 : if let Some(h) = self.lfc_offload_task.lock().unwrap().take() {
2496 0 : h.abort()
2497 0 : }
2498 0 : }
2499 :
2500 0 : fn update_installed_extensions_collection_interval(&self, spec: &ComputeSpec) {
2501 : // Update the interval for collecting installed extensions statistics
2502 : // If the value is -1, we never suspend so set the value to default collection.
2503 : // If the value is 0, it means default, we will just continue to use the default.
2504 0 : if spec.suspend_timeout_seconds == -1 || spec.suspend_timeout_seconds == 0 {
2505 0 : self.params.installed_extensions_collection_interval.store(
2506 0 : DEFAULT_INSTALLED_EXTENSIONS_COLLECTION_INTERVAL,
2507 0 : std::sync::atomic::Ordering::SeqCst,
2508 0 : );
2509 0 : } else {
2510 0 : self.params.installed_extensions_collection_interval.store(
2511 0 : spec.suspend_timeout_seconds as u64,
2512 0 : std::sync::atomic::Ordering::SeqCst,
2513 0 : );
2514 0 : }
2515 0 : }
2516 : }
2517 :
2518 0 : pub async fn installed_extensions(conf: tokio_postgres::Config) -> Result<()> {
2519 0 : let res = get_installed_extensions(conf).await;
2520 0 : match res {
2521 0 : Ok(extensions) => {
2522 0 : info!(
2523 0 : "[NEON_EXT_STAT] {}",
2524 0 : serde_json::to_string(&extensions).expect("failed to serialize extensions list")
2525 : );
2526 : }
2527 0 : Err(err) => error!("could not get installed extensions: {err}"),
2528 : }
2529 0 : Ok(())
2530 0 : }
2531 :
2532 0 : pub fn forward_termination_signal(dev_mode: bool) {
2533 0 : let ss_pid = SYNC_SAFEKEEPERS_PID.load(Ordering::SeqCst);
2534 0 : if ss_pid != 0 {
2535 0 : let ss_pid = nix::unistd::Pid::from_raw(ss_pid as i32);
2536 0 : kill(ss_pid, Signal::SIGTERM).ok();
2537 0 : }
2538 :
2539 0 : if !dev_mode {
2540 : // Terminate pgbouncer with SIGKILL
2541 0 : match pid_file::read(PGBOUNCER_PIDFILE.into()) {
2542 0 : Ok(pid_file::PidFileRead::LockedByOtherProcess(pid)) => {
2543 0 : info!("sending SIGKILL to pgbouncer process pid: {}", pid);
2544 0 : if let Err(e) = kill(pid, Signal::SIGKILL) {
2545 0 : error!("failed to terminate pgbouncer: {}", e);
2546 0 : }
2547 : }
2548 : // pgbouncer does not lock the pid file, so we read and kill the process directly
2549 : Ok(pid_file::PidFileRead::NotHeldByAnyProcess(_)) => {
2550 0 : if let Ok(pid_str) = std::fs::read_to_string(PGBOUNCER_PIDFILE) {
2551 0 : if let Ok(pid) = pid_str.trim().parse::<i32>() {
2552 0 : info!(
2553 0 : "sending SIGKILL to pgbouncer process pid: {} (from unlocked pid file)",
2554 : pid
2555 : );
2556 0 : if let Err(e) = kill(Pid::from_raw(pid), Signal::SIGKILL) {
2557 0 : error!("failed to terminate pgbouncer: {}", e);
2558 0 : }
2559 0 : }
2560 : } else {
2561 0 : info!("pgbouncer pid file exists but process not running");
2562 : }
2563 : }
2564 : Ok(pid_file::PidFileRead::NotExist) => {
2565 0 : info!("pgbouncer pid file not found, process may not be running");
2566 : }
2567 0 : Err(e) => {
2568 0 : error!("error reading pgbouncer pid file: {}", e);
2569 : }
2570 : }
2571 :
2572 : // Terminate local_proxy
2573 0 : match pid_file::read("/etc/local_proxy/pid".into()) {
2574 0 : Ok(pid_file::PidFileRead::LockedByOtherProcess(pid)) => {
2575 0 : info!("sending SIGTERM to local_proxy process pid: {}", pid);
2576 0 : if let Err(e) = kill(pid, Signal::SIGTERM) {
2577 0 : error!("failed to terminate local_proxy: {}", e);
2578 0 : }
2579 : }
2580 : Ok(pid_file::PidFileRead::NotHeldByAnyProcess(_)) => {
2581 0 : info!("local_proxy PID file exists but process not running");
2582 : }
2583 : Ok(pid_file::PidFileRead::NotExist) => {
2584 0 : info!("local_proxy PID file not found, process may not be running");
2585 : }
2586 0 : Err(e) => {
2587 0 : error!("error reading local_proxy PID file: {}", e);
2588 : }
2589 : }
2590 : } else {
2591 0 : info!("Skipping pgbouncer and local_proxy termination because in dev mode");
2592 : }
2593 :
2594 0 : let pg_pid = PG_PID.load(Ordering::SeqCst);
2595 0 : if pg_pid != 0 {
2596 0 : let pg_pid = nix::unistd::Pid::from_raw(pg_pid as i32);
2597 0 : // Use 'fast' shutdown (SIGINT) because it also creates a shutdown checkpoint, which is important for
2598 0 : // ROs to get a list of running xacts faster instead of going through the CLOG.
2599 0 : // See https://www.postgresql.org/docs/current/server-shutdown.html for the list of modes and signals.
2600 0 : kill(pg_pid, Signal::SIGINT).ok();
2601 0 : }
2602 0 : }
2603 :
2604 : // helper trait to call JoinSet::spawn_blocking(f), but propagates the current
2605 : // tracing span to the thread.
2606 : trait JoinSetExt<T> {
2607 : fn spawn_blocking_child<F>(&mut self, f: F) -> tokio::task::AbortHandle
2608 : where
2609 : F: FnOnce() -> T + Send + 'static,
2610 : T: Send;
2611 : }
2612 :
2613 : impl<T: 'static> JoinSetExt<T> for tokio::task::JoinSet<T> {
2614 0 : fn spawn_blocking_child<F>(&mut self, f: F) -> tokio::task::AbortHandle
2615 0 : where
2616 0 : F: FnOnce() -> T + Send + 'static,
2617 0 : T: Send,
2618 : {
2619 0 : let sp = tracing::Span::current();
2620 0 : self.spawn_blocking(move || {
2621 0 : let _e = sp.enter();
2622 0 : f()
2623 0 : })
2624 0 : }
2625 : }
2626 :
2627 : #[cfg(test)]
2628 : mod tests {
2629 : use std::fs::File;
2630 :
2631 : use super::*;
2632 :
2633 : #[test]
2634 1 : fn duplicate_safekeeper_connstring() {
2635 1 : let file = File::open("tests/cluster_spec.json").unwrap();
2636 1 : let spec: ComputeSpec = serde_json::from_reader(file).unwrap();
2637 :
2638 1 : match ParsedSpec::try_from(spec.clone()) {
2639 0 : Ok(_p) => panic!("Failed to detect duplicate entry"),
2640 1 : Err(e) => assert!(e.starts_with("duplicate entry in safekeeper_connstrings:")),
2641 : };
2642 1 : }
2643 : }
|