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