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