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