Line data Source code
1 : use std::collections::HashMap;
2 : use std::env;
3 : use std::fs;
4 : use std::io::BufRead;
5 : use std::os::unix::fs::{symlink, PermissionsExt};
6 : use std::path::Path;
7 : use std::process::{Command, Stdio};
8 : use std::str::FromStr;
9 : use std::sync::atomic::AtomicU32;
10 : use std::sync::atomic::Ordering;
11 : use std::sync::{Condvar, Mutex, RwLock};
12 : use std::thread;
13 : use std::time::Instant;
14 :
15 : use anyhow::{Context, Result};
16 : use chrono::{DateTime, Utc};
17 : use futures::future::join_all;
18 : use futures::stream::FuturesUnordered;
19 : use futures::StreamExt;
20 : use nix::unistd::Pid;
21 : use postgres::error::SqlState;
22 : use postgres::{Client, NoTls};
23 : use tracing::{debug, error, info, instrument, warn};
24 : use utils::id::{TenantId, TimelineId};
25 : use utils::lsn::Lsn;
26 :
27 : use compute_api::responses::{ComputeMetrics, ComputeStatus};
28 : use compute_api::spec::{ComputeFeature, ComputeMode, ComputeSpec};
29 : use utils::measured_stream::MeasuredReader;
30 :
31 : use nix::sys::signal::{kill, Signal};
32 :
33 : use remote_storage::{DownloadError, RemotePath};
34 :
35 : use crate::checker::create_availability_check_data;
36 : use crate::logger::inlinify;
37 : use crate::pg_helpers::*;
38 : use crate::spec::*;
39 : use crate::sync_sk::{check_if_synced, ping_safekeeper};
40 : use crate::{config, extension_server};
41 :
42 : pub static SYNC_SAFEKEEPERS_PID: AtomicU32 = AtomicU32::new(0);
43 : pub static PG_PID: AtomicU32 = AtomicU32::new(0);
44 :
45 : /// Compute node info shared across several `compute_ctl` threads.
46 : pub struct ComputeNode {
47 : // Url type maintains proper escaping
48 : pub connstr: url::Url,
49 : pub pgdata: String,
50 : pub pgbin: String,
51 : pub pgversion: String,
52 : /// We should only allow live re- / configuration of the compute node if
53 : /// it uses 'pull model', i.e. it can go to control-plane and fetch
54 : /// the latest configuration. Otherwise, there could be a case:
55 : /// - we start compute with some spec provided as argument
56 : /// - we push new spec and it does reconfiguration
57 : /// - but then something happens and compute pod / VM is destroyed,
58 : /// so k8s controller starts it again with the **old** spec
59 : ///
60 : /// and the same for empty computes:
61 : /// - we started compute without any spec
62 : /// - we push spec and it does configuration
63 : /// - but then it is restarted without any spec again
64 : pub live_config_allowed: bool,
65 : /// Volatile part of the `ComputeNode`, which should be used under `Mutex`.
66 : /// To allow HTTP API server to serving status requests, while configuration
67 : /// is in progress, lock should be held only for short periods of time to do
68 : /// read/write, not the whole configuration process.
69 : pub state: Mutex<ComputeState>,
70 : /// `Condvar` to allow notifying waiters about state changes.
71 : pub state_changed: Condvar,
72 : /// the address of extension storage proxy gateway
73 : pub ext_remote_storage: Option<String>,
74 : // key: ext_archive_name, value: started download time, download_completed?
75 : pub ext_download_progress: RwLock<HashMap<String, (DateTime<Utc>, bool)>>,
76 : pub build_tag: String,
77 : }
78 :
79 : // store some metrics about download size that might impact startup time
80 : #[derive(Clone, Debug)]
81 : pub struct RemoteExtensionMetrics {
82 : num_ext_downloaded: u64,
83 : largest_ext_size: u64,
84 : total_ext_download_size: u64,
85 : }
86 :
87 : #[derive(Clone, Debug)]
88 : pub struct ComputeState {
89 : pub start_time: DateTime<Utc>,
90 : pub status: ComputeStatus,
91 : /// Timestamp of the last Postgres activity. It could be `None` if
92 : /// compute wasn't used since start.
93 : pub last_active: Option<DateTime<Utc>>,
94 : pub error: Option<String>,
95 : pub pspec: Option<ParsedSpec>,
96 : pub metrics: ComputeMetrics,
97 : }
98 :
99 : impl ComputeState {
100 0 : pub fn new() -> Self {
101 0 : Self {
102 0 : start_time: Utc::now(),
103 0 : status: ComputeStatus::Empty,
104 0 : last_active: None,
105 0 : error: None,
106 0 : pspec: None,
107 0 : metrics: ComputeMetrics::default(),
108 0 : }
109 0 : }
110 : }
111 :
112 : impl Default for ComputeState {
113 0 : fn default() -> Self {
114 0 : Self::new()
115 0 : }
116 : }
117 :
118 : #[derive(Clone, Debug)]
119 : pub struct ParsedSpec {
120 : pub spec: ComputeSpec,
121 : pub tenant_id: TenantId,
122 : pub timeline_id: TimelineId,
123 : pub pageserver_connstr: String,
124 : pub safekeeper_connstrings: Vec<String>,
125 : pub storage_auth_token: Option<String>,
126 : }
127 :
128 : impl TryFrom<ComputeSpec> for ParsedSpec {
129 : type Error = String;
130 0 : fn try_from(spec: ComputeSpec) -> Result<Self, String> {
131 : // Extract the options from the spec file that are needed to connect to
132 : // the storage system.
133 : //
134 : // For backwards-compatibility, the top-level fields in the spec file
135 : // may be empty. In that case, we need to dig them from the GUCs in the
136 : // cluster.settings field.
137 0 : let pageserver_connstr = spec
138 0 : .pageserver_connstring
139 0 : .clone()
140 0 : .or_else(|| spec.cluster.settings.find("neon.pageserver_connstring"))
141 0 : .ok_or("pageserver connstr should be provided")?;
142 0 : let safekeeper_connstrings = if spec.safekeeper_connstrings.is_empty() {
143 0 : if matches!(spec.mode, ComputeMode::Primary) {
144 0 : spec.cluster
145 0 : .settings
146 0 : .find("neon.safekeepers")
147 0 : .ok_or("safekeeper connstrings should be provided")?
148 0 : .split(',')
149 0 : .map(|str| str.to_string())
150 0 : .collect()
151 : } else {
152 0 : vec![]
153 : }
154 : } else {
155 0 : spec.safekeeper_connstrings.clone()
156 : };
157 0 : let storage_auth_token = spec.storage_auth_token.clone();
158 0 : let tenant_id: TenantId = if let Some(tenant_id) = spec.tenant_id {
159 0 : tenant_id
160 : } else {
161 0 : spec.cluster
162 0 : .settings
163 0 : .find("neon.tenant_id")
164 0 : .ok_or("tenant id should be provided")
165 0 : .map(|s| TenantId::from_str(&s))?
166 0 : .or(Err("invalid tenant id"))?
167 : };
168 0 : let timeline_id: TimelineId = if let Some(timeline_id) = spec.timeline_id {
169 0 : timeline_id
170 : } else {
171 0 : spec.cluster
172 0 : .settings
173 0 : .find("neon.timeline_id")
174 0 : .ok_or("timeline id should be provided")
175 0 : .map(|s| TimelineId::from_str(&s))?
176 0 : .or(Err("invalid timeline id"))?
177 : };
178 :
179 0 : Ok(ParsedSpec {
180 0 : spec,
181 0 : pageserver_connstr,
182 0 : safekeeper_connstrings,
183 0 : storage_auth_token,
184 0 : tenant_id,
185 0 : timeline_id,
186 0 : })
187 0 : }
188 : }
189 :
190 : /// If we are a VM, returns a [`Command`] that will run in the `neon-postgres`
191 : /// cgroup. Otherwise returns the default `Command::new(cmd)`
192 : ///
193 : /// This function should be used to start postgres, as it will start it in the
194 : /// neon-postgres cgroup if we are a VM. This allows autoscaling to control
195 : /// postgres' resource usage. The cgroup will exist in VMs because vm-builder
196 : /// creates it during the sysinit phase of its inittab.
197 0 : fn maybe_cgexec(cmd: &str) -> Command {
198 0 : // The cplane sets this env var for autoscaling computes.
199 0 : // use `var_os` so we don't have to worry about the variable being valid
200 0 : // unicode. Should never be an concern . . . but just in case
201 0 : if env::var_os("AUTOSCALING").is_some() {
202 0 : let mut command = Command::new("cgexec");
203 0 : command.args(["-g", "memory:neon-postgres"]);
204 0 : command.arg(cmd);
205 0 : command
206 : } else {
207 0 : Command::new(cmd)
208 : }
209 0 : }
210 :
211 : /// Create special neon_superuser role, that's a slightly nerfed version of a real superuser
212 : /// that we give to customers
213 0 : #[instrument(skip_all)]
214 : fn create_neon_superuser(spec: &ComputeSpec, client: &mut Client) -> Result<()> {
215 : let roles = spec
216 : .cluster
217 : .roles
218 : .iter()
219 0 : .map(|r| escape_literal(&r.name))
220 : .collect::<Vec<_>>();
221 :
222 : let dbs = spec
223 : .cluster
224 : .databases
225 : .iter()
226 0 : .map(|db| escape_literal(&db.name))
227 : .collect::<Vec<_>>();
228 :
229 : let roles_decl = if roles.is_empty() {
230 : String::from("roles text[] := NULL;")
231 : } else {
232 : format!(
233 : r#"
234 : roles text[] := ARRAY(SELECT rolname
235 : FROM pg_catalog.pg_roles
236 : WHERE rolname IN ({}));"#,
237 : roles.join(", ")
238 : )
239 : };
240 :
241 : let database_decl = if dbs.is_empty() {
242 : String::from("dbs text[] := NULL;")
243 : } else {
244 : format!(
245 : r#"
246 : dbs text[] := ARRAY(SELECT datname
247 : FROM pg_catalog.pg_database
248 : WHERE datname IN ({}));"#,
249 : dbs.join(", ")
250 : )
251 : };
252 :
253 : // ALL PRIVILEGES grants CREATE, CONNECT, and TEMPORARY on all databases
254 : // (see https://www.postgresql.org/docs/current/ddl-priv.html)
255 : let query = format!(
256 : r#"
257 : DO $$
258 : DECLARE
259 : r text;
260 : {}
261 : {}
262 : BEGIN
263 : IF NOT EXISTS (
264 : SELECT FROM pg_catalog.pg_roles WHERE rolname = 'neon_superuser')
265 : THEN
266 : CREATE ROLE neon_superuser CREATEDB CREATEROLE NOLOGIN REPLICATION BYPASSRLS IN ROLE pg_read_all_data, pg_write_all_data;
267 : IF array_length(roles, 1) IS NOT NULL THEN
268 : EXECUTE format('GRANT neon_superuser TO %s',
269 : array_to_string(ARRAY(SELECT quote_ident(x) FROM unnest(roles) as x), ', '));
270 : FOREACH r IN ARRAY roles LOOP
271 : EXECUTE format('ALTER ROLE %s CREATEROLE CREATEDB', quote_ident(r));
272 : END LOOP;
273 : END IF;
274 : IF array_length(dbs, 1) IS NOT NULL THEN
275 : EXECUTE format('GRANT ALL PRIVILEGES ON DATABASE %s TO neon_superuser',
276 : array_to_string(ARRAY(SELECT quote_ident(x) FROM unnest(dbs) as x), ', '));
277 : END IF;
278 : END IF;
279 : END
280 : $$;"#,
281 : roles_decl, database_decl,
282 : );
283 : info!("Neon superuser created: {}", inlinify(&query));
284 : client
285 : .simple_query(&query)
286 0 : .map_err(|e| anyhow::anyhow!(e).context(query))?;
287 : Ok(())
288 : }
289 :
290 : impl ComputeNode {
291 : /// Check that compute node has corresponding feature enabled.
292 0 : pub fn has_feature(&self, feature: ComputeFeature) -> bool {
293 0 : let state = self.state.lock().unwrap();
294 :
295 0 : if let Some(s) = state.pspec.as_ref() {
296 0 : s.spec.features.contains(&feature)
297 : } else {
298 0 : false
299 : }
300 0 : }
301 :
302 0 : pub fn set_status(&self, status: ComputeStatus) {
303 0 : let mut state = self.state.lock().unwrap();
304 0 : state.status = status;
305 0 : self.state_changed.notify_all();
306 0 : }
307 :
308 0 : pub fn get_status(&self) -> ComputeStatus {
309 0 : self.state.lock().unwrap().status
310 0 : }
311 :
312 : // Remove `pgdata` directory and create it again with right permissions.
313 0 : fn create_pgdata(&self) -> Result<()> {
314 0 : // Ignore removal error, likely it is a 'No such file or directory (os error 2)'.
315 0 : // If it is something different then create_dir() will error out anyway.
316 0 : let _ok = fs::remove_dir_all(&self.pgdata);
317 0 : fs::create_dir(&self.pgdata)?;
318 0 : fs::set_permissions(&self.pgdata, fs::Permissions::from_mode(0o700))?;
319 :
320 0 : Ok(())
321 0 : }
322 :
323 : // Get basebackup from the libpq connection to pageserver using `connstr` and
324 : // unarchive it to `pgdata` directory overriding all its previous content.
325 0 : #[instrument(skip_all, fields(%lsn))]
326 : fn try_get_basebackup(&self, compute_state: &ComputeState, lsn: Lsn) -> Result<()> {
327 : let spec = compute_state.pspec.as_ref().expect("spec must be set");
328 : let start_time = Instant::now();
329 :
330 : let shard0_connstr = spec.pageserver_connstr.split(',').next().unwrap();
331 : let mut config = postgres::Config::from_str(shard0_connstr)?;
332 :
333 : // Use the storage auth token from the config file, if given.
334 : // Note: this overrides any password set in the connection string.
335 : if let Some(storage_auth_token) = &spec.storage_auth_token {
336 : info!("Got storage auth token from spec file");
337 : config.password(storage_auth_token);
338 : } else {
339 : info!("Storage auth token not set");
340 : }
341 :
342 : // Connect to pageserver
343 : let mut client = config.connect(NoTls)?;
344 : let pageserver_connect_micros = start_time.elapsed().as_micros() as u64;
345 :
346 : let basebackup_cmd = match lsn {
347 : // HACK We don't use compression on first start (Lsn(0)) because there's no API for it
348 : Lsn(0) => format!("basebackup {} {}", spec.tenant_id, spec.timeline_id),
349 : _ => format!(
350 : "basebackup {} {} {} --gzip",
351 : spec.tenant_id, spec.timeline_id, lsn
352 : ),
353 : };
354 :
355 : let copyreader = client.copy_out(basebackup_cmd.as_str())?;
356 : let mut measured_reader = MeasuredReader::new(copyreader);
357 :
358 : // Check the magic number to see if it's a gzip or not. Even though
359 : // we might explicitly ask for gzip, an old pageserver with no implementation
360 : // of gzip compression might send us uncompressed data. After some time
361 : // passes we can assume all pageservers know how to compress and we can
362 : // delete this check.
363 : //
364 : // If the data is not gzip, it will be tar. It will not be mistakenly
365 : // recognized as gzip because tar starts with an ascii encoding of a filename,
366 : // and 0x1f and 0x8b are unlikely first characters for any filename. Moreover,
367 : // we send the "global" directory first from the pageserver, so it definitely
368 : // won't be recognized as gzip.
369 : let mut bufreader = std::io::BufReader::new(&mut measured_reader);
370 : let gzip = {
371 : let peek = bufreader.fill_buf().unwrap();
372 : peek[0] == 0x1f && peek[1] == 0x8b
373 : };
374 :
375 : // Read the archive directly from the `CopyOutReader`
376 : //
377 : // Set `ignore_zeros` so that unpack() reads all the Copy data and
378 : // doesn't stop at the end-of-archive marker. Otherwise, if the server
379 : // sends an Error after finishing the tarball, we will not notice it.
380 : if gzip {
381 : let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(&mut bufreader));
382 : ar.set_ignore_zeros(true);
383 : ar.unpack(&self.pgdata)?;
384 : } else {
385 : let mut ar = tar::Archive::new(&mut bufreader);
386 : ar.set_ignore_zeros(true);
387 : ar.unpack(&self.pgdata)?;
388 : };
389 :
390 : // Report metrics
391 : let mut state = self.state.lock().unwrap();
392 : state.metrics.pageserver_connect_micros = pageserver_connect_micros;
393 : state.metrics.basebackup_bytes = measured_reader.get_byte_count() as u64;
394 : state.metrics.basebackup_ms = start_time.elapsed().as_millis() as u64;
395 : Ok(())
396 : }
397 :
398 : // Gets the basebackup in a retry loop
399 0 : #[instrument(skip_all, fields(%lsn))]
400 : pub fn get_basebackup(&self, compute_state: &ComputeState, lsn: Lsn) -> Result<()> {
401 : let mut retry_period_ms = 500.0;
402 : let mut attempts = 0;
403 : let max_attempts = 10;
404 : loop {
405 : let result = self.try_get_basebackup(compute_state, lsn);
406 : match result {
407 : Ok(_) => {
408 : return result;
409 : }
410 : Err(ref e) if attempts < max_attempts => {
411 : warn!(
412 : "Failed to get basebackup: {} (attempt {}/{})",
413 : e, attempts, max_attempts
414 : );
415 : std::thread::sleep(std::time::Duration::from_millis(retry_period_ms as u64));
416 : retry_period_ms *= 1.5;
417 : }
418 : Err(_) => {
419 : return result;
420 : }
421 : }
422 : attempts += 1;
423 : }
424 : }
425 :
426 0 : pub async fn check_safekeepers_synced_async(
427 0 : &self,
428 0 : compute_state: &ComputeState,
429 0 : ) -> Result<Option<Lsn>> {
430 0 : // Construct a connection config for each safekeeper
431 0 : let pspec: ParsedSpec = compute_state
432 0 : .pspec
433 0 : .as_ref()
434 0 : .expect("spec must be set")
435 0 : .clone();
436 0 : let sk_connstrs: Vec<String> = pspec.safekeeper_connstrings.clone();
437 0 : let sk_configs = sk_connstrs.into_iter().map(|connstr| {
438 0 : // Format connstr
439 0 : let id = connstr.clone();
440 0 : let connstr = format!("postgresql://no_user@{}", connstr);
441 0 : let options = format!(
442 0 : "-c timeline_id={} tenant_id={}",
443 0 : pspec.timeline_id, pspec.tenant_id
444 0 : );
445 0 :
446 0 : // Construct client
447 0 : let mut config = tokio_postgres::Config::from_str(&connstr).unwrap();
448 0 : config.options(&options);
449 0 : if let Some(storage_auth_token) = pspec.storage_auth_token.clone() {
450 0 : config.password(storage_auth_token);
451 0 : }
452 :
453 0 : (id, config)
454 0 : });
455 0 :
456 0 : // Create task set to query all safekeepers
457 0 : let mut tasks = FuturesUnordered::new();
458 0 : let quorum = sk_configs.len() / 2 + 1;
459 0 : for (id, config) in sk_configs {
460 0 : let timeout = tokio::time::Duration::from_millis(100);
461 0 : let task = tokio::time::timeout(timeout, ping_safekeeper(id, config));
462 0 : tasks.push(tokio::spawn(task));
463 0 : }
464 :
465 : // Get a quorum of responses or errors
466 0 : let mut responses = Vec::new();
467 0 : let mut join_errors = Vec::new();
468 0 : let mut task_errors = Vec::new();
469 0 : let mut timeout_errors = Vec::new();
470 0 : while let Some(response) = tasks.next().await {
471 0 : match response {
472 0 : Ok(Ok(Ok(r))) => responses.push(r),
473 0 : Ok(Ok(Err(e))) => task_errors.push(e),
474 0 : Ok(Err(e)) => timeout_errors.push(e),
475 0 : Err(e) => join_errors.push(e),
476 : };
477 0 : if responses.len() >= quorum {
478 0 : break;
479 0 : }
480 0 : if join_errors.len() + task_errors.len() + timeout_errors.len() >= quorum {
481 0 : break;
482 0 : }
483 : }
484 :
485 : // In case of error, log and fail the check, but don't crash.
486 : // We're playing it safe because these errors could be transient
487 : // and we don't yet retry. Also being careful here allows us to
488 : // be backwards compatible with safekeepers that don't have the
489 : // TIMELINE_STATUS API yet.
490 0 : if responses.len() < quorum {
491 0 : error!(
492 0 : "failed sync safekeepers check {:?} {:?} {:?}",
493 : join_errors, task_errors, timeout_errors
494 : );
495 0 : return Ok(None);
496 0 : }
497 0 :
498 0 : Ok(check_if_synced(responses))
499 0 : }
500 :
501 : // Fast path for sync_safekeepers. If they're already synced we get the lsn
502 : // in one roundtrip. If not, we should do a full sync_safekeepers.
503 0 : pub fn check_safekeepers_synced(&self, compute_state: &ComputeState) -> Result<Option<Lsn>> {
504 0 : let start_time = Utc::now();
505 0 :
506 0 : // Run actual work with new tokio runtime
507 0 : let rt = tokio::runtime::Builder::new_current_thread()
508 0 : .enable_all()
509 0 : .build()
510 0 : .expect("failed to create rt");
511 0 : let result = rt.block_on(self.check_safekeepers_synced_async(compute_state));
512 0 :
513 0 : // Record runtime
514 0 : self.state.lock().unwrap().metrics.sync_sk_check_ms = Utc::now()
515 0 : .signed_duration_since(start_time)
516 0 : .to_std()
517 0 : .unwrap()
518 0 : .as_millis() as u64;
519 0 : result
520 0 : }
521 :
522 : // Run `postgres` in a special mode with `--sync-safekeepers` argument
523 : // and return the reported LSN back to the caller.
524 0 : #[instrument(skip_all)]
525 : pub fn sync_safekeepers(&self, storage_auth_token: Option<String>) -> Result<Lsn> {
526 : let start_time = Utc::now();
527 :
528 : let mut sync_handle = maybe_cgexec(&self.pgbin)
529 : .args(["--sync-safekeepers"])
530 : .env("PGDATA", &self.pgdata) // we cannot use -D in this mode
531 : .envs(if let Some(storage_auth_token) = &storage_auth_token {
532 : vec![("NEON_AUTH_TOKEN", storage_auth_token)]
533 : } else {
534 : vec![]
535 : })
536 : .stdout(Stdio::piped())
537 : .stderr(Stdio::piped())
538 : .spawn()
539 : .expect("postgres --sync-safekeepers failed to start");
540 : SYNC_SAFEKEEPERS_PID.store(sync_handle.id(), Ordering::SeqCst);
541 :
542 : // `postgres --sync-safekeepers` will print all log output to stderr and
543 : // final LSN to stdout. So we leave stdout to collect LSN, while stderr logs
544 : // will be collected in a child thread.
545 : let stderr = sync_handle
546 : .stderr
547 : .take()
548 : .expect("stderr should be captured");
549 : let logs_handle = handle_postgres_logs(stderr);
550 :
551 : let sync_output = sync_handle
552 : .wait_with_output()
553 : .expect("postgres --sync-safekeepers failed");
554 : SYNC_SAFEKEEPERS_PID.store(0, Ordering::SeqCst);
555 :
556 : // Process has exited, so we can join the logs thread.
557 : let _ = logs_handle
558 : .join()
559 0 : .map_err(|e| tracing::error!("log thread panicked: {:?}", e));
560 :
561 : if !sync_output.status.success() {
562 : anyhow::bail!(
563 : "postgres --sync-safekeepers exited with non-zero status: {}. stdout: {}",
564 : sync_output.status,
565 : String::from_utf8(sync_output.stdout)
566 : .expect("postgres --sync-safekeepers exited, and stdout is not utf-8"),
567 : );
568 : }
569 :
570 : self.state.lock().unwrap().metrics.sync_safekeepers_ms = Utc::now()
571 : .signed_duration_since(start_time)
572 : .to_std()
573 : .unwrap()
574 : .as_millis() as u64;
575 :
576 : let lsn = Lsn::from_str(String::from_utf8(sync_output.stdout)?.trim())?;
577 :
578 : Ok(lsn)
579 : }
580 :
581 : /// Do all the preparations like PGDATA directory creation, configuration,
582 : /// safekeepers sync, basebackup, etc.
583 0 : #[instrument(skip_all)]
584 : pub fn prepare_pgdata(
585 : &self,
586 : compute_state: &ComputeState,
587 : extension_server_port: u16,
588 : ) -> Result<()> {
589 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
590 : let spec = &pspec.spec;
591 : let pgdata_path = Path::new(&self.pgdata);
592 :
593 : // Remove/create an empty pgdata directory and put configuration there.
594 : self.create_pgdata()?;
595 : config::write_postgres_conf(
596 : &pgdata_path.join("postgresql.conf"),
597 : &pspec.spec,
598 : Some(extension_server_port),
599 : )?;
600 :
601 : // Syncing safekeepers is only safe with primary nodes: if a primary
602 : // is already connected it will be kicked out, so a secondary (standby)
603 : // cannot sync safekeepers.
604 : let lsn = match spec.mode {
605 : ComputeMode::Primary => {
606 : info!("checking if safekeepers are synced");
607 : let lsn = if let Ok(Some(lsn)) = self.check_safekeepers_synced(compute_state) {
608 : lsn
609 : } else {
610 : info!("starting safekeepers syncing");
611 : self.sync_safekeepers(pspec.storage_auth_token.clone())
612 0 : .with_context(|| "failed to sync safekeepers")?
613 : };
614 : info!("safekeepers synced at LSN {}", lsn);
615 : lsn
616 : }
617 : ComputeMode::Static(lsn) => {
618 : info!("Starting read-only node at static LSN {}", lsn);
619 : lsn
620 : }
621 : ComputeMode::Replica => {
622 : info!("Initializing standby from latest Pageserver LSN");
623 : Lsn(0)
624 : }
625 : };
626 :
627 : info!(
628 : "getting basebackup@{} from pageserver {}",
629 : lsn, &pspec.pageserver_connstr
630 : );
631 0 : self.get_basebackup(compute_state, lsn).with_context(|| {
632 0 : format!(
633 0 : "failed to get basebackup@{} from pageserver {}",
634 0 : lsn, &pspec.pageserver_connstr
635 0 : )
636 0 : })?;
637 :
638 : // Update pg_hba.conf received with basebackup.
639 : update_pg_hba(pgdata_path)?;
640 :
641 : // Place pg_dynshmem under /dev/shm. This allows us to use
642 : // 'dynamic_shared_memory_type = mmap' so that the files are placed in
643 : // /dev/shm, similar to how 'dynamic_shared_memory_type = posix' works.
644 : //
645 : // Why on earth don't we just stick to the 'posix' default, you might
646 : // ask. It turns out that making large allocations with 'posix' doesn't
647 : // work very well with autoscaling. The behavior we want is that:
648 : //
649 : // 1. You can make large DSM allocations, larger than the current RAM
650 : // size of the VM, without errors
651 : //
652 : // 2. If the allocated memory is really used, the VM is scaled up
653 : // automatically to accommodate that
654 : //
655 : // We try to make that possible by having swap in the VM. But with the
656 : // default 'posix' DSM implementation, we fail step 1, even when there's
657 : // plenty of swap available. PostgreSQL uses posix_fallocate() to create
658 : // the shmem segment, which is really just a file in /dev/shm in Linux,
659 : // but posix_fallocate() on tmpfs returns ENOMEM if the size is larger
660 : // than available RAM.
661 : //
662 : // Using 'dynamic_shared_memory_type = mmap' works around that, because
663 : // the Postgres 'mmap' DSM implementation doesn't use
664 : // posix_fallocate(). Instead, it uses repeated calls to write(2) to
665 : // fill the file with zeros. It's weird that that differs between
666 : // 'posix' and 'mmap', but we take advantage of it. When the file is
667 : // filled slowly with write(2), the kernel allows it to grow larger, as
668 : // long as there's swap available.
669 : //
670 : // In short, using 'dynamic_shared_memory_type = mmap' allows us one DSM
671 : // segment to be larger than currently available RAM. But because we
672 : // don't want to store it on a real file, which the kernel would try to
673 : // flush to disk, so symlink pg_dynshm to /dev/shm.
674 : //
675 : // We don't set 'dynamic_shared_memory_type = mmap' here, we let the
676 : // control plane control that option. If 'mmap' is not used, this
677 : // symlink doesn't affect anything.
678 : //
679 : // See https://github.com/neondatabase/autoscaling/issues/800
680 : std::fs::remove_dir(pgdata_path.join("pg_dynshmem"))?;
681 : symlink("/dev/shm/", pgdata_path.join("pg_dynshmem"))?;
682 :
683 : match spec.mode {
684 : ComputeMode::Primary => {}
685 : ComputeMode::Replica | ComputeMode::Static(..) => {
686 : add_standby_signal(pgdata_path)?;
687 : }
688 : }
689 :
690 : Ok(())
691 : }
692 :
693 : /// Start and stop a postgres process to warm up the VM for startup.
694 0 : pub fn prewarm_postgres(&self) -> Result<()> {
695 0 : info!("prewarming");
696 :
697 : // Create pgdata
698 0 : let pgdata = &format!("{}.warmup", self.pgdata);
699 0 : create_pgdata(pgdata)?;
700 :
701 : // Run initdb to completion
702 0 : info!("running initdb");
703 0 : let initdb_bin = Path::new(&self.pgbin).parent().unwrap().join("initdb");
704 0 : Command::new(initdb_bin)
705 0 : .args(["-D", pgdata])
706 0 : .output()
707 0 : .expect("cannot start initdb process");
708 0 :
709 0 : // Write conf
710 0 : use std::io::Write;
711 0 : let conf_path = Path::new(pgdata).join("postgresql.conf");
712 0 : let mut file = std::fs::File::create(conf_path)?;
713 0 : writeln!(file, "shared_buffers=65536")?;
714 0 : writeln!(file, "port=51055")?; // Nobody should be connecting
715 0 : writeln!(file, "shared_preload_libraries = 'neon'")?;
716 :
717 : // Start postgres
718 0 : info!("starting postgres");
719 0 : let mut pg = maybe_cgexec(&self.pgbin)
720 0 : .args(["-D", pgdata])
721 0 : .spawn()
722 0 : .expect("cannot start postgres process");
723 0 :
724 0 : // Stop it when it's ready
725 0 : info!("waiting for postgres");
726 0 : wait_for_postgres(&mut pg, Path::new(pgdata))?;
727 : // SIGQUIT orders postgres to exit immediately. We don't want to SIGKILL
728 : // it to avoid orphaned processes prowling around while datadir is
729 : // wiped.
730 0 : let pm_pid = Pid::from_raw(pg.id() as i32);
731 0 : kill(pm_pid, Signal::SIGQUIT)?;
732 0 : info!("sent SIGQUIT signal");
733 0 : pg.wait()?;
734 0 : info!("done prewarming");
735 :
736 : // clean up
737 0 : let _ok = fs::remove_dir_all(pgdata);
738 0 : Ok(())
739 0 : }
740 :
741 : /// Start Postgres as a child process and manage DBs/roles.
742 : /// After that this will hang waiting on the postmaster process to exit.
743 : /// Returns a handle to the child process and a handle to the logs thread.
744 0 : #[instrument(skip_all)]
745 : pub fn start_postgres(
746 : &self,
747 : storage_auth_token: Option<String>,
748 : ) -> Result<(std::process::Child, std::thread::JoinHandle<()>)> {
749 : let pgdata_path = Path::new(&self.pgdata);
750 :
751 : // Run postgres as a child process.
752 : let mut pg = maybe_cgexec(&self.pgbin)
753 : .args(["-D", &self.pgdata])
754 : .envs(if let Some(storage_auth_token) = &storage_auth_token {
755 : vec![("NEON_AUTH_TOKEN", storage_auth_token)]
756 : } else {
757 : vec![]
758 : })
759 : .stderr(Stdio::piped())
760 : .spawn()
761 : .expect("cannot start postgres process");
762 : PG_PID.store(pg.id(), Ordering::SeqCst);
763 :
764 : // Start a thread to collect logs from stderr.
765 : let stderr = pg.stderr.take().expect("stderr should be captured");
766 : let logs_handle = handle_postgres_logs(stderr);
767 :
768 : wait_for_postgres(&mut pg, pgdata_path)?;
769 :
770 : Ok((pg, logs_handle))
771 : }
772 :
773 : /// Do post configuration of the already started Postgres. This function spawns a background thread to
774 : /// configure the database after applying the compute spec. Currently, it upgrades the neon extension
775 : /// version. In the future, it may upgrade all 3rd-party extensions.
776 0 : #[instrument(skip_all)]
777 : pub fn post_apply_config(&self) -> Result<()> {
778 : let connstr = self.connstr.clone();
779 0 : thread::spawn(move || {
780 0 : let func = || {
781 0 : let mut client = Client::connect(connstr.as_str(), NoTls)?;
782 0 : handle_neon_extension_upgrade(&mut client)
783 0 : .context("handle_neon_extension_upgrade")?;
784 0 : Ok::<_, anyhow::Error>(())
785 0 : };
786 0 : if let Err(err) = func() {
787 0 : error!("error while post_apply_config: {err:#}");
788 0 : }
789 0 : });
790 : Ok(())
791 : }
792 :
793 : /// Do initial configuration of the already started Postgres.
794 0 : #[instrument(skip_all)]
795 : pub fn apply_config(&self, compute_state: &ComputeState) -> Result<()> {
796 : // If connection fails,
797 : // it may be the old node with `zenith_admin` superuser.
798 : //
799 : // In this case we need to connect with old `zenith_admin` name
800 : // and create new user. We cannot simply rename connected user,
801 : // but we can create a new one and grant it all privileges.
802 : let mut connstr = self.connstr.clone();
803 : connstr
804 : .query_pairs_mut()
805 : .append_pair("application_name", "apply_config");
806 :
807 : let mut client = match Client::connect(connstr.as_str(), NoTls) {
808 : Err(e) => match e.code() {
809 : Some(&SqlState::INVALID_PASSWORD)
810 : | Some(&SqlState::INVALID_AUTHORIZATION_SPECIFICATION) => {
811 : // connect with zenith_admin if cloud_admin could not authenticate
812 : info!(
813 : "cannot connect to postgres: {}, retrying with `zenith_admin` username",
814 : e
815 : );
816 : let mut zenith_admin_connstr = connstr.clone();
817 :
818 : zenith_admin_connstr
819 : .set_username("zenith_admin")
820 0 : .map_err(|_| anyhow::anyhow!("invalid connstr"))?;
821 :
822 : let mut client =
823 : Client::connect(zenith_admin_connstr.as_str(), NoTls)
824 : .context("broken cloud_admin credential: tried connecting with cloud_admin but could not authenticate, and zenith_admin does not work either")?;
825 : // Disable forwarding so that users don't get a cloud_admin role
826 :
827 0 : let mut func = || {
828 0 : client.simple_query("SET neon.forward_ddl = false")?;
829 0 : client.simple_query("CREATE USER cloud_admin WITH SUPERUSER")?;
830 0 : client.simple_query("GRANT zenith_admin TO cloud_admin")?;
831 0 : Ok::<_, anyhow::Error>(())
832 0 : };
833 : func().context("apply_config setup cloud_admin")?;
834 :
835 : drop(client);
836 :
837 : // reconnect with connstring with expected name
838 : Client::connect(connstr.as_str(), NoTls)?
839 : }
840 : _ => return Err(e.into()),
841 : },
842 : Ok(client) => client,
843 : };
844 :
845 : // Disable DDL forwarding because control plane already knows about these roles/databases.
846 : client
847 : .simple_query("SET neon.forward_ddl = false")
848 : .context("apply_config SET neon.forward_ddl = false")?;
849 :
850 : // Proceed with post-startup configuration. Note, that order of operations is important.
851 : let spec = &compute_state.pspec.as_ref().expect("spec must be set").spec;
852 : create_neon_superuser(spec, &mut client).context("apply_config create_neon_superuser")?;
853 : cleanup_instance(&mut client).context("apply_config cleanup_instance")?;
854 : handle_roles(spec, &mut client).context("apply_config handle_roles")?;
855 : handle_databases(spec, &mut client).context("apply_config handle_databases")?;
856 : handle_role_deletions(spec, connstr.as_str(), &mut client)
857 : .context("apply_config handle_role_deletions")?;
858 : handle_grants(
859 : spec,
860 : &mut client,
861 : connstr.as_str(),
862 : self.has_feature(ComputeFeature::AnonExtension),
863 : )
864 : .context("apply_config handle_grants")?;
865 : handle_extensions(spec, &mut client).context("apply_config handle_extensions")?;
866 : handle_extension_neon(&mut client).context("apply_config handle_extension_neon")?;
867 : create_availability_check_data(&mut client)
868 : .context("apply_config create_availability_check_data")?;
869 :
870 : // 'Close' connection
871 : drop(client);
872 :
873 : // Run migrations separately to not hold up cold starts
874 0 : thread::spawn(move || {
875 0 : let mut connstr = connstr.clone();
876 0 : connstr
877 0 : .query_pairs_mut()
878 0 : .append_pair("application_name", "migrations");
879 :
880 0 : let mut client = Client::connect(connstr.as_str(), NoTls)?;
881 0 : handle_migrations(&mut client).context("apply_config handle_migrations")
882 0 : });
883 : Ok(())
884 : }
885 :
886 : // Wrapped this around `pg_ctl reload`, but right now we don't use
887 : // `pg_ctl` for start / stop.
888 0 : #[instrument(skip_all)]
889 : fn pg_reload_conf(&self) -> Result<()> {
890 : let pgctl_bin = Path::new(&self.pgbin).parent().unwrap().join("pg_ctl");
891 : Command::new(pgctl_bin)
892 : .args(["reload", "-D", &self.pgdata])
893 : .output()
894 : .expect("cannot run pg_ctl process");
895 : Ok(())
896 : }
897 :
898 : /// Similar to `apply_config()`, but does a bit different sequence of operations,
899 : /// as it's used to reconfigure a previously started and configured Postgres node.
900 0 : #[instrument(skip_all)]
901 : pub fn reconfigure(&self) -> Result<()> {
902 : let spec = self.state.lock().unwrap().pspec.clone().unwrap().spec;
903 :
904 : if let Some(ref pgbouncer_settings) = spec.pgbouncer_settings {
905 : info!("tuning pgbouncer");
906 :
907 : let rt = tokio::runtime::Builder::new_current_thread()
908 : .enable_all()
909 : .build()
910 : .expect("failed to create rt");
911 :
912 : // Spawn a thread to do the tuning,
913 : // so that we don't block the main thread that starts Postgres.
914 : let pgbouncer_settings = pgbouncer_settings.clone();
915 0 : let _handle = thread::spawn(move || {
916 0 : let res = rt.block_on(tune_pgbouncer(pgbouncer_settings));
917 0 : if let Err(err) = res {
918 0 : error!("error while tuning pgbouncer: {err:?}");
919 0 : }
920 0 : });
921 : }
922 :
923 : // Write new config
924 : let pgdata_path = Path::new(&self.pgdata);
925 : let postgresql_conf_path = pgdata_path.join("postgresql.conf");
926 : config::write_postgres_conf(&postgresql_conf_path, &spec, None)?;
927 : // temporarily reset max_cluster_size in config
928 : // to avoid the possibility of hitting the limit, while we are reconfiguring:
929 : // creating new extensions, roles, etc...
930 0 : config::with_compute_ctl_tmp_override(pgdata_path, "neon.max_cluster_size=-1", || {
931 0 : self.pg_reload_conf()?;
932 :
933 0 : let mut client = Client::connect(self.connstr.as_str(), NoTls)?;
934 :
935 : // Proceed with post-startup configuration. Note, that order of operations is important.
936 : // Disable DDL forwarding because control plane already knows about these roles/databases.
937 0 : if spec.mode == ComputeMode::Primary {
938 0 : client.simple_query("SET neon.forward_ddl = false")?;
939 0 : cleanup_instance(&mut client)?;
940 0 : handle_roles(&spec, &mut client)?;
941 0 : handle_databases(&spec, &mut client)?;
942 0 : handle_role_deletions(&spec, self.connstr.as_str(), &mut client)?;
943 0 : handle_grants(
944 0 : &spec,
945 0 : &mut client,
946 0 : self.connstr.as_str(),
947 0 : self.has_feature(ComputeFeature::AnonExtension),
948 0 : )?;
949 0 : handle_extensions(&spec, &mut client)?;
950 0 : handle_extension_neon(&mut client)?;
951 : // We can skip handle_migrations here because a new migration can only appear
952 : // if we have a new version of the compute_ctl binary, which can only happen
953 : // if compute got restarted, in which case we'll end up inside of apply_config
954 : // instead of reconfigure.
955 0 : }
956 :
957 : // 'Close' connection
958 0 : drop(client);
959 0 :
960 0 : Ok(())
961 0 : })?;
962 :
963 : self.pg_reload_conf()?;
964 :
965 : let unknown_op = "unknown".to_string();
966 : let op_id = spec.operation_uuid.as_ref().unwrap_or(&unknown_op);
967 : info!(
968 : "finished reconfiguration of compute node for operation {}",
969 : op_id
970 : );
971 :
972 : Ok(())
973 : }
974 :
975 0 : #[instrument(skip_all)]
976 : pub fn start_compute(
977 : &self,
978 : extension_server_port: u16,
979 : ) -> Result<(std::process::Child, std::thread::JoinHandle<()>)> {
980 : let compute_state = self.state.lock().unwrap().clone();
981 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
982 : info!(
983 : "starting compute for project {}, operation {}, tenant {}, timeline {}",
984 : pspec.spec.cluster.cluster_id.as_deref().unwrap_or("None"),
985 : pspec.spec.operation_uuid.as_deref().unwrap_or("None"),
986 : pspec.tenant_id,
987 : pspec.timeline_id,
988 : );
989 :
990 : // tune pgbouncer
991 : if let Some(pgbouncer_settings) = &pspec.spec.pgbouncer_settings {
992 : info!("tuning pgbouncer");
993 :
994 : let rt = tokio::runtime::Builder::new_current_thread()
995 : .enable_all()
996 : .build()
997 : .expect("failed to create rt");
998 :
999 : // Spawn a thread to do the tuning,
1000 : // so that we don't block the main thread that starts Postgres.
1001 : let pgbouncer_settings = pgbouncer_settings.clone();
1002 0 : let _handle = thread::spawn(move || {
1003 0 : let res = rt.block_on(tune_pgbouncer(pgbouncer_settings));
1004 0 : if let Err(err) = res {
1005 0 : error!("error while tuning pgbouncer: {err:?}");
1006 0 : }
1007 0 : });
1008 : }
1009 :
1010 : info!(
1011 : "start_compute spec.remote_extensions {:?}",
1012 : pspec.spec.remote_extensions
1013 : );
1014 :
1015 : // This part is sync, because we need to download
1016 : // remote shared_preload_libraries before postgres start (if any)
1017 : if let Some(remote_extensions) = &pspec.spec.remote_extensions {
1018 : // First, create control files for all availale extensions
1019 : extension_server::create_control_files(remote_extensions, &self.pgbin);
1020 :
1021 : let library_load_start_time = Utc::now();
1022 : let remote_ext_metrics = self.prepare_preload_libraries(&pspec.spec)?;
1023 :
1024 : let library_load_time = Utc::now()
1025 : .signed_duration_since(library_load_start_time)
1026 : .to_std()
1027 : .unwrap()
1028 : .as_millis() as u64;
1029 : let mut state = self.state.lock().unwrap();
1030 : state.metrics.load_ext_ms = library_load_time;
1031 : state.metrics.num_ext_downloaded = remote_ext_metrics.num_ext_downloaded;
1032 : state.metrics.largest_ext_size = remote_ext_metrics.largest_ext_size;
1033 : state.metrics.total_ext_download_size = remote_ext_metrics.total_ext_download_size;
1034 : info!(
1035 : "Loading shared_preload_libraries took {:?}ms",
1036 : library_load_time
1037 : );
1038 : info!("{:?}", remote_ext_metrics);
1039 : }
1040 :
1041 : self.prepare_pgdata(&compute_state, extension_server_port)?;
1042 :
1043 : let start_time = Utc::now();
1044 : let pg_process = self.start_postgres(pspec.storage_auth_token.clone())?;
1045 :
1046 : let config_time = Utc::now();
1047 : if pspec.spec.mode == ComputeMode::Primary {
1048 : if !pspec.spec.skip_pg_catalog_updates {
1049 : let pgdata_path = Path::new(&self.pgdata);
1050 : // temporarily reset max_cluster_size in config
1051 : // to avoid the possibility of hitting the limit, while we are applying config:
1052 : // creating new extensions, roles, etc...
1053 : config::with_compute_ctl_tmp_override(
1054 : pgdata_path,
1055 : "neon.max_cluster_size=-1",
1056 0 : || {
1057 0 : self.pg_reload_conf()?;
1058 :
1059 0 : self.apply_config(&compute_state)?;
1060 :
1061 0 : Ok(())
1062 0 : },
1063 : )?;
1064 : self.pg_reload_conf()?;
1065 : }
1066 : self.post_apply_config()?;
1067 : }
1068 :
1069 : let startup_end_time = Utc::now();
1070 : {
1071 : let mut state = self.state.lock().unwrap();
1072 : state.metrics.start_postgres_ms = config_time
1073 : .signed_duration_since(start_time)
1074 : .to_std()
1075 : .unwrap()
1076 : .as_millis() as u64;
1077 : state.metrics.config_ms = startup_end_time
1078 : .signed_duration_since(config_time)
1079 : .to_std()
1080 : .unwrap()
1081 : .as_millis() as u64;
1082 : state.metrics.total_startup_ms = startup_end_time
1083 : .signed_duration_since(compute_state.start_time)
1084 : .to_std()
1085 : .unwrap()
1086 : .as_millis() as u64;
1087 : }
1088 : self.set_status(ComputeStatus::Running);
1089 :
1090 : info!(
1091 : "finished configuration of compute for project {}",
1092 : pspec.spec.cluster.cluster_id.as_deref().unwrap_or("None")
1093 : );
1094 :
1095 : // Log metrics so that we can search for slow operations in logs
1096 : let metrics = {
1097 : let state = self.state.lock().unwrap();
1098 : state.metrics.clone()
1099 : };
1100 : info!(?metrics, "compute start finished");
1101 :
1102 : Ok(pg_process)
1103 : }
1104 :
1105 : /// Update the `last_active` in the shared state, but ensure that it's a more recent one.
1106 0 : pub fn update_last_active(&self, last_active: Option<DateTime<Utc>>) {
1107 0 : let mut state = self.state.lock().unwrap();
1108 0 : // NB: `Some(<DateTime>)` is always greater than `None`.
1109 0 : if last_active > state.last_active {
1110 0 : state.last_active = last_active;
1111 0 : debug!("set the last compute activity time to: {:?}", last_active);
1112 0 : }
1113 0 : }
1114 :
1115 : // Look for core dumps and collect backtraces.
1116 : //
1117 : // EKS worker nodes have following core dump settings:
1118 : // /proc/sys/kernel/core_pattern -> core
1119 : // /proc/sys/kernel/core_uses_pid -> 1
1120 : // ulimit -c -> unlimited
1121 : // which results in core dumps being written to postgres data directory as core.<pid>.
1122 : //
1123 : // Use that as a default location and pattern, except macos where core dumps are written
1124 : // to /cores/ directory by default.
1125 0 : pub fn check_for_core_dumps(&self) -> Result<()> {
1126 0 : let core_dump_dir = match std::env::consts::OS {
1127 0 : "macos" => Path::new("/cores/"),
1128 0 : _ => Path::new(&self.pgdata),
1129 : };
1130 :
1131 : // Collect core dump paths if any
1132 0 : info!("checking for core dumps in {}", core_dump_dir.display());
1133 0 : let files = fs::read_dir(core_dump_dir)?;
1134 0 : let cores = files.filter_map(|entry| {
1135 0 : let entry = entry.ok()?;
1136 0 : let _ = entry.file_name().to_str()?.strip_prefix("core.")?;
1137 0 : Some(entry.path())
1138 0 : });
1139 :
1140 : // Print backtrace for each core dump
1141 0 : for core_path in cores {
1142 0 : warn!(
1143 0 : "core dump found: {}, collecting backtrace",
1144 0 : core_path.display()
1145 : );
1146 :
1147 : // Try first with gdb
1148 0 : let backtrace = Command::new("gdb")
1149 0 : .args(["--batch", "-q", "-ex", "bt", &self.pgbin])
1150 0 : .arg(&core_path)
1151 0 : .output();
1152 :
1153 : // Try lldb if no gdb is found -- that is handy for local testing on macOS
1154 0 : let backtrace = match backtrace {
1155 0 : Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
1156 0 : warn!("cannot find gdb, trying lldb");
1157 0 : Command::new("lldb")
1158 0 : .arg("-c")
1159 0 : .arg(&core_path)
1160 0 : .args(["--batch", "-o", "bt all", "-o", "quit"])
1161 0 : .output()
1162 : }
1163 0 : _ => backtrace,
1164 0 : }?;
1165 :
1166 0 : warn!(
1167 0 : "core dump backtrace: {}",
1168 0 : String::from_utf8_lossy(&backtrace.stdout)
1169 : );
1170 0 : warn!(
1171 0 : "debugger stderr: {}",
1172 0 : String::from_utf8_lossy(&backtrace.stderr)
1173 : );
1174 : }
1175 :
1176 0 : Ok(())
1177 0 : }
1178 :
1179 : /// Select `pg_stat_statements` data and return it as a stringified JSON
1180 0 : pub async fn collect_insights(&self) -> String {
1181 0 : let mut result_rows: Vec<String> = Vec::new();
1182 0 : let connect_result = tokio_postgres::connect(self.connstr.as_str(), NoTls).await;
1183 0 : let (client, connection) = connect_result.unwrap();
1184 0 : tokio::spawn(async move {
1185 0 : if let Err(e) = connection.await {
1186 0 : eprintln!("connection error: {}", e);
1187 0 : }
1188 0 : });
1189 0 : let result = client
1190 0 : .simple_query(
1191 0 : "SELECT
1192 0 : row_to_json(pg_stat_statements)
1193 0 : FROM
1194 0 : pg_stat_statements
1195 0 : WHERE
1196 0 : userid != 'cloud_admin'::regrole::oid
1197 0 : ORDER BY
1198 0 : (mean_exec_time + mean_plan_time) DESC
1199 0 : LIMIT 100",
1200 0 : )
1201 0 : .await;
1202 :
1203 0 : if let Ok(raw_rows) = result {
1204 0 : for message in raw_rows.iter() {
1205 0 : if let postgres::SimpleQueryMessage::Row(row) = message {
1206 0 : if let Some(json) = row.get(0) {
1207 0 : result_rows.push(json.to_string());
1208 0 : }
1209 0 : }
1210 : }
1211 :
1212 0 : format!("{{\"pg_stat_statements\": [{}]}}", result_rows.join(","))
1213 : } else {
1214 0 : "{{\"pg_stat_statements\": []}}".to_string()
1215 : }
1216 0 : }
1217 :
1218 : // download an archive, unzip and place files in correct locations
1219 0 : pub async fn download_extension(
1220 0 : &self,
1221 0 : real_ext_name: String,
1222 0 : ext_path: RemotePath,
1223 0 : ) -> Result<u64, DownloadError> {
1224 0 : let ext_remote_storage =
1225 0 : self.ext_remote_storage
1226 0 : .as_ref()
1227 0 : .ok_or(DownloadError::BadInput(anyhow::anyhow!(
1228 0 : "Remote extensions storage is not configured",
1229 0 : )))?;
1230 :
1231 0 : let ext_archive_name = ext_path.object_name().expect("bad path");
1232 0 :
1233 0 : let mut first_try = false;
1234 0 : if !self
1235 0 : .ext_download_progress
1236 0 : .read()
1237 0 : .expect("lock err")
1238 0 : .contains_key(ext_archive_name)
1239 0 : {
1240 0 : self.ext_download_progress
1241 0 : .write()
1242 0 : .expect("lock err")
1243 0 : .insert(ext_archive_name.to_string(), (Utc::now(), false));
1244 0 : first_try = true;
1245 0 : }
1246 0 : let (download_start, download_completed) =
1247 0 : self.ext_download_progress.read().expect("lock err")[ext_archive_name];
1248 0 : let start_time_delta = Utc::now()
1249 0 : .signed_duration_since(download_start)
1250 0 : .to_std()
1251 0 : .unwrap()
1252 0 : .as_millis() as u64;
1253 0 :
1254 0 : // how long to wait for extension download if it was started by another process
1255 0 : const HANG_TIMEOUT: u64 = 3000; // milliseconds
1256 0 :
1257 0 : if download_completed {
1258 0 : info!("extension already downloaded, skipping re-download");
1259 0 : return Ok(0);
1260 0 : } else if start_time_delta < HANG_TIMEOUT && !first_try {
1261 0 : info!("download {ext_archive_name} already started by another process, hanging untill completion or timeout");
1262 0 : let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(500));
1263 0 : loop {
1264 0 : info!("waiting for download");
1265 0 : interval.tick().await;
1266 0 : let (_, download_completed_now) =
1267 0 : self.ext_download_progress.read().expect("lock")[ext_archive_name];
1268 0 : if download_completed_now {
1269 0 : info!("download finished by whoever else downloaded it");
1270 0 : return Ok(0);
1271 0 : }
1272 : }
1273 : // NOTE: the above loop will get terminated
1274 : // based on the timeout of the download function
1275 0 : }
1276 0 :
1277 0 : // if extension hasn't been downloaded before or the previous
1278 0 : // attempt to download was at least HANG_TIMEOUT ms ago
1279 0 : // then we try to download it here
1280 0 : info!("downloading new extension {ext_archive_name}");
1281 :
1282 0 : let download_size = extension_server::download_extension(
1283 0 : &real_ext_name,
1284 0 : &ext_path,
1285 0 : ext_remote_storage,
1286 0 : &self.pgbin,
1287 0 : )
1288 0 : .await
1289 0 : .map_err(DownloadError::Other);
1290 0 :
1291 0 : if download_size.is_ok() {
1292 0 : self.ext_download_progress
1293 0 : .write()
1294 0 : .expect("bad lock")
1295 0 : .insert(ext_archive_name.to_string(), (download_start, true));
1296 0 : }
1297 :
1298 0 : download_size
1299 0 : }
1300 :
1301 : #[tokio::main]
1302 0 : pub async fn prepare_preload_libraries(
1303 0 : &self,
1304 0 : spec: &ComputeSpec,
1305 0 : ) -> Result<RemoteExtensionMetrics> {
1306 0 : if self.ext_remote_storage.is_none() {
1307 0 : return Ok(RemoteExtensionMetrics {
1308 0 : num_ext_downloaded: 0,
1309 0 : largest_ext_size: 0,
1310 0 : total_ext_download_size: 0,
1311 0 : });
1312 0 : }
1313 0 : let remote_extensions = spec
1314 0 : .remote_extensions
1315 0 : .as_ref()
1316 0 : .ok_or(anyhow::anyhow!("Remote extensions are not configured"))?;
1317 0 :
1318 0 : info!("parse shared_preload_libraries from spec.cluster.settings");
1319 0 : let mut libs_vec = Vec::new();
1320 0 : if let Some(libs) = spec.cluster.settings.find("shared_preload_libraries") {
1321 0 : libs_vec = libs
1322 0 : .split(&[',', '\'', ' '])
1323 0 : .filter(|s| *s != "neon" && !s.is_empty())
1324 0 : .map(str::to_string)
1325 0 : .collect();
1326 0 : }
1327 0 : info!("parse shared_preload_libraries from provided postgresql.conf");
1328 0 :
1329 0 : // that is used in neon_local and python tests
1330 0 : if let Some(conf) = &spec.cluster.postgresql_conf {
1331 0 : let conf_lines = conf.split('\n').collect::<Vec<&str>>();
1332 0 : let mut shared_preload_libraries_line = "";
1333 0 : for line in conf_lines {
1334 0 : if line.starts_with("shared_preload_libraries") {
1335 0 : shared_preload_libraries_line = line;
1336 0 : }
1337 0 : }
1338 0 : let mut preload_libs_vec = Vec::new();
1339 0 : if let Some(libs) = shared_preload_libraries_line.split("='").nth(1) {
1340 0 : preload_libs_vec = libs
1341 0 : .split(&[',', '\'', ' '])
1342 0 : .filter(|s| *s != "neon" && !s.is_empty())
1343 0 : .map(str::to_string)
1344 0 : .collect();
1345 0 : }
1346 0 : libs_vec.extend(preload_libs_vec);
1347 0 : }
1348 0 :
1349 0 : // Don't try to download libraries that are not in the index.
1350 0 : // Assume that they are already present locally.
1351 0 : libs_vec.retain(|lib| remote_extensions.library_index.contains_key(lib));
1352 0 :
1353 0 : info!("Downloading to shared preload libraries: {:?}", &libs_vec);
1354 0 :
1355 0 : let mut download_tasks = Vec::new();
1356 0 : for library in &libs_vec {
1357 0 : let (ext_name, ext_path) =
1358 0 : remote_extensions.get_ext(library, true, &self.build_tag, &self.pgversion)?;
1359 0 : download_tasks.push(self.download_extension(ext_name, ext_path));
1360 0 : }
1361 0 : let results = join_all(download_tasks).await;
1362 0 :
1363 0 : let mut remote_ext_metrics = RemoteExtensionMetrics {
1364 0 : num_ext_downloaded: 0,
1365 0 : largest_ext_size: 0,
1366 0 : total_ext_download_size: 0,
1367 0 : };
1368 0 : for result in results {
1369 0 : let download_size = match result {
1370 0 : Ok(res) => {
1371 0 : remote_ext_metrics.num_ext_downloaded += 1;
1372 0 : res
1373 0 : }
1374 0 : Err(err) => {
1375 0 : // if we failed to download an extension, we don't want to fail the whole
1376 0 : // process, but we do want to log the error
1377 0 : error!("Failed to download extension: {}", err);
1378 0 : 0
1379 0 : }
1380 0 : };
1381 0 :
1382 0 : remote_ext_metrics.largest_ext_size =
1383 0 : std::cmp::max(remote_ext_metrics.largest_ext_size, download_size);
1384 0 : remote_ext_metrics.total_ext_download_size += download_size;
1385 0 : }
1386 0 : Ok(remote_ext_metrics)
1387 0 : }
1388 : }
1389 :
1390 0 : pub fn forward_termination_signal() {
1391 0 : let ss_pid = SYNC_SAFEKEEPERS_PID.load(Ordering::SeqCst);
1392 0 : if ss_pid != 0 {
1393 0 : let ss_pid = nix::unistd::Pid::from_raw(ss_pid as i32);
1394 0 : kill(ss_pid, Signal::SIGTERM).ok();
1395 0 : }
1396 0 : let pg_pid = PG_PID.load(Ordering::SeqCst);
1397 0 : if pg_pid != 0 {
1398 0 : let pg_pid = nix::unistd::Pid::from_raw(pg_pid as i32);
1399 0 : // Use 'fast' shutdown (SIGINT) because it also creates a shutdown checkpoint, which is important for
1400 0 : // ROs to get a list of running xacts faster instead of going through the CLOG.
1401 0 : // See https://www.postgresql.org/docs/current/server-shutdown.html for the list of modes and signals.
1402 0 : kill(pg_pid, Signal::SIGINT).ok();
1403 0 : }
1404 0 : }
|