LCOV - code coverage report
Current view: top level - compute_tools/src - compute.rs (source / functions) Coverage Total Hit
Test: 249f165943bd2c492f96a3f7d250276e4addca1a.info Lines: 0.0 % 921 0
Test Date: 2024-11-20 18:39:52 Functions: 0.0 % 97 0

            Line data    Source code
       1              : use std::collections::{HashMap, HashSet};
       2              : use std::env;
       3              : use std::fs;
       4              : use std::iter::once;
       5              : use std::os::unix::fs::{symlink, PermissionsExt};
       6              : use std::path::Path;
       7              : use std::process::{Command, Stdio};
       8              : use std::str::FromStr;
       9              : use std::sync::atomic::AtomicU32;
      10              : use std::sync::atomic::Ordering;
      11              : use std::sync::{Arc, Condvar, Mutex, RwLock};
      12              : use std::thread;
      13              : use std::time::Duration;
      14              : use std::time::Instant;
      15              : 
      16              : use anyhow::{Context, Result};
      17              : use chrono::{DateTime, Utc};
      18              : use compute_api::spec::{PgIdent, Role};
      19              : use futures::future::join_all;
      20              : use futures::stream::FuturesUnordered;
      21              : use futures::StreamExt;
      22              : use nix::unistd::Pid;
      23              : use postgres::error::SqlState;
      24              : use postgres::{Client, NoTls};
      25              : use tracing::{debug, error, info, instrument, warn};
      26              : use utils::id::{TenantId, TimelineId};
      27              : use utils::lsn::Lsn;
      28              : 
      29              : use compute_api::privilege::Privilege;
      30              : use compute_api::responses::{ComputeMetrics, ComputeStatus};
      31              : use compute_api::spec::{ComputeFeature, ComputeMode, ComputeSpec, ExtVersion};
      32              : use utils::measured_stream::MeasuredReader;
      33              : 
      34              : use nix::sys::signal::{kill, Signal};
      35              : use remote_storage::{DownloadError, RemotePath};
      36              : use tokio::spawn;
      37              : use url::Url;
      38              : 
      39              : use crate::installed_extensions::get_installed_extensions_sync;
      40              : use crate::local_proxy;
      41              : use crate::pg_helpers::*;
      42              : use crate::spec::*;
      43              : use crate::spec_apply::ApplySpecPhase::{
      44              :     CreateAndAlterDatabases, CreateAndAlterRoles, CreateAvailabilityCheck, CreateSuperUser,
      45              :     DropInvalidDatabases, DropRoles, HandleNeonExtension, HandleOtherExtensions,
      46              :     RenameAndDeleteDatabases, RenameRoles, RunInEachDatabase,
      47              : };
      48              : use crate::spec_apply::PerDatabasePhase::{
      49              :     ChangeSchemaPerms, DeleteDBRoleReferences, HandleAnonExtension,
      50              : };
      51              : use crate::spec_apply::{apply_operations, MutableApplyContext, DB};
      52              : use crate::sync_sk::{check_if_synced, ping_safekeeper};
      53              : use crate::{config, extension_server};
      54              : 
      55              : pub static SYNC_SAFEKEEPERS_PID: AtomicU32 = AtomicU32::new(0);
      56              : pub static PG_PID: AtomicU32 = AtomicU32::new(0);
      57              : 
      58              : /// Compute node info shared across several `compute_ctl` threads.
      59              : pub struct ComputeNode {
      60              :     // Url type maintains proper escaping
      61              :     pub connstr: url::Url,
      62              :     pub pgdata: String,
      63              :     pub pgbin: String,
      64              :     pub pgversion: String,
      65              :     /// We should only allow live re- / configuration of the compute node if
      66              :     /// it uses 'pull model', i.e. it can go to control-plane and fetch
      67              :     /// the latest configuration. Otherwise, there could be a case:
      68              :     /// - we start compute with some spec provided as argument
      69              :     /// - we push new spec and it does reconfiguration
      70              :     /// - but then something happens and compute pod / VM is destroyed,
      71              :     ///   so k8s controller starts it again with the **old** spec
      72              :     ///
      73              :     /// and the same for empty computes:
      74              :     /// - we started compute without any spec
      75              :     /// - we push spec and it does configuration
      76              :     /// - but then it is restarted without any spec again
      77              :     pub live_config_allowed: bool,
      78              :     /// Volatile part of the `ComputeNode`, which should be used under `Mutex`.
      79              :     /// To allow HTTP API server to serving status requests, while configuration
      80              :     /// is in progress, lock should be held only for short periods of time to do
      81              :     /// read/write, not the whole configuration process.
      82              :     pub state: Mutex<ComputeState>,
      83              :     /// `Condvar` to allow notifying waiters about state changes.
      84              :     pub state_changed: Condvar,
      85              :     /// the address of extension storage proxy gateway
      86              :     pub ext_remote_storage: Option<String>,
      87              :     // key: ext_archive_name, value: started download time, download_completed?
      88              :     pub ext_download_progress: RwLock<HashMap<String, (DateTime<Utc>, bool)>>,
      89              :     pub build_tag: String,
      90              : }
      91              : 
      92              : // store some metrics about download size that might impact startup time
      93              : #[derive(Clone, Debug)]
      94              : pub struct RemoteExtensionMetrics {
      95              :     num_ext_downloaded: u64,
      96              :     largest_ext_size: u64,
      97              :     total_ext_download_size: u64,
      98              : }
      99              : 
     100              : #[derive(Clone, Debug)]
     101              : pub struct ComputeState {
     102              :     pub start_time: DateTime<Utc>,
     103              :     pub status: ComputeStatus,
     104              :     /// Timestamp of the last Postgres activity. It could be `None` if
     105              :     /// compute wasn't used since start.
     106              :     pub last_active: Option<DateTime<Utc>>,
     107              :     pub error: Option<String>,
     108              :     pub pspec: Option<ParsedSpec>,
     109              :     pub metrics: ComputeMetrics,
     110              : }
     111              : 
     112              : impl ComputeState {
     113            0 :     pub fn new() -> Self {
     114            0 :         Self {
     115            0 :             start_time: Utc::now(),
     116            0 :             status: ComputeStatus::Empty,
     117            0 :             last_active: None,
     118            0 :             error: None,
     119            0 :             pspec: None,
     120            0 :             metrics: ComputeMetrics::default(),
     121            0 :         }
     122            0 :     }
     123              : 
     124            0 :     pub fn set_status(&mut self, status: ComputeStatus, state_changed: &Condvar) {
     125            0 :         let prev = self.status;
     126            0 :         info!("Changing compute status from {} to {}", prev, status);
     127            0 :         self.status = status;
     128            0 :         state_changed.notify_all();
     129            0 :     }
     130              : 
     131            0 :     pub fn set_failed_status(&mut self, err: anyhow::Error, state_changed: &Condvar) {
     132            0 :         self.error = Some(format!("{err:?}"));
     133            0 :         self.set_status(ComputeStatus::Failed, state_changed);
     134            0 :     }
     135              : }
     136              : 
     137              : impl Default for ComputeState {
     138            0 :     fn default() -> Self {
     139            0 :         Self::new()
     140            0 :     }
     141              : }
     142              : 
     143              : #[derive(Clone, Debug)]
     144              : pub struct ParsedSpec {
     145              :     pub spec: ComputeSpec,
     146              :     pub tenant_id: TenantId,
     147              :     pub timeline_id: TimelineId,
     148              :     pub pageserver_connstr: String,
     149              :     pub safekeeper_connstrings: Vec<String>,
     150              :     pub storage_auth_token: Option<String>,
     151              : }
     152              : 
     153              : impl TryFrom<ComputeSpec> for ParsedSpec {
     154              :     type Error = String;
     155            0 :     fn try_from(spec: ComputeSpec) -> Result<Self, String> {
     156              :         // Extract the options from the spec file that are needed to connect to
     157              :         // the storage system.
     158              :         //
     159              :         // For backwards-compatibility, the top-level fields in the spec file
     160              :         // may be empty. In that case, we need to dig them from the GUCs in the
     161              :         // cluster.settings field.
     162            0 :         let pageserver_connstr = spec
     163            0 :             .pageserver_connstring
     164            0 :             .clone()
     165            0 :             .or_else(|| spec.cluster.settings.find("neon.pageserver_connstring"))
     166            0 :             .ok_or("pageserver connstr should be provided")?;
     167            0 :         let safekeeper_connstrings = if spec.safekeeper_connstrings.is_empty() {
     168            0 :             if matches!(spec.mode, ComputeMode::Primary) {
     169            0 :                 spec.cluster
     170            0 :                     .settings
     171            0 :                     .find("neon.safekeepers")
     172            0 :                     .ok_or("safekeeper connstrings should be provided")?
     173            0 :                     .split(',')
     174            0 :                     .map(|str| str.to_string())
     175            0 :                     .collect()
     176              :             } else {
     177            0 :                 vec![]
     178              :             }
     179              :         } else {
     180            0 :             spec.safekeeper_connstrings.clone()
     181              :         };
     182            0 :         let storage_auth_token = spec.storage_auth_token.clone();
     183            0 :         let tenant_id: TenantId = if let Some(tenant_id) = spec.tenant_id {
     184            0 :             tenant_id
     185              :         } else {
     186            0 :             spec.cluster
     187            0 :                 .settings
     188            0 :                 .find("neon.tenant_id")
     189            0 :                 .ok_or("tenant id should be provided")
     190            0 :                 .map(|s| TenantId::from_str(&s))?
     191            0 :                 .or(Err("invalid tenant id"))?
     192              :         };
     193            0 :         let timeline_id: TimelineId = if let Some(timeline_id) = spec.timeline_id {
     194            0 :             timeline_id
     195              :         } else {
     196            0 :             spec.cluster
     197            0 :                 .settings
     198            0 :                 .find("neon.timeline_id")
     199            0 :                 .ok_or("timeline id should be provided")
     200            0 :                 .map(|s| TimelineId::from_str(&s))?
     201            0 :                 .or(Err("invalid timeline id"))?
     202              :         };
     203              : 
     204            0 :         Ok(ParsedSpec {
     205            0 :             spec,
     206            0 :             pageserver_connstr,
     207            0 :             safekeeper_connstrings,
     208            0 :             storage_auth_token,
     209            0 :             tenant_id,
     210            0 :             timeline_id,
     211            0 :         })
     212            0 :     }
     213              : }
     214              : 
     215              : /// If we are a VM, returns a [`Command`] that will run in the `neon-postgres`
     216              : /// cgroup. Otherwise returns the default `Command::new(cmd)`
     217              : ///
     218              : /// This function should be used to start postgres, as it will start it in the
     219              : /// neon-postgres cgroup if we are a VM. This allows autoscaling to control
     220              : /// postgres' resource usage. The cgroup will exist in VMs because vm-builder
     221              : /// creates it during the sysinit phase of its inittab.
     222            0 : fn maybe_cgexec(cmd: &str) -> Command {
     223            0 :     // The cplane sets this env var for autoscaling computes.
     224            0 :     // use `var_os` so we don't have to worry about the variable being valid
     225            0 :     // unicode. Should never be an concern . . . but just in case
     226            0 :     if env::var_os("AUTOSCALING").is_some() {
     227            0 :         let mut command = Command::new("cgexec");
     228            0 :         command.args(["-g", "memory:neon-postgres"]);
     229            0 :         command.arg(cmd);
     230            0 :         command
     231              :     } else {
     232            0 :         Command::new(cmd)
     233              :     }
     234            0 : }
     235              : 
     236            0 : pub(crate) fn construct_superuser_query(spec: &ComputeSpec) -> String {
     237            0 :     let roles = spec
     238            0 :         .cluster
     239            0 :         .roles
     240            0 :         .iter()
     241            0 :         .map(|r| escape_literal(&r.name))
     242            0 :         .collect::<Vec<_>>();
     243            0 : 
     244            0 :     let dbs = spec
     245            0 :         .cluster
     246            0 :         .databases
     247            0 :         .iter()
     248            0 :         .map(|db| escape_literal(&db.name))
     249            0 :         .collect::<Vec<_>>();
     250              : 
     251            0 :     let roles_decl = if roles.is_empty() {
     252            0 :         String::from("roles text[] := NULL;")
     253              :     } else {
     254            0 :         format!(
     255            0 :             r#"
     256            0 :                roles text[] := ARRAY(SELECT rolname
     257            0 :                                      FROM pg_catalog.pg_roles
     258            0 :                                      WHERE rolname IN ({}));"#,
     259            0 :             roles.join(", ")
     260            0 :         )
     261              :     };
     262              : 
     263            0 :     let database_decl = if dbs.is_empty() {
     264            0 :         String::from("dbs text[] := NULL;")
     265              :     } else {
     266            0 :         format!(
     267            0 :             r#"
     268            0 :                dbs text[] := ARRAY(SELECT datname
     269            0 :                                    FROM pg_catalog.pg_database
     270            0 :                                    WHERE datname IN ({}));"#,
     271            0 :             dbs.join(", ")
     272            0 :         )
     273              :     };
     274              : 
     275              :     // ALL PRIVILEGES grants CREATE, CONNECT, and TEMPORARY on all databases
     276              :     // (see https://www.postgresql.org/docs/current/ddl-priv.html)
     277            0 :     let query = format!(
     278            0 :         r#"
     279            0 :             DO $$
     280            0 :                 DECLARE
     281            0 :                     r text;
     282            0 :                     {}
     283            0 :                     {}
     284            0 :                 BEGIN
     285            0 :                     IF NOT EXISTS (
     286            0 :                         SELECT FROM pg_catalog.pg_roles WHERE rolname = 'neon_superuser')
     287            0 :                     THEN
     288            0 :                         CREATE ROLE neon_superuser CREATEDB CREATEROLE NOLOGIN REPLICATION BYPASSRLS IN ROLE pg_read_all_data, pg_write_all_data;
     289            0 :                         IF array_length(roles, 1) IS NOT NULL THEN
     290            0 :                             EXECUTE format('GRANT neon_superuser TO %s',
     291            0 :                                            array_to_string(ARRAY(SELECT quote_ident(x) FROM unnest(roles) as x), ', '));
     292            0 :                             FOREACH r IN ARRAY roles LOOP
     293            0 :                                 EXECUTE format('ALTER ROLE %s CREATEROLE CREATEDB', quote_ident(r));
     294            0 :                             END LOOP;
     295            0 :                         END IF;
     296            0 :                         IF array_length(dbs, 1) IS NOT NULL THEN
     297            0 :                             EXECUTE format('GRANT ALL PRIVILEGES ON DATABASE %s TO neon_superuser',
     298            0 :                                            array_to_string(ARRAY(SELECT quote_ident(x) FROM unnest(dbs) as x), ', '));
     299            0 :                         END IF;
     300            0 :                     END IF;
     301            0 :                 END
     302            0 :             $$;"#,
     303            0 :         roles_decl, database_decl,
     304            0 :     );
     305            0 : 
     306            0 :     query
     307            0 : }
     308              : 
     309              : impl ComputeNode {
     310              :     /// Check that compute node has corresponding feature enabled.
     311            0 :     pub fn has_feature(&self, feature: ComputeFeature) -> bool {
     312            0 :         let state = self.state.lock().unwrap();
     313              : 
     314            0 :         if let Some(s) = state.pspec.as_ref() {
     315            0 :             s.spec.features.contains(&feature)
     316              :         } else {
     317            0 :             false
     318              :         }
     319            0 :     }
     320              : 
     321            0 :     pub fn set_status(&self, status: ComputeStatus) {
     322            0 :         let mut state = self.state.lock().unwrap();
     323            0 :         state.set_status(status, &self.state_changed);
     324            0 :     }
     325              : 
     326            0 :     pub fn set_failed_status(&self, err: anyhow::Error) {
     327            0 :         let mut state = self.state.lock().unwrap();
     328            0 :         state.set_failed_status(err, &self.state_changed);
     329            0 :     }
     330              : 
     331            0 :     pub fn get_status(&self) -> ComputeStatus {
     332            0 :         self.state.lock().unwrap().status
     333            0 :     }
     334              : 
     335              :     // Remove `pgdata` directory and create it again with right permissions.
     336            0 :     fn create_pgdata(&self) -> Result<()> {
     337            0 :         // Ignore removal error, likely it is a 'No such file or directory (os error 2)'.
     338            0 :         // If it is something different then create_dir() will error out anyway.
     339            0 :         let _ok = fs::remove_dir_all(&self.pgdata);
     340            0 :         fs::create_dir(&self.pgdata)?;
     341            0 :         fs::set_permissions(&self.pgdata, fs::Permissions::from_mode(0o700))?;
     342              : 
     343            0 :         Ok(())
     344            0 :     }
     345              : 
     346              :     // Get basebackup from the libpq connection to pageserver using `connstr` and
     347              :     // unarchive it to `pgdata` directory overriding all its previous content.
     348            0 :     #[instrument(skip_all, fields(%lsn))]
     349              :     fn try_get_basebackup(&self, compute_state: &ComputeState, lsn: Lsn) -> Result<()> {
     350              :         let spec = compute_state.pspec.as_ref().expect("spec must be set");
     351              :         let start_time = Instant::now();
     352              : 
     353              :         let shard0_connstr = spec.pageserver_connstr.split(',').next().unwrap();
     354              :         let mut config = postgres::Config::from_str(shard0_connstr)?;
     355              : 
     356              :         // Use the storage auth token from the config file, if given.
     357              :         // Note: this overrides any password set in the connection string.
     358              :         if let Some(storage_auth_token) = &spec.storage_auth_token {
     359              :             info!("Got storage auth token from spec file");
     360              :             config.password(storage_auth_token);
     361              :         } else {
     362              :             info!("Storage auth token not set");
     363              :         }
     364              : 
     365              :         // Connect to pageserver
     366              :         let mut client = config.connect(NoTls)?;
     367              :         let pageserver_connect_micros = start_time.elapsed().as_micros() as u64;
     368              : 
     369              :         let basebackup_cmd = match lsn {
     370              :             Lsn(0) => {
     371              :                 if spec.spec.mode != ComputeMode::Primary {
     372              :                     format!(
     373              :                         "basebackup {} {} --gzip --replica",
     374              :                         spec.tenant_id, spec.timeline_id
     375              :                     )
     376              :                 } else {
     377              :                     format!("basebackup {} {} --gzip", spec.tenant_id, spec.timeline_id)
     378              :                 }
     379              :             }
     380              :             _ => {
     381              :                 if spec.spec.mode != ComputeMode::Primary {
     382              :                     format!(
     383              :                         "basebackup {} {} {} --gzip --replica",
     384              :                         spec.tenant_id, spec.timeline_id, lsn
     385              :                     )
     386              :                 } else {
     387              :                     format!(
     388              :                         "basebackup {} {} {} --gzip",
     389              :                         spec.tenant_id, spec.timeline_id, lsn
     390              :                     )
     391              :                 }
     392              :             }
     393              :         };
     394              : 
     395              :         let copyreader = client.copy_out(basebackup_cmd.as_str())?;
     396              :         let mut measured_reader = MeasuredReader::new(copyreader);
     397              :         let mut bufreader = std::io::BufReader::new(&mut measured_reader);
     398              : 
     399              :         // Read the archive directly from the `CopyOutReader`
     400              :         //
     401              :         // Set `ignore_zeros` so that unpack() reads all the Copy data and
     402              :         // doesn't stop at the end-of-archive marker. Otherwise, if the server
     403              :         // sends an Error after finishing the tarball, we will not notice it.
     404              :         let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&mut bufreader));
     405              :         ar.set_ignore_zeros(true);
     406              :         ar.unpack(&self.pgdata)?;
     407              : 
     408              :         // Report metrics
     409              :         let mut state = self.state.lock().unwrap();
     410              :         state.metrics.pageserver_connect_micros = pageserver_connect_micros;
     411              :         state.metrics.basebackup_bytes = measured_reader.get_byte_count() as u64;
     412              :         state.metrics.basebackup_ms = start_time.elapsed().as_millis() as u64;
     413              :         Ok(())
     414              :     }
     415              : 
     416              :     // Gets the basebackup in a retry loop
     417            0 :     #[instrument(skip_all, fields(%lsn))]
     418              :     pub fn get_basebackup(&self, compute_state: &ComputeState, lsn: Lsn) -> Result<()> {
     419              :         let mut retry_period_ms = 500.0;
     420              :         let mut attempts = 0;
     421              :         const DEFAULT_ATTEMPTS: u16 = 10;
     422              :         #[cfg(feature = "testing")]
     423              :         let max_attempts = if let Ok(v) = env::var("NEON_COMPUTE_TESTING_BASEBACKUP_RETRIES") {
     424              :             u16::from_str(&v).unwrap()
     425              :         } else {
     426              :             DEFAULT_ATTEMPTS
     427              :         };
     428              :         #[cfg(not(feature = "testing"))]
     429              :         let max_attempts = DEFAULT_ATTEMPTS;
     430              :         loop {
     431              :             let result = self.try_get_basebackup(compute_state, lsn);
     432              :             match result {
     433              :                 Ok(_) => {
     434              :                     return result;
     435              :                 }
     436              :                 Err(ref e) if attempts < max_attempts => {
     437              :                     warn!(
     438              :                         "Failed to get basebackup: {} (attempt {}/{})",
     439              :                         e, attempts, max_attempts
     440              :                     );
     441              :                     std::thread::sleep(std::time::Duration::from_millis(retry_period_ms as u64));
     442              :                     retry_period_ms *= 1.5;
     443              :                 }
     444              :                 Err(_) => {
     445              :                     return result;
     446              :                 }
     447              :             }
     448              :             attempts += 1;
     449              :         }
     450              :     }
     451              : 
     452            0 :     pub async fn check_safekeepers_synced_async(
     453            0 :         &self,
     454            0 :         compute_state: &ComputeState,
     455            0 :     ) -> Result<Option<Lsn>> {
     456            0 :         // Construct a connection config for each safekeeper
     457            0 :         let pspec: ParsedSpec = compute_state
     458            0 :             .pspec
     459            0 :             .as_ref()
     460            0 :             .expect("spec must be set")
     461            0 :             .clone();
     462            0 :         let sk_connstrs: Vec<String> = pspec.safekeeper_connstrings.clone();
     463            0 :         let sk_configs = sk_connstrs.into_iter().map(|connstr| {
     464            0 :             // Format connstr
     465            0 :             let id = connstr.clone();
     466            0 :             let connstr = format!("postgresql://no_user@{}", connstr);
     467            0 :             let options = format!(
     468            0 :                 "-c timeline_id={} tenant_id={}",
     469            0 :                 pspec.timeline_id, pspec.tenant_id
     470            0 :             );
     471            0 : 
     472            0 :             // Construct client
     473            0 :             let mut config = tokio_postgres::Config::from_str(&connstr).unwrap();
     474            0 :             config.options(&options);
     475            0 :             if let Some(storage_auth_token) = pspec.storage_auth_token.clone() {
     476            0 :                 config.password(storage_auth_token);
     477            0 :             }
     478              : 
     479            0 :             (id, config)
     480            0 :         });
     481            0 : 
     482            0 :         // Create task set to query all safekeepers
     483            0 :         let mut tasks = FuturesUnordered::new();
     484            0 :         let quorum = sk_configs.len() / 2 + 1;
     485            0 :         for (id, config) in sk_configs {
     486            0 :             let timeout = tokio::time::Duration::from_millis(100);
     487            0 :             let task = tokio::time::timeout(timeout, ping_safekeeper(id, config));
     488            0 :             tasks.push(tokio::spawn(task));
     489            0 :         }
     490              : 
     491              :         // Get a quorum of responses or errors
     492            0 :         let mut responses = Vec::new();
     493            0 :         let mut join_errors = Vec::new();
     494            0 :         let mut task_errors = Vec::new();
     495            0 :         let mut timeout_errors = Vec::new();
     496            0 :         while let Some(response) = tasks.next().await {
     497            0 :             match response {
     498            0 :                 Ok(Ok(Ok(r))) => responses.push(r),
     499            0 :                 Ok(Ok(Err(e))) => task_errors.push(e),
     500            0 :                 Ok(Err(e)) => timeout_errors.push(e),
     501            0 :                 Err(e) => join_errors.push(e),
     502              :             };
     503            0 :             if responses.len() >= quorum {
     504            0 :                 break;
     505            0 :             }
     506            0 :             if join_errors.len() + task_errors.len() + timeout_errors.len() >= quorum {
     507            0 :                 break;
     508            0 :             }
     509              :         }
     510              : 
     511              :         // In case of error, log and fail the check, but don't crash.
     512              :         // We're playing it safe because these errors could be transient
     513              :         // and we don't yet retry. Also being careful here allows us to
     514              :         // be backwards compatible with safekeepers that don't have the
     515              :         // TIMELINE_STATUS API yet.
     516            0 :         if responses.len() < quorum {
     517            0 :             error!(
     518            0 :                 "failed sync safekeepers check {:?} {:?} {:?}",
     519              :                 join_errors, task_errors, timeout_errors
     520              :             );
     521            0 :             return Ok(None);
     522            0 :         }
     523            0 : 
     524            0 :         Ok(check_if_synced(responses))
     525            0 :     }
     526              : 
     527              :     // Fast path for sync_safekeepers. If they're already synced we get the lsn
     528              :     // in one roundtrip. If not, we should do a full sync_safekeepers.
     529            0 :     pub fn check_safekeepers_synced(&self, compute_state: &ComputeState) -> Result<Option<Lsn>> {
     530            0 :         let start_time = Utc::now();
     531            0 : 
     532            0 :         // Run actual work with new tokio runtime
     533            0 :         let rt = tokio::runtime::Builder::new_current_thread()
     534            0 :             .enable_all()
     535            0 :             .build()
     536            0 :             .expect("failed to create rt");
     537            0 :         let result = rt.block_on(self.check_safekeepers_synced_async(compute_state));
     538            0 : 
     539            0 :         // Record runtime
     540            0 :         self.state.lock().unwrap().metrics.sync_sk_check_ms = Utc::now()
     541            0 :             .signed_duration_since(start_time)
     542            0 :             .to_std()
     543            0 :             .unwrap()
     544            0 :             .as_millis() as u64;
     545            0 :         result
     546            0 :     }
     547              : 
     548              :     // Run `postgres` in a special mode with `--sync-safekeepers` argument
     549              :     // and return the reported LSN back to the caller.
     550            0 :     #[instrument(skip_all)]
     551              :     pub fn sync_safekeepers(&self, storage_auth_token: Option<String>) -> Result<Lsn> {
     552              :         let start_time = Utc::now();
     553              : 
     554              :         let mut sync_handle = maybe_cgexec(&self.pgbin)
     555              :             .args(["--sync-safekeepers"])
     556              :             .env("PGDATA", &self.pgdata) // we cannot use -D in this mode
     557              :             .envs(if let Some(storage_auth_token) = &storage_auth_token {
     558              :                 vec![("NEON_AUTH_TOKEN", storage_auth_token)]
     559              :             } else {
     560              :                 vec![]
     561              :             })
     562              :             .stdout(Stdio::piped())
     563              :             .stderr(Stdio::piped())
     564              :             .spawn()
     565              :             .expect("postgres --sync-safekeepers failed to start");
     566              :         SYNC_SAFEKEEPERS_PID.store(sync_handle.id(), Ordering::SeqCst);
     567              : 
     568              :         // `postgres --sync-safekeepers` will print all log output to stderr and
     569              :         // final LSN to stdout. So we leave stdout to collect LSN, while stderr logs
     570              :         // will be collected in a child thread.
     571              :         let stderr = sync_handle
     572              :             .stderr
     573              :             .take()
     574              :             .expect("stderr should be captured");
     575              :         let logs_handle = handle_postgres_logs(stderr);
     576              : 
     577              :         let sync_output = sync_handle
     578              :             .wait_with_output()
     579              :             .expect("postgres --sync-safekeepers failed");
     580              :         SYNC_SAFEKEEPERS_PID.store(0, Ordering::SeqCst);
     581              : 
     582              :         // Process has exited, so we can join the logs thread.
     583              :         let _ = logs_handle
     584              :             .join()
     585            0 :             .map_err(|e| tracing::error!("log thread panicked: {:?}", e));
     586              : 
     587              :         if !sync_output.status.success() {
     588              :             anyhow::bail!(
     589              :                 "postgres --sync-safekeepers exited with non-zero status: {}. stdout: {}",
     590              :                 sync_output.status,
     591              :                 String::from_utf8(sync_output.stdout)
     592              :                     .expect("postgres --sync-safekeepers exited, and stdout is not utf-8"),
     593              :             );
     594              :         }
     595              : 
     596              :         self.state.lock().unwrap().metrics.sync_safekeepers_ms = Utc::now()
     597              :             .signed_duration_since(start_time)
     598              :             .to_std()
     599              :             .unwrap()
     600              :             .as_millis() as u64;
     601              : 
     602              :         let lsn = Lsn::from_str(String::from_utf8(sync_output.stdout)?.trim())?;
     603              : 
     604              :         Ok(lsn)
     605              :     }
     606              : 
     607              :     /// Do all the preparations like PGDATA directory creation, configuration,
     608              :     /// safekeepers sync, basebackup, etc.
     609            0 :     #[instrument(skip_all)]
     610              :     pub fn prepare_pgdata(
     611              :         &self,
     612              :         compute_state: &ComputeState,
     613              :         extension_server_port: u16,
     614              :     ) -> Result<()> {
     615              :         let pspec = compute_state.pspec.as_ref().expect("spec must be set");
     616              :         let spec = &pspec.spec;
     617              :         let pgdata_path = Path::new(&self.pgdata);
     618              : 
     619              :         // Remove/create an empty pgdata directory and put configuration there.
     620              :         self.create_pgdata()?;
     621              :         config::write_postgres_conf(
     622              :             &pgdata_path.join("postgresql.conf"),
     623              :             &pspec.spec,
     624              :             Some(extension_server_port),
     625              :         )?;
     626              : 
     627              :         // Syncing safekeepers is only safe with primary nodes: if a primary
     628              :         // is already connected it will be kicked out, so a secondary (standby)
     629              :         // cannot sync safekeepers.
     630              :         let lsn = match spec.mode {
     631              :             ComputeMode::Primary => {
     632              :                 info!("checking if safekeepers are synced");
     633              :                 let lsn = if let Ok(Some(lsn)) = self.check_safekeepers_synced(compute_state) {
     634              :                     lsn
     635              :                 } else {
     636              :                     info!("starting safekeepers syncing");
     637              :                     self.sync_safekeepers(pspec.storage_auth_token.clone())
     638            0 :                         .with_context(|| "failed to sync safekeepers")?
     639              :                 };
     640              :                 info!("safekeepers synced at LSN {}", lsn);
     641              :                 lsn
     642              :             }
     643              :             ComputeMode::Static(lsn) => {
     644              :                 info!("Starting read-only node at static LSN {}", lsn);
     645              :                 lsn
     646              :             }
     647              :             ComputeMode::Replica => {
     648              :                 info!("Initializing standby from latest Pageserver LSN");
     649              :                 Lsn(0)
     650              :             }
     651              :         };
     652              : 
     653              :         info!(
     654              :             "getting basebackup@{} from pageserver {}",
     655              :             lsn, &pspec.pageserver_connstr
     656              :         );
     657            0 :         self.get_basebackup(compute_state, lsn).with_context(|| {
     658            0 :             format!(
     659            0 :                 "failed to get basebackup@{} from pageserver {}",
     660            0 :                 lsn, &pspec.pageserver_connstr
     661            0 :             )
     662            0 :         })?;
     663              : 
     664              :         // Update pg_hba.conf received with basebackup.
     665              :         update_pg_hba(pgdata_path)?;
     666              : 
     667              :         // Place pg_dynshmem under /dev/shm. This allows us to use
     668              :         // 'dynamic_shared_memory_type = mmap' so that the files are placed in
     669              :         // /dev/shm, similar to how 'dynamic_shared_memory_type = posix' works.
     670              :         //
     671              :         // Why on earth don't we just stick to the 'posix' default, you might
     672              :         // ask.  It turns out that making large allocations with 'posix' doesn't
     673              :         // work very well with autoscaling. The behavior we want is that:
     674              :         //
     675              :         // 1. You can make large DSM allocations, larger than the current RAM
     676              :         //    size of the VM, without errors
     677              :         //
     678              :         // 2. If the allocated memory is really used, the VM is scaled up
     679              :         //    automatically to accommodate that
     680              :         //
     681              :         // We try to make that possible by having swap in the VM. But with the
     682              :         // default 'posix' DSM implementation, we fail step 1, even when there's
     683              :         // plenty of swap available. PostgreSQL uses posix_fallocate() to create
     684              :         // the shmem segment, which is really just a file in /dev/shm in Linux,
     685              :         // but posix_fallocate() on tmpfs returns ENOMEM if the size is larger
     686              :         // than available RAM.
     687              :         //
     688              :         // Using 'dynamic_shared_memory_type = mmap' works around that, because
     689              :         // the Postgres 'mmap' DSM implementation doesn't use
     690              :         // posix_fallocate(). Instead, it uses repeated calls to write(2) to
     691              :         // fill the file with zeros. It's weird that that differs between
     692              :         // 'posix' and 'mmap', but we take advantage of it. When the file is
     693              :         // filled slowly with write(2), the kernel allows it to grow larger, as
     694              :         // long as there's swap available.
     695              :         //
     696              :         // In short, using 'dynamic_shared_memory_type = mmap' allows us one DSM
     697              :         // segment to be larger than currently available RAM. But because we
     698              :         // don't want to store it on a real file, which the kernel would try to
     699              :         // flush to disk, so symlink pg_dynshm to /dev/shm.
     700              :         //
     701              :         // We don't set 'dynamic_shared_memory_type = mmap' here, we let the
     702              :         // control plane control that option. If 'mmap' is not used, this
     703              :         // symlink doesn't affect anything.
     704              :         //
     705              :         // See https://github.com/neondatabase/autoscaling/issues/800
     706              :         std::fs::remove_dir(pgdata_path.join("pg_dynshmem"))?;
     707              :         symlink("/dev/shm/", pgdata_path.join("pg_dynshmem"))?;
     708              : 
     709              :         match spec.mode {
     710              :             ComputeMode::Primary => {}
     711              :             ComputeMode::Replica | ComputeMode::Static(..) => {
     712              :                 add_standby_signal(pgdata_path)?;
     713              :             }
     714              :         }
     715              : 
     716              :         Ok(())
     717              :     }
     718              : 
     719              :     /// Start and stop a postgres process to warm up the VM for startup.
     720            0 :     pub fn prewarm_postgres(&self) -> Result<()> {
     721            0 :         info!("prewarming");
     722              : 
     723              :         // Create pgdata
     724            0 :         let pgdata = &format!("{}.warmup", self.pgdata);
     725            0 :         create_pgdata(pgdata)?;
     726              : 
     727              :         // Run initdb to completion
     728            0 :         info!("running initdb");
     729            0 :         let initdb_bin = Path::new(&self.pgbin).parent().unwrap().join("initdb");
     730            0 :         Command::new(initdb_bin)
     731            0 :             .args(["--pgdata", pgdata])
     732            0 :             .output()
     733            0 :             .expect("cannot start initdb process");
     734              : 
     735              :         // Write conf
     736              :         use std::io::Write;
     737            0 :         let conf_path = Path::new(pgdata).join("postgresql.conf");
     738            0 :         let mut file = std::fs::File::create(conf_path)?;
     739            0 :         writeln!(file, "shared_buffers=65536")?;
     740            0 :         writeln!(file, "port=51055")?; // Nobody should be connecting
     741            0 :         writeln!(file, "shared_preload_libraries = 'neon'")?;
     742              : 
     743              :         // Start postgres
     744            0 :         info!("starting postgres");
     745            0 :         let mut pg = maybe_cgexec(&self.pgbin)
     746            0 :             .args(["-D", pgdata])
     747            0 :             .spawn()
     748            0 :             .expect("cannot start postgres process");
     749            0 : 
     750            0 :         // Stop it when it's ready
     751            0 :         info!("waiting for postgres");
     752            0 :         wait_for_postgres(&mut pg, Path::new(pgdata))?;
     753              :         // SIGQUIT orders postgres to exit immediately. We don't want to SIGKILL
     754              :         // it to avoid orphaned processes prowling around while datadir is
     755              :         // wiped.
     756            0 :         let pm_pid = Pid::from_raw(pg.id() as i32);
     757            0 :         kill(pm_pid, Signal::SIGQUIT)?;
     758            0 :         info!("sent SIGQUIT signal");
     759            0 :         pg.wait()?;
     760            0 :         info!("done prewarming");
     761              : 
     762              :         // clean up
     763            0 :         let _ok = fs::remove_dir_all(pgdata);
     764            0 :         Ok(())
     765            0 :     }
     766              : 
     767              :     /// Start Postgres as a child process and manage DBs/roles.
     768              :     /// After that this will hang waiting on the postmaster process to exit.
     769              :     /// Returns a handle to the child process and a handle to the logs thread.
     770            0 :     #[instrument(skip_all)]
     771              :     pub fn start_postgres(
     772              :         &self,
     773              :         storage_auth_token: Option<String>,
     774              :     ) -> Result<(std::process::Child, std::thread::JoinHandle<()>)> {
     775              :         let pgdata_path = Path::new(&self.pgdata);
     776              : 
     777              :         // Run postgres as a child process.
     778              :         let mut pg = maybe_cgexec(&self.pgbin)
     779              :             .args(["-D", &self.pgdata])
     780              :             .envs(if let Some(storage_auth_token) = &storage_auth_token {
     781              :                 vec![("NEON_AUTH_TOKEN", storage_auth_token)]
     782              :             } else {
     783              :                 vec![]
     784              :             })
     785              :             .stderr(Stdio::piped())
     786              :             .spawn()
     787              :             .expect("cannot start postgres process");
     788              :         PG_PID.store(pg.id(), Ordering::SeqCst);
     789              : 
     790              :         // Start a thread to collect logs from stderr.
     791              :         let stderr = pg.stderr.take().expect("stderr should be captured");
     792              :         let logs_handle = handle_postgres_logs(stderr);
     793              : 
     794              :         wait_for_postgres(&mut pg, pgdata_path)?;
     795              : 
     796              :         Ok((pg, logs_handle))
     797              :     }
     798              : 
     799              :     /// Do post configuration of the already started Postgres. This function spawns a background thread to
     800              :     /// configure the database after applying the compute spec. Currently, it upgrades the neon extension
     801              :     /// version. In the future, it may upgrade all 3rd-party extensions.
     802            0 :     #[instrument(skip_all)]
     803              :     pub fn post_apply_config(&self) -> Result<()> {
     804              :         let connstr = self.connstr.clone();
     805            0 :         thread::spawn(move || {
     806            0 :             let func = || {
     807            0 :                 let mut client = Client::connect(connstr.as_str(), NoTls)?;
     808            0 :                 handle_neon_extension_upgrade(&mut client)
     809            0 :                     .context("handle_neon_extension_upgrade")?;
     810            0 :                 Ok::<_, anyhow::Error>(())
     811            0 :             };
     812            0 :             if let Err(err) = func() {
     813            0 :                 error!("error while post_apply_config: {err:#}");
     814            0 :             }
     815            0 :         });
     816              :         Ok(())
     817              :     }
     818              : 
     819            0 :     async fn get_maintenance_client(url: &Url) -> Result<tokio_postgres::Client> {
     820            0 :         let mut connstr = url.clone();
     821            0 : 
     822            0 :         connstr
     823            0 :             .query_pairs_mut()
     824            0 :             .append_pair("application_name", "apply_config");
     825              : 
     826            0 :         let (client, conn) = match tokio_postgres::connect(connstr.as_str(), NoTls).await {
     827            0 :             Err(e) => match e.code() {
     828              :                 Some(&SqlState::INVALID_PASSWORD)
     829              :                 | Some(&SqlState::INVALID_AUTHORIZATION_SPECIFICATION) => {
     830              :                     // connect with zenith_admin if cloud_admin could not authenticate
     831            0 :                     info!(
     832            0 :                         "cannot connect to postgres: {}, retrying with `zenith_admin` username",
     833              :                         e
     834              :                     );
     835            0 :                     let mut zenith_admin_connstr = connstr.clone();
     836            0 : 
     837            0 :                     zenith_admin_connstr
     838            0 :                         .set_username("zenith_admin")
     839            0 :                         .map_err(|_| anyhow::anyhow!("invalid connstr"))?;
     840              : 
     841            0 :                     let mut client =
     842            0 :                         Client::connect(zenith_admin_connstr.as_str(), NoTls)
     843            0 :                             .context("broken cloud_admin credential: tried connecting with cloud_admin but could not authenticate, and zenith_admin does not work either")?;
     844              : 
     845              :                     // Disable forwarding so that users don't get a cloud_admin role
     846            0 :                     let mut func = || {
     847            0 :                         client.simple_query("SET neon.forward_ddl = false")?;
     848            0 :                         client.simple_query("CREATE USER cloud_admin WITH SUPERUSER")?;
     849            0 :                         client.simple_query("GRANT zenith_admin TO cloud_admin")?;
     850            0 :                         Ok::<_, anyhow::Error>(())
     851            0 :                     };
     852            0 :                     func().context("apply_config setup cloud_admin")?;
     853              : 
     854            0 :                     drop(client);
     855            0 : 
     856            0 :                     // reconnect with connstring with expected name
     857            0 :                     tokio_postgres::connect(connstr.as_str(), NoTls).await?
     858              :                 }
     859            0 :                 _ => return Err(e.into()),
     860              :             },
     861            0 :             Ok((client, conn)) => (client, conn),
     862              :         };
     863              : 
     864            0 :         spawn(async move {
     865            0 :             if let Err(e) = conn.await {
     866            0 :                 error!("maintenance client connection error: {}", e);
     867            0 :             }
     868            0 :         });
     869            0 : 
     870            0 :         // Disable DDL forwarding because control plane already knows about the roles/databases
     871            0 :         // we're about to modify.
     872            0 :         client
     873            0 :             .simple_query("SET neon.forward_ddl = false")
     874            0 :             .await
     875            0 :             .context("apply_config SET neon.forward_ddl = false")?;
     876              : 
     877            0 :         Ok(client)
     878            0 :     }
     879              : 
     880              :     /// Apply the spec to the running PostgreSQL instance.
     881              :     /// The caller can decide to run with multiple clients in parallel, or
     882              :     /// single mode.  Either way, the commands executed will be the same, and
     883              :     /// only commands run in different databases are parallelized.
     884            0 :     #[instrument(skip_all)]
     885              :     pub fn apply_spec_sql(
     886              :         &self,
     887              :         spec: Arc<ComputeSpec>,
     888              :         url: Arc<Url>,
     889              :         concurrency: usize,
     890              :     ) -> Result<()> {
     891              :         let rt = tokio::runtime::Builder::new_multi_thread()
     892              :             .enable_all()
     893              :             .build()?;
     894              : 
     895              :         info!("Applying config with max {} concurrency", concurrency);
     896              :         debug!("Config: {:?}", spec);
     897              : 
     898            0 :         rt.block_on(async {
     899              :             // Proceed with post-startup configuration. Note, that order of operations is important.
     900            0 :             let client = Self::get_maintenance_client(&url).await?;
     901            0 :             let spec = spec.clone();
     902              : 
     903            0 :             let databases = get_existing_dbs_async(&client).await?;
     904            0 :             let roles = get_existing_roles_async(&client)
     905            0 :                 .await?
     906            0 :                 .into_iter()
     907            0 :                 .map(|role| (role.name.clone(), role))
     908            0 :                 .collect::<HashMap<String, Role>>();
     909            0 : 
     910            0 :             let jwks_roles = Arc::new(
     911            0 :                 spec.as_ref()
     912            0 :                     .local_proxy_config
     913            0 :                     .iter()
     914            0 :                     .flat_map(|it| &it.jwks)
     915            0 :                     .flatten()
     916            0 :                     .flat_map(|setting| &setting.role_names)
     917            0 :                     .cloned()
     918            0 :                     .collect::<HashSet<_>>(),
     919            0 :             );
     920            0 : 
     921            0 :             let ctx = Arc::new(tokio::sync::RwLock::new(MutableApplyContext {
     922            0 :                 roles,
     923            0 :                 dbs: databases,
     924            0 :             }));
     925              : 
     926            0 :             for phase in [
     927            0 :                 CreateSuperUser,
     928            0 :                 DropInvalidDatabases,
     929            0 :                 RenameRoles,
     930            0 :                 CreateAndAlterRoles,
     931            0 :                 RenameAndDeleteDatabases,
     932            0 :                 CreateAndAlterDatabases,
     933              :             ] {
     934            0 :                 debug!("Applying phase {:?}", &phase);
     935            0 :                 apply_operations(
     936            0 :                     spec.clone(),
     937            0 :                     ctx.clone(),
     938            0 :                     jwks_roles.clone(),
     939            0 :                     phase,
     940            0 :                     || async { Ok(&client) },
     941            0 :                 )
     942            0 :                 .await?;
     943              :             }
     944              : 
     945            0 :             let concurrency_token = Arc::new(tokio::sync::Semaphore::new(concurrency));
     946            0 : 
     947            0 :             let db_processes = spec
     948            0 :                 .cluster
     949            0 :                 .databases
     950            0 :                 .iter()
     951            0 :                 .map(|db| DB::new(db.clone()))
     952            0 :                 // include
     953            0 :                 .chain(once(DB::SystemDB))
     954            0 :                 .map(|db| {
     955            0 :                     let spec = spec.clone();
     956            0 :                     let ctx = ctx.clone();
     957            0 :                     let jwks_roles = jwks_roles.clone();
     958            0 :                     let mut url = url.as_ref().clone();
     959            0 :                     let concurrency_token = concurrency_token.clone();
     960            0 :                     let db = db.clone();
     961            0 : 
     962            0 :                     debug!("Applying per-database phases for Database {:?}", &db);
     963              : 
     964            0 :                     match &db {
     965            0 :                         DB::SystemDB => {}
     966            0 :                         DB::UserDB(db) => {
     967            0 :                             url.set_path(db.name.as_str());
     968            0 :                         }
     969              :                     }
     970              : 
     971            0 :                     let url = Arc::new(url);
     972            0 :                     let fut = Self::apply_spec_sql_db(
     973            0 :                         spec.clone(),
     974            0 :                         url,
     975            0 :                         ctx.clone(),
     976            0 :                         jwks_roles.clone(),
     977            0 :                         concurrency_token.clone(),
     978            0 :                         db,
     979            0 :                     );
     980            0 : 
     981            0 :                     Ok(spawn(fut))
     982            0 :                 })
     983            0 :                 .collect::<Vec<Result<_, anyhow::Error>>>();
     984              : 
     985            0 :             for process in db_processes.into_iter() {
     986            0 :                 let handle = process?;
     987            0 :                 handle.await??;
     988              :             }
     989              : 
     990            0 :             for phase in vec![
     991            0 :                 HandleOtherExtensions,
     992            0 :                 HandleNeonExtension,
     993            0 :                 CreateAvailabilityCheck,
     994            0 :                 DropRoles,
     995            0 :             ] {
     996            0 :                 debug!("Applying phase {:?}", &phase);
     997            0 :                 apply_operations(
     998            0 :                     spec.clone(),
     999            0 :                     ctx.clone(),
    1000            0 :                     jwks_roles.clone(),
    1001            0 :                     phase,
    1002            0 :                     || async { Ok(&client) },
    1003            0 :                 )
    1004            0 :                 .await?;
    1005              :             }
    1006              : 
    1007            0 :             Ok::<(), anyhow::Error>(())
    1008            0 :         })?;
    1009              : 
    1010              :         Ok(())
    1011              :     }
    1012              : 
    1013              :     /// Apply SQL migrations of the RunInEachDatabase phase.
    1014              :     ///
    1015              :     /// May opt to not connect to databases that don't have any scheduled
    1016              :     /// operations.  The function is concurrency-controlled with the provided
    1017              :     /// semaphore.  The caller has to make sure the semaphore isn't exhausted.
    1018            0 :     async fn apply_spec_sql_db(
    1019            0 :         spec: Arc<ComputeSpec>,
    1020            0 :         url: Arc<Url>,
    1021            0 :         ctx: Arc<tokio::sync::RwLock<MutableApplyContext>>,
    1022            0 :         jwks_roles: Arc<HashSet<String>>,
    1023            0 :         concurrency_token: Arc<tokio::sync::Semaphore>,
    1024            0 :         db: DB,
    1025            0 :     ) -> Result<()> {
    1026            0 :         let _permit = concurrency_token.acquire().await?;
    1027              : 
    1028            0 :         let mut client_conn = None;
    1029              : 
    1030            0 :         for subphase in [
    1031            0 :             DeleteDBRoleReferences,
    1032            0 :             ChangeSchemaPerms,
    1033            0 :             HandleAnonExtension,
    1034              :         ] {
    1035            0 :             apply_operations(
    1036            0 :                 spec.clone(),
    1037            0 :                 ctx.clone(),
    1038            0 :                 jwks_roles.clone(),
    1039            0 :                 RunInEachDatabase {
    1040            0 :                     db: db.clone(),
    1041            0 :                     subphase,
    1042            0 :                 },
    1043            0 :                 // Only connect if apply_operation actually wants a connection.
    1044            0 :                 // It's quite possible this database doesn't need any queries,
    1045            0 :                 // so by not connecting we save time and effort connecting to
    1046            0 :                 // that database.
    1047            0 :                 || async {
    1048            0 :                     if client_conn.is_none() {
    1049            0 :                         let db_client = Self::get_maintenance_client(&url).await?;
    1050            0 :                         client_conn.replace(db_client);
    1051            0 :                     }
    1052            0 :                     let client = client_conn.as_ref().unwrap();
    1053            0 :                     Ok(client)
    1054            0 :                 },
    1055            0 :             )
    1056            0 :             .await?;
    1057              :         }
    1058              : 
    1059            0 :         drop(client_conn);
    1060            0 : 
    1061            0 :         Ok::<(), anyhow::Error>(())
    1062            0 :     }
    1063              : 
    1064              :     /// Do initial configuration of the already started Postgres.
    1065            0 :     #[instrument(skip_all)]
    1066              :     pub fn apply_config(&self, compute_state: &ComputeState) -> Result<()> {
    1067              :         // If connection fails,
    1068              :         // it may be the old node with `zenith_admin` superuser.
    1069              :         //
    1070              :         // In this case we need to connect with old `zenith_admin` name
    1071              :         // and create new user. We cannot simply rename connected user,
    1072              :         // but we can create a new one and grant it all privileges.
    1073              :         let mut url = self.connstr.clone();
    1074              :         url.query_pairs_mut()
    1075              :             .append_pair("application_name", "apply_config");
    1076              : 
    1077              :         let url = Arc::new(url);
    1078              :         let spec = Arc::new(
    1079              :             compute_state
    1080              :                 .pspec
    1081              :                 .as_ref()
    1082              :                 .expect("spec must be set")
    1083              :                 .spec
    1084              :                 .clone(),
    1085              :         );
    1086              : 
    1087              :         // Choose how many concurrent connections to use for applying the spec changes.
    1088              :         // If the cluster is not currently Running we don't have to deal with user connections,
    1089              :         // and can thus use all `max_connections` connection slots. However, that's generally not
    1090              :         // very efficient, so we generally still limit it to a smaller number.
    1091              :         let max_concurrent_connections = if compute_state.status != ComputeStatus::Running {
    1092              :             // If the settings contain 'max_connections', use that as template
    1093              :             if let Some(config) = spec.cluster.settings.find("max_connections") {
    1094              :                 config.parse::<usize>().ok()
    1095              :             } else {
    1096              :                 // Otherwise, try to find the setting in the postgresql_conf string
    1097              :                 spec.cluster
    1098              :                     .postgresql_conf
    1099              :                     .iter()
    1100            0 :                     .flat_map(|conf| conf.split("\n"))
    1101            0 :                     .filter_map(|line| {
    1102            0 :                         if !line.contains("max_connections") {
    1103            0 :                             return None;
    1104            0 :                         }
    1105              : 
    1106            0 :                         let (key, value) = line.split_once("=")?;
    1107            0 :                         let key = key
    1108            0 :                             .trim_start_matches(char::is_whitespace)
    1109            0 :                             .trim_end_matches(char::is_whitespace);
    1110            0 : 
    1111            0 :                         let value = value
    1112            0 :                             .trim_start_matches(char::is_whitespace)
    1113            0 :                             .trim_end_matches(char::is_whitespace);
    1114            0 : 
    1115            0 :                         if key != "max_connections" {
    1116            0 :                             return None;
    1117            0 :                         }
    1118            0 : 
    1119            0 :                         value.parse::<usize>().ok()
    1120            0 :                     })
    1121              :                     .next()
    1122              :             }
    1123              :             // If max_connections is present, use at most 1/3rd of that.
    1124              :             // When max_connections is lower than 30, try to use at least 10 connections, but
    1125              :             // never more than max_connections.
    1126            0 :             .map(|limit| match limit {
    1127            0 :                 0..10 => limit,
    1128            0 :                 10..30 => 10,
    1129            0 :                 30.. => limit / 3,
    1130            0 :             })
    1131              :             // If we didn't find max_connections, default to 10 concurrent connections.
    1132              :             .unwrap_or(10)
    1133              :         } else {
    1134              :             // state == Running
    1135              :             // Because the cluster is already in the Running state, we should assume users are
    1136              :             // already connected to the cluster, and high concurrency could negatively
    1137              :             // impact user connectivity. Therefore, we can limit concurrency to the number of
    1138              :             // reserved superuser connections, which users wouldn't be able to use anyway.
    1139              :             spec.cluster
    1140              :                 .settings
    1141              :                 .find("superuser_reserved_connections")
    1142              :                 .iter()
    1143            0 :                 .filter_map(|val| val.parse::<usize>().ok())
    1144            0 :                 .map(|val| if val > 1 { val - 1 } else { 1 })
    1145              :                 .last()
    1146              :                 .unwrap_or(3)
    1147              :         };
    1148              : 
    1149              :         // Merge-apply spec & changes to PostgreSQL state.
    1150              :         self.apply_spec_sql(spec.clone(), url.clone(), max_concurrent_connections)?;
    1151              : 
    1152              :         if let Some(ref local_proxy) = &spec.clone().local_proxy_config {
    1153              :             info!("configuring local_proxy");
    1154              :             local_proxy::configure(local_proxy).context("apply_config local_proxy")?;
    1155              :         }
    1156              : 
    1157              :         // Run migrations separately to not hold up cold starts
    1158            0 :         thread::spawn(move || {
    1159            0 :             let mut connstr = url.as_ref().clone();
    1160            0 :             connstr
    1161            0 :                 .query_pairs_mut()
    1162            0 :                 .append_pair("application_name", "migrations");
    1163              : 
    1164            0 :             let mut client = Client::connect(connstr.as_str(), NoTls)?;
    1165            0 :             handle_migrations(&mut client).context("apply_config handle_migrations")
    1166            0 :         });
    1167              : 
    1168              :         Ok::<(), anyhow::Error>(())
    1169              :     }
    1170              : 
    1171              :     // Wrapped this around `pg_ctl reload`, but right now we don't use
    1172              :     // `pg_ctl` for start / stop.
    1173            0 :     #[instrument(skip_all)]
    1174              :     fn pg_reload_conf(&self) -> Result<()> {
    1175              :         let pgctl_bin = Path::new(&self.pgbin).parent().unwrap().join("pg_ctl");
    1176              :         Command::new(pgctl_bin)
    1177              :             .args(["reload", "-D", &self.pgdata])
    1178              :             .output()
    1179              :             .expect("cannot run pg_ctl process");
    1180              :         Ok(())
    1181              :     }
    1182              : 
    1183              :     /// Similar to `apply_config()`, but does a bit different sequence of operations,
    1184              :     /// as it's used to reconfigure a previously started and configured Postgres node.
    1185            0 :     #[instrument(skip_all)]
    1186              :     pub fn reconfigure(&self) -> Result<()> {
    1187              :         let spec = self.state.lock().unwrap().pspec.clone().unwrap().spec;
    1188              : 
    1189              :         if let Some(ref pgbouncer_settings) = spec.pgbouncer_settings {
    1190              :             info!("tuning pgbouncer");
    1191              : 
    1192              :             let rt = tokio::runtime::Builder::new_current_thread()
    1193              :                 .enable_all()
    1194              :                 .build()
    1195              :                 .expect("failed to create rt");
    1196              : 
    1197              :             // Spawn a thread to do the tuning,
    1198              :             // so that we don't block the main thread that starts Postgres.
    1199              :             let pgbouncer_settings = pgbouncer_settings.clone();
    1200            0 :             let _handle = thread::spawn(move || {
    1201            0 :                 let res = rt.block_on(tune_pgbouncer(pgbouncer_settings));
    1202            0 :                 if let Err(err) = res {
    1203            0 :                     error!("error while tuning pgbouncer: {err:?}");
    1204            0 :                 }
    1205            0 :             });
    1206              :         }
    1207              : 
    1208              :         if let Some(ref local_proxy) = spec.local_proxy_config {
    1209              :             info!("configuring local_proxy");
    1210              : 
    1211              :             // Spawn a thread to do the configuration,
    1212              :             // so that we don't block the main thread that starts Postgres.
    1213              :             let local_proxy = local_proxy.clone();
    1214            0 :             let _handle = Some(thread::spawn(move || {
    1215            0 :                 if let Err(err) = local_proxy::configure(&local_proxy) {
    1216            0 :                     error!("error while configuring local_proxy: {err:?}");
    1217            0 :                 }
    1218            0 :             }));
    1219              :         }
    1220              : 
    1221              :         // Write new config
    1222              :         let pgdata_path = Path::new(&self.pgdata);
    1223              :         let postgresql_conf_path = pgdata_path.join("postgresql.conf");
    1224              :         config::write_postgres_conf(&postgresql_conf_path, &spec, None)?;
    1225              :         // temporarily reset max_cluster_size in config
    1226              :         // to avoid the possibility of hitting the limit, while we are reconfiguring:
    1227              :         // creating new extensions, roles, etc...
    1228            0 :         config::with_compute_ctl_tmp_override(pgdata_path, "neon.max_cluster_size=-1", || {
    1229            0 :             self.pg_reload_conf()?;
    1230              : 
    1231            0 :             if spec.mode == ComputeMode::Primary {
    1232            0 :                 let mut url = self.connstr.clone();
    1233            0 :                 url.query_pairs_mut()
    1234            0 :                     .append_pair("application_name", "apply_config");
    1235            0 :                 let url = Arc::new(url);
    1236            0 : 
    1237            0 :                 let spec = Arc::new(spec.clone());
    1238            0 : 
    1239            0 :                 self.apply_spec_sql(spec, url, 1)?;
    1240            0 :             }
    1241              : 
    1242            0 :             Ok(())
    1243            0 :         })?;
    1244              : 
    1245              :         self.pg_reload_conf()?;
    1246              : 
    1247              :         let unknown_op = "unknown".to_string();
    1248              :         let op_id = spec.operation_uuid.as_ref().unwrap_or(&unknown_op);
    1249              :         info!(
    1250              :             "finished reconfiguration of compute node for operation {}",
    1251              :             op_id
    1252              :         );
    1253              : 
    1254              :         Ok(())
    1255              :     }
    1256              : 
    1257            0 :     #[instrument(skip_all)]
    1258              :     pub fn start_compute(
    1259              :         &self,
    1260              :         extension_server_port: u16,
    1261              :     ) -> Result<(std::process::Child, std::thread::JoinHandle<()>)> {
    1262              :         let compute_state = self.state.lock().unwrap().clone();
    1263              :         let pspec = compute_state.pspec.as_ref().expect("spec must be set");
    1264              :         info!(
    1265              :             "starting compute for project {}, operation {}, tenant {}, timeline {}",
    1266              :             pspec.spec.cluster.cluster_id.as_deref().unwrap_or("None"),
    1267              :             pspec.spec.operation_uuid.as_deref().unwrap_or("None"),
    1268              :             pspec.tenant_id,
    1269              :             pspec.timeline_id,
    1270              :         );
    1271              : 
    1272              :         // tune pgbouncer
    1273              :         if let Some(pgbouncer_settings) = &pspec.spec.pgbouncer_settings {
    1274              :             info!("tuning pgbouncer");
    1275              : 
    1276              :             let rt = tokio::runtime::Builder::new_current_thread()
    1277              :                 .enable_all()
    1278              :                 .build()
    1279              :                 .expect("failed to create rt");
    1280              : 
    1281              :             // Spawn a thread to do the tuning,
    1282              :             // so that we don't block the main thread that starts Postgres.
    1283              :             let pgbouncer_settings = pgbouncer_settings.clone();
    1284            0 :             let _handle = thread::spawn(move || {
    1285            0 :                 let res = rt.block_on(tune_pgbouncer(pgbouncer_settings));
    1286            0 :                 if let Err(err) = res {
    1287            0 :                     error!("error while tuning pgbouncer: {err:?}");
    1288            0 :                 }
    1289            0 :             });
    1290              :         }
    1291              : 
    1292              :         if let Some(local_proxy) = &pspec.spec.local_proxy_config {
    1293              :             info!("configuring local_proxy");
    1294              : 
    1295              :             // Spawn a thread to do the configuration,
    1296              :             // so that we don't block the main thread that starts Postgres.
    1297              :             let local_proxy = local_proxy.clone();
    1298            0 :             let _handle = thread::spawn(move || {
    1299            0 :                 if let Err(err) = local_proxy::configure(&local_proxy) {
    1300            0 :                     error!("error while configuring local_proxy: {err:?}");
    1301            0 :                 }
    1302            0 :             });
    1303              :         }
    1304              : 
    1305              :         info!(
    1306              :             "start_compute spec.remote_extensions {:?}",
    1307              :             pspec.spec.remote_extensions
    1308              :         );
    1309              : 
    1310              :         // This part is sync, because we need to download
    1311              :         // remote shared_preload_libraries before postgres start (if any)
    1312              :         if let Some(remote_extensions) = &pspec.spec.remote_extensions {
    1313              :             // First, create control files for all availale extensions
    1314              :             extension_server::create_control_files(remote_extensions, &self.pgbin);
    1315              : 
    1316              :             let library_load_start_time = Utc::now();
    1317              :             let remote_ext_metrics = self.prepare_preload_libraries(&pspec.spec)?;
    1318              : 
    1319              :             let library_load_time = Utc::now()
    1320              :                 .signed_duration_since(library_load_start_time)
    1321              :                 .to_std()
    1322              :                 .unwrap()
    1323              :                 .as_millis() as u64;
    1324              :             let mut state = self.state.lock().unwrap();
    1325              :             state.metrics.load_ext_ms = library_load_time;
    1326              :             state.metrics.num_ext_downloaded = remote_ext_metrics.num_ext_downloaded;
    1327              :             state.metrics.largest_ext_size = remote_ext_metrics.largest_ext_size;
    1328              :             state.metrics.total_ext_download_size = remote_ext_metrics.total_ext_download_size;
    1329              :             info!(
    1330              :                 "Loading shared_preload_libraries took {:?}ms",
    1331              :                 library_load_time
    1332              :             );
    1333              :             info!("{:?}", remote_ext_metrics);
    1334              :         }
    1335              : 
    1336              :         self.prepare_pgdata(&compute_state, extension_server_port)?;
    1337              : 
    1338              :         let start_time = Utc::now();
    1339              :         let pg_process = self.start_postgres(pspec.storage_auth_token.clone())?;
    1340              : 
    1341              :         let config_time = Utc::now();
    1342              :         if pspec.spec.mode == ComputeMode::Primary {
    1343              :             if !pspec.spec.skip_pg_catalog_updates {
    1344              :                 let pgdata_path = Path::new(&self.pgdata);
    1345              :                 // temporarily reset max_cluster_size in config
    1346              :                 // to avoid the possibility of hitting the limit, while we are applying config:
    1347              :                 // creating new extensions, roles, etc...
    1348              :                 config::with_compute_ctl_tmp_override(
    1349              :                     pgdata_path,
    1350              :                     "neon.max_cluster_size=-1",
    1351            0 :                     || {
    1352            0 :                         self.pg_reload_conf()?;
    1353              : 
    1354            0 :                         self.apply_config(&compute_state)?;
    1355              : 
    1356            0 :                         Ok(())
    1357            0 :                     },
    1358              :                 )?;
    1359              :                 self.pg_reload_conf()?;
    1360              :             }
    1361              :             self.post_apply_config()?;
    1362              : 
    1363              :             let connstr = self.connstr.clone();
    1364            0 :             thread::spawn(move || {
    1365            0 :                 get_installed_extensions_sync(connstr).context("get_installed_extensions")
    1366            0 :             });
    1367              :         }
    1368              : 
    1369              :         let startup_end_time = Utc::now();
    1370              :         {
    1371              :             let mut state = self.state.lock().unwrap();
    1372              :             state.metrics.start_postgres_ms = config_time
    1373              :                 .signed_duration_since(start_time)
    1374              :                 .to_std()
    1375              :                 .unwrap()
    1376              :                 .as_millis() as u64;
    1377              :             state.metrics.config_ms = startup_end_time
    1378              :                 .signed_duration_since(config_time)
    1379              :                 .to_std()
    1380              :                 .unwrap()
    1381              :                 .as_millis() as u64;
    1382              :             state.metrics.total_startup_ms = startup_end_time
    1383              :                 .signed_duration_since(compute_state.start_time)
    1384              :                 .to_std()
    1385              :                 .unwrap()
    1386              :                 .as_millis() as u64;
    1387              :         }
    1388              :         self.set_status(ComputeStatus::Running);
    1389              : 
    1390              :         info!(
    1391              :             "finished configuration of compute for project {}",
    1392              :             pspec.spec.cluster.cluster_id.as_deref().unwrap_or("None")
    1393              :         );
    1394              : 
    1395              :         // Log metrics so that we can search for slow operations in logs
    1396              :         let metrics = {
    1397              :             let state = self.state.lock().unwrap();
    1398              :             state.metrics.clone()
    1399              :         };
    1400              :         info!(?metrics, "compute start finished");
    1401              : 
    1402              :         Ok(pg_process)
    1403              :     }
    1404              : 
    1405              :     /// Update the `last_active` in the shared state, but ensure that it's a more recent one.
    1406            0 :     pub fn update_last_active(&self, last_active: Option<DateTime<Utc>>) {
    1407            0 :         let mut state = self.state.lock().unwrap();
    1408            0 :         // NB: `Some(<DateTime>)` is always greater than `None`.
    1409            0 :         if last_active > state.last_active {
    1410            0 :             state.last_active = last_active;
    1411            0 :             debug!("set the last compute activity time to: {:?}", last_active);
    1412            0 :         }
    1413            0 :     }
    1414              : 
    1415              :     // Look for core dumps and collect backtraces.
    1416              :     //
    1417              :     // EKS worker nodes have following core dump settings:
    1418              :     //   /proc/sys/kernel/core_pattern -> core
    1419              :     //   /proc/sys/kernel/core_uses_pid -> 1
    1420              :     //   ulimit -c -> unlimited
    1421              :     // which results in core dumps being written to postgres data directory as core.<pid>.
    1422              :     //
    1423              :     // Use that as a default location and pattern, except macos where core dumps are written
    1424              :     // to /cores/ directory by default.
    1425              :     //
    1426              :     // With default Linux settings, the core dump file is called just "core", so check for
    1427              :     // that too.
    1428            0 :     pub fn check_for_core_dumps(&self) -> Result<()> {
    1429            0 :         let core_dump_dir = match std::env::consts::OS {
    1430            0 :             "macos" => Path::new("/cores/"),
    1431            0 :             _ => Path::new(&self.pgdata),
    1432              :         };
    1433              : 
    1434              :         // Collect core dump paths if any
    1435            0 :         info!("checking for core dumps in {}", core_dump_dir.display());
    1436            0 :         let files = fs::read_dir(core_dump_dir)?;
    1437            0 :         let cores = files.filter_map(|entry| {
    1438            0 :             let entry = entry.ok()?;
    1439              : 
    1440            0 :             let is_core_dump = match entry.file_name().to_str()? {
    1441            0 :                 n if n.starts_with("core.") => true,
    1442            0 :                 "core" => true,
    1443            0 :                 _ => false,
    1444              :             };
    1445            0 :             if is_core_dump {
    1446            0 :                 Some(entry.path())
    1447              :             } else {
    1448            0 :                 None
    1449              :             }
    1450            0 :         });
    1451              : 
    1452              :         // Print backtrace for each core dump
    1453            0 :         for core_path in cores {
    1454            0 :             warn!(
    1455            0 :                 "core dump found: {}, collecting backtrace",
    1456            0 :                 core_path.display()
    1457              :             );
    1458              : 
    1459              :             // Try first with gdb
    1460            0 :             let backtrace = Command::new("gdb")
    1461            0 :                 .args(["--batch", "-q", "-ex", "bt", &self.pgbin])
    1462            0 :                 .arg(&core_path)
    1463            0 :                 .output();
    1464              : 
    1465              :             // Try lldb if no gdb is found -- that is handy for local testing on macOS
    1466            0 :             let backtrace = match backtrace {
    1467            0 :                 Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
    1468            0 :                     warn!("cannot find gdb, trying lldb");
    1469            0 :                     Command::new("lldb")
    1470            0 :                         .arg("-c")
    1471            0 :                         .arg(&core_path)
    1472            0 :                         .args(["--batch", "-o", "bt all", "-o", "quit"])
    1473            0 :                         .output()
    1474              :                 }
    1475            0 :                 _ => backtrace,
    1476            0 :             }?;
    1477              : 
    1478            0 :             warn!(
    1479            0 :                 "core dump backtrace: {}",
    1480            0 :                 String::from_utf8_lossy(&backtrace.stdout)
    1481              :             );
    1482            0 :             warn!(
    1483            0 :                 "debugger stderr: {}",
    1484            0 :                 String::from_utf8_lossy(&backtrace.stderr)
    1485              :             );
    1486              :         }
    1487              : 
    1488            0 :         Ok(())
    1489            0 :     }
    1490              : 
    1491              :     /// Select `pg_stat_statements` data and return it as a stringified JSON
    1492            0 :     pub async fn collect_insights(&self) -> String {
    1493            0 :         let mut result_rows: Vec<String> = Vec::new();
    1494            0 :         let connect_result = tokio_postgres::connect(self.connstr.as_str(), NoTls).await;
    1495            0 :         let (client, connection) = connect_result.unwrap();
    1496            0 :         tokio::spawn(async move {
    1497            0 :             if let Err(e) = connection.await {
    1498            0 :                 eprintln!("connection error: {}", e);
    1499            0 :             }
    1500            0 :         });
    1501            0 :         let result = client
    1502            0 :             .simple_query(
    1503            0 :                 "SELECT
    1504            0 :     row_to_json(pg_stat_statements)
    1505            0 : FROM
    1506            0 :     pg_stat_statements
    1507            0 : WHERE
    1508            0 :     userid != 'cloud_admin'::regrole::oid
    1509            0 : ORDER BY
    1510            0 :     (mean_exec_time + mean_plan_time) DESC
    1511            0 : LIMIT 100",
    1512            0 :             )
    1513            0 :             .await;
    1514              : 
    1515            0 :         if let Ok(raw_rows) = result {
    1516            0 :             for message in raw_rows.iter() {
    1517            0 :                 if let postgres::SimpleQueryMessage::Row(row) = message {
    1518            0 :                     if let Some(json) = row.get(0) {
    1519            0 :                         result_rows.push(json.to_string());
    1520            0 :                     }
    1521            0 :                 }
    1522              :             }
    1523              : 
    1524            0 :             format!("{{\"pg_stat_statements\": [{}]}}", result_rows.join(","))
    1525              :         } else {
    1526            0 :             "{{\"pg_stat_statements\": []}}".to_string()
    1527              :         }
    1528            0 :     }
    1529              : 
    1530              :     // download an archive, unzip and place files in correct locations
    1531            0 :     pub async fn download_extension(
    1532            0 :         &self,
    1533            0 :         real_ext_name: String,
    1534            0 :         ext_path: RemotePath,
    1535            0 :     ) -> Result<u64, DownloadError> {
    1536            0 :         let ext_remote_storage =
    1537            0 :             self.ext_remote_storage
    1538            0 :                 .as_ref()
    1539            0 :                 .ok_or(DownloadError::BadInput(anyhow::anyhow!(
    1540            0 :                     "Remote extensions storage is not configured",
    1541            0 :                 )))?;
    1542              : 
    1543            0 :         let ext_archive_name = ext_path.object_name().expect("bad path");
    1544            0 : 
    1545            0 :         let mut first_try = false;
    1546            0 :         if !self
    1547            0 :             .ext_download_progress
    1548            0 :             .read()
    1549            0 :             .expect("lock err")
    1550            0 :             .contains_key(ext_archive_name)
    1551            0 :         {
    1552            0 :             self.ext_download_progress
    1553            0 :                 .write()
    1554            0 :                 .expect("lock err")
    1555            0 :                 .insert(ext_archive_name.to_string(), (Utc::now(), false));
    1556            0 :             first_try = true;
    1557            0 :         }
    1558            0 :         let (download_start, download_completed) =
    1559            0 :             self.ext_download_progress.read().expect("lock err")[ext_archive_name];
    1560            0 :         let start_time_delta = Utc::now()
    1561            0 :             .signed_duration_since(download_start)
    1562            0 :             .to_std()
    1563            0 :             .unwrap()
    1564            0 :             .as_millis() as u64;
    1565              : 
    1566              :         // how long to wait for extension download if it was started by another process
    1567              :         const HANG_TIMEOUT: u64 = 3000; // milliseconds
    1568              : 
    1569            0 :         if download_completed {
    1570            0 :             info!("extension already downloaded, skipping re-download");
    1571            0 :             return Ok(0);
    1572            0 :         } else if start_time_delta < HANG_TIMEOUT && !first_try {
    1573            0 :             info!("download {ext_archive_name} already started by another process, hanging untill completion or timeout");
    1574            0 :             let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(500));
    1575              :             loop {
    1576            0 :                 info!("waiting for download");
    1577            0 :                 interval.tick().await;
    1578            0 :                 let (_, download_completed_now) =
    1579            0 :                     self.ext_download_progress.read().expect("lock")[ext_archive_name];
    1580            0 :                 if download_completed_now {
    1581            0 :                     info!("download finished by whoever else downloaded it");
    1582            0 :                     return Ok(0);
    1583            0 :                 }
    1584              :             }
    1585              :             // NOTE: the above loop will get terminated
    1586              :             // based on the timeout of the download function
    1587            0 :         }
    1588            0 : 
    1589            0 :         // if extension hasn't been downloaded before or the previous
    1590            0 :         // attempt to download was at least HANG_TIMEOUT ms ago
    1591            0 :         // then we try to download it here
    1592            0 :         info!("downloading new extension {ext_archive_name}");
    1593              : 
    1594            0 :         let download_size = extension_server::download_extension(
    1595            0 :             &real_ext_name,
    1596            0 :             &ext_path,
    1597            0 :             ext_remote_storage,
    1598            0 :             &self.pgbin,
    1599            0 :         )
    1600            0 :         .await
    1601            0 :         .map_err(DownloadError::Other);
    1602            0 : 
    1603            0 :         if download_size.is_ok() {
    1604            0 :             self.ext_download_progress
    1605            0 :                 .write()
    1606            0 :                 .expect("bad lock")
    1607            0 :                 .insert(ext_archive_name.to_string(), (download_start, true));
    1608            0 :         }
    1609              : 
    1610            0 :         download_size
    1611            0 :     }
    1612              : 
    1613            0 :     pub async fn set_role_grants(
    1614            0 :         &self,
    1615            0 :         db_name: &PgIdent,
    1616            0 :         schema_name: &PgIdent,
    1617            0 :         privileges: &[Privilege],
    1618            0 :         role_name: &PgIdent,
    1619            0 :     ) -> Result<()> {
    1620              :         use tokio_postgres::config::Config;
    1621              :         use tokio_postgres::NoTls;
    1622              : 
    1623            0 :         let mut conf = Config::from_str(self.connstr.as_str()).unwrap();
    1624            0 :         conf.dbname(db_name);
    1625              : 
    1626            0 :         let (db_client, conn) = conf
    1627            0 :             .connect(NoTls)
    1628            0 :             .await
    1629            0 :             .context("Failed to connect to the database")?;
    1630            0 :         tokio::spawn(conn);
    1631            0 : 
    1632            0 :         // TODO: support other types of grants apart from schemas?
    1633            0 :         let query = format!(
    1634            0 :             "GRANT {} ON SCHEMA {} TO {}",
    1635            0 :             privileges
    1636            0 :                 .iter()
    1637            0 :                 // should not be quoted as it's part of the command.
    1638            0 :                 // is already sanitized so it's ok
    1639            0 :                 .map(|p| p.as_str())
    1640            0 :                 .collect::<Vec<&'static str>>()
    1641            0 :                 .join(", "),
    1642            0 :             // quote the schema and role name as identifiers to sanitize them.
    1643            0 :             schema_name.pg_quote(),
    1644            0 :             role_name.pg_quote(),
    1645            0 :         );
    1646            0 :         db_client
    1647            0 :             .simple_query(&query)
    1648            0 :             .await
    1649            0 :             .with_context(|| format!("Failed to execute query: {}", query))?;
    1650              : 
    1651            0 :         Ok(())
    1652            0 :     }
    1653              : 
    1654            0 :     pub async fn install_extension(
    1655            0 :         &self,
    1656            0 :         ext_name: &PgIdent,
    1657            0 :         db_name: &PgIdent,
    1658            0 :         ext_version: ExtVersion,
    1659            0 :     ) -> Result<ExtVersion> {
    1660              :         use tokio_postgres::config::Config;
    1661              :         use tokio_postgres::NoTls;
    1662              : 
    1663            0 :         let mut conf = Config::from_str(self.connstr.as_str()).unwrap();
    1664            0 :         conf.dbname(db_name);
    1665              : 
    1666            0 :         let (db_client, conn) = conf
    1667            0 :             .connect(NoTls)
    1668            0 :             .await
    1669            0 :             .context("Failed to connect to the database")?;
    1670            0 :         tokio::spawn(conn);
    1671            0 : 
    1672            0 :         let version_query = "SELECT extversion FROM pg_extension WHERE extname = $1";
    1673            0 :         let version: Option<ExtVersion> = db_client
    1674            0 :             .query_opt(version_query, &[&ext_name])
    1675            0 :             .await
    1676            0 :             .with_context(|| format!("Failed to execute query: {}", version_query))?
    1677            0 :             .map(|row| row.get(0));
    1678            0 : 
    1679            0 :         // sanitize the inputs as postgres idents.
    1680            0 :         let ext_name: String = ext_name.pg_quote();
    1681            0 :         let quoted_version: String = ext_version.pg_quote();
    1682              : 
    1683            0 :         if let Some(installed_version) = version {
    1684            0 :             if installed_version == ext_version {
    1685            0 :                 return Ok(installed_version);
    1686            0 :             }
    1687            0 :             let query = format!("ALTER EXTENSION {ext_name} UPDATE TO {quoted_version}");
    1688            0 :             db_client
    1689            0 :                 .simple_query(&query)
    1690            0 :                 .await
    1691            0 :                 .with_context(|| format!("Failed to execute query: {}", query))?;
    1692              :         } else {
    1693            0 :             let query =
    1694            0 :                 format!("CREATE EXTENSION IF NOT EXISTS {ext_name} WITH VERSION {quoted_version}");
    1695            0 :             db_client
    1696            0 :                 .simple_query(&query)
    1697            0 :                 .await
    1698            0 :                 .with_context(|| format!("Failed to execute query: {}", query))?;
    1699              :         }
    1700              : 
    1701            0 :         Ok(ext_version)
    1702            0 :     }
    1703              : 
    1704              :     #[tokio::main]
    1705            0 :     pub async fn prepare_preload_libraries(
    1706            0 :         &self,
    1707            0 :         spec: &ComputeSpec,
    1708            0 :     ) -> Result<RemoteExtensionMetrics> {
    1709            0 :         if self.ext_remote_storage.is_none() {
    1710            0 :             return Ok(RemoteExtensionMetrics {
    1711            0 :                 num_ext_downloaded: 0,
    1712            0 :                 largest_ext_size: 0,
    1713            0 :                 total_ext_download_size: 0,
    1714            0 :             });
    1715            0 :         }
    1716            0 :         let remote_extensions = spec
    1717            0 :             .remote_extensions
    1718            0 :             .as_ref()
    1719            0 :             .ok_or(anyhow::anyhow!("Remote extensions are not configured"))?;
    1720            0 : 
    1721            0 :         info!("parse shared_preload_libraries from spec.cluster.settings");
    1722            0 :         let mut libs_vec = Vec::new();
    1723            0 :         if let Some(libs) = spec.cluster.settings.find("shared_preload_libraries") {
    1724            0 :             libs_vec = libs
    1725            0 :                 .split(&[',', '\'', ' '])
    1726            0 :                 .filter(|s| *s != "neon" && !s.is_empty())
    1727            0 :                 .map(str::to_string)
    1728            0 :                 .collect();
    1729            0 :         }
    1730            0 :         info!("parse shared_preload_libraries from provided postgresql.conf");
    1731            0 : 
    1732            0 :         // that is used in neon_local and python tests
    1733            0 :         if let Some(conf) = &spec.cluster.postgresql_conf {
    1734            0 :             let conf_lines = conf.split('\n').collect::<Vec<&str>>();
    1735            0 :             let mut shared_preload_libraries_line = "";
    1736            0 :             for line in conf_lines {
    1737            0 :                 if line.starts_with("shared_preload_libraries") {
    1738            0 :                     shared_preload_libraries_line = line;
    1739            0 :                 }
    1740            0 :             }
    1741            0 :             let mut preload_libs_vec = Vec::new();
    1742            0 :             if let Some(libs) = shared_preload_libraries_line.split("='").nth(1) {
    1743            0 :                 preload_libs_vec = libs
    1744            0 :                     .split(&[',', '\'', ' '])
    1745            0 :                     .filter(|s| *s != "neon" && !s.is_empty())
    1746            0 :                     .map(str::to_string)
    1747            0 :                     .collect();
    1748            0 :             }
    1749            0 :             libs_vec.extend(preload_libs_vec);
    1750            0 :         }
    1751            0 : 
    1752            0 :         // Don't try to download libraries that are not in the index.
    1753            0 :         // Assume that they are already present locally.
    1754            0 :         libs_vec.retain(|lib| remote_extensions.library_index.contains_key(lib));
    1755            0 : 
    1756            0 :         info!("Downloading to shared preload libraries: {:?}", &libs_vec);
    1757            0 : 
    1758            0 :         let mut download_tasks = Vec::new();
    1759            0 :         for library in &libs_vec {
    1760            0 :             let (ext_name, ext_path) =
    1761            0 :                 remote_extensions.get_ext(library, true, &self.build_tag, &self.pgversion)?;
    1762            0 :             download_tasks.push(self.download_extension(ext_name, ext_path));
    1763            0 :         }
    1764            0 :         let results = join_all(download_tasks).await;
    1765            0 : 
    1766            0 :         let mut remote_ext_metrics = RemoteExtensionMetrics {
    1767            0 :             num_ext_downloaded: 0,
    1768            0 :             largest_ext_size: 0,
    1769            0 :             total_ext_download_size: 0,
    1770            0 :         };
    1771            0 :         for result in results {
    1772            0 :             let download_size = match result {
    1773            0 :                 Ok(res) => {
    1774            0 :                     remote_ext_metrics.num_ext_downloaded += 1;
    1775            0 :                     res
    1776            0 :                 }
    1777            0 :                 Err(err) => {
    1778            0 :                     // if we failed to download an extension, we don't want to fail the whole
    1779            0 :                     // process, but we do want to log the error
    1780            0 :                     error!("Failed to download extension: {}", err);
    1781            0 :                     0
    1782            0 :                 }
    1783            0 :             };
    1784            0 : 
    1785            0 :             remote_ext_metrics.largest_ext_size =
    1786            0 :                 std::cmp::max(remote_ext_metrics.largest_ext_size, download_size);
    1787            0 :             remote_ext_metrics.total_ext_download_size += download_size;
    1788            0 :         }
    1789            0 :         Ok(remote_ext_metrics)
    1790            0 :     }
    1791              : 
    1792              :     /// Waits until current thread receives a state changed notification and
    1793              :     /// the pageserver connection strings has changed.
    1794              :     ///
    1795              :     /// The operation will time out after a specified duration.
    1796            0 :     pub fn wait_timeout_while_pageserver_connstr_unchanged(&self, duration: Duration) {
    1797            0 :         let state = self.state.lock().unwrap();
    1798            0 :         let old_pageserver_connstr = state
    1799            0 :             .pspec
    1800            0 :             .as_ref()
    1801            0 :             .expect("spec must be set")
    1802            0 :             .pageserver_connstr
    1803            0 :             .clone();
    1804            0 :         let mut unchanged = true;
    1805            0 :         let _ = self
    1806            0 :             .state_changed
    1807            0 :             .wait_timeout_while(state, duration, |s| {
    1808            0 :                 let pageserver_connstr = &s
    1809            0 :                     .pspec
    1810            0 :                     .as_ref()
    1811            0 :                     .expect("spec must be set")
    1812            0 :                     .pageserver_connstr;
    1813            0 :                 unchanged = pageserver_connstr == &old_pageserver_connstr;
    1814            0 :                 unchanged
    1815            0 :             })
    1816            0 :             .unwrap();
    1817            0 :         if !unchanged {
    1818            0 :             info!("Pageserver config changed");
    1819            0 :         }
    1820            0 :     }
    1821              : }
    1822              : 
    1823            0 : pub fn forward_termination_signal() {
    1824            0 :     let ss_pid = SYNC_SAFEKEEPERS_PID.load(Ordering::SeqCst);
    1825            0 :     if ss_pid != 0 {
    1826            0 :         let ss_pid = nix::unistd::Pid::from_raw(ss_pid as i32);
    1827            0 :         kill(ss_pid, Signal::SIGTERM).ok();
    1828            0 :     }
    1829            0 :     let pg_pid = PG_PID.load(Ordering::SeqCst);
    1830            0 :     if pg_pid != 0 {
    1831            0 :         let pg_pid = nix::unistd::Pid::from_raw(pg_pid as i32);
    1832            0 :         // Use 'fast' shutdown (SIGINT) because it also creates a shutdown checkpoint, which is important for
    1833            0 :         // ROs to get a list of running xacts faster instead of going through the CLOG.
    1834            0 :         // See https://www.postgresql.org/docs/current/server-shutdown.html for the list of modes and signals.
    1835            0 :         kill(pg_pid, Signal::SIGINT).ok();
    1836            0 :     }
    1837            0 : }
        

Generated by: LCOV version 2.1-beta