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