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