LCOV - code coverage report
Current view: top level - compute_tools/src - compute.rs (source / functions) Coverage Total Hit
Test: 5713ff31fc16472ab3f92425989ca6addc3dcf9c.info Lines: 5.8 % 1398 81
Test Date: 2025-07-30 16:18:19 Functions: 5.0 % 119 6

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

Generated by: LCOV version 2.1-beta