Line data Source code
1 : //!
2 : //! Postgres wrapper (`compute_ctl`) is intended to be run as a Docker entrypoint or as a `systemd`
3 : //! `ExecStart` option. It will handle all the `Neon` specifics during compute node
4 : //! initialization:
5 : //! - `compute_ctl` accepts cluster (compute node) specification as a JSON file.
6 : //! - Every start is a fresh start, so the data directory is removed and
7 : //! initialized again on each run.
8 : //! - If remote_extension_config is provided, it will be used to fetch extensions list
9 : //! and download `shared_preload_libraries` from the remote storage.
10 : //! - Next it will put configuration files into the `PGDATA` directory.
11 : //! - Sync safekeepers and get commit LSN.
12 : //! - Get `basebackup` from pageserver using the returned on the previous step LSN.
13 : //! - Try to start `postgres` and wait until it is ready to accept connections.
14 : //! - Check and alter/drop/create roles and databases.
15 : //! - Hang waiting on the `postmaster` process to exit.
16 : //!
17 : //! Also `compute_ctl` spawns two separate service threads:
18 : //! - `compute-monitor` checks the last Postgres activity timestamp and saves it
19 : //! into the shared `ComputeNode`;
20 : //! - `http-endpoint` runs a Hyper HTTP API server, which serves readiness and the
21 : //! last activity requests.
22 : //!
23 : //! If `AUTOSCALING` environment variable is set, `compute_ctl` will start the
24 : //! `vm-monitor` located in [`neon/libs/vm_monitor`]. For VM compute nodes,
25 : //! `vm-monitor` communicates with the VM autoscaling system. It coordinates
26 : //! downscaling and requests immediate upscaling under resource pressure.
27 : //!
28 : //! Usage example:
29 : //! ```sh
30 : //! compute_ctl -D /var/db/postgres/compute \
31 : //! -C 'postgresql://cloud_admin@localhost/postgres' \
32 : //! -S /var/db/postgres/specs/current.json \
33 : //! -b /usr/local/bin/postgres \
34 : //! -r http://pg-ext-s3-gateway \
35 : //! ```
36 : use std::collections::HashMap;
37 : use std::fs::File;
38 : use std::path::Path;
39 : use std::process::exit;
40 : use std::str::FromStr;
41 : use std::sync::atomic::Ordering;
42 : use std::sync::{mpsc, Arc, Condvar, Mutex, RwLock};
43 : use std::{thread, time::Duration};
44 :
45 : use anyhow::{Context, Result};
46 : use chrono::Utc;
47 : use clap::Arg;
48 : use compute_tools::disk_quota::set_disk_quota;
49 : use compute_tools::lsn_lease::launch_lsn_lease_bg_task_for_static;
50 : use signal_hook::consts::{SIGQUIT, SIGTERM};
51 : use signal_hook::{consts::SIGINT, iterator::Signals};
52 : use tracing::{error, info, warn};
53 : use url::Url;
54 :
55 : use compute_api::responses::ComputeStatus;
56 : use compute_api::spec::ComputeSpec;
57 :
58 : use compute_tools::compute::{
59 : forward_termination_signal, ComputeNode, ComputeState, ParsedSpec, PG_PID,
60 : };
61 : use compute_tools::configurator::launch_configurator;
62 : use compute_tools::extension_server::get_pg_version_string;
63 : use compute_tools::http::api::launch_http_server;
64 : use compute_tools::logger::*;
65 : use compute_tools::monitor::launch_monitor;
66 : use compute_tools::params::*;
67 : use compute_tools::spec::*;
68 : use compute_tools::swap::resize_swap;
69 : use rlimit::{setrlimit, Resource};
70 :
71 : // this is an arbitrary build tag. Fine as a default / for testing purposes
72 : // in-case of not-set environment var
73 : const BUILD_TAG_DEFAULT: &str = "latest";
74 :
75 0 : fn main() -> Result<()> {
76 0 : let (build_tag, clap_args) = init()?;
77 :
78 : // enable core dumping for all child processes
79 0 : setrlimit(Resource::CORE, rlimit::INFINITY, rlimit::INFINITY)?;
80 :
81 0 : let (pg_handle, start_pg_result) = {
82 : // Enter startup tracing context
83 0 : let _startup_context_guard = startup_context_from_env();
84 :
85 0 : let cli_args = process_cli(&clap_args)?;
86 :
87 0 : let cli_spec = try_spec_from_cli(&clap_args, &cli_args)?;
88 :
89 0 : let wait_spec_result = wait_spec(build_tag, cli_args, cli_spec)?;
90 :
91 0 : start_postgres(&clap_args, wait_spec_result)?
92 :
93 : // Startup is finished, exit the startup tracing span
94 : };
95 :
96 : // PostgreSQL is now running, if startup was successful. Wait until it exits.
97 0 : let wait_pg_result = wait_postgres(pg_handle)?;
98 :
99 0 : let delay_exit = cleanup_after_postgres_exit(start_pg_result)?;
100 :
101 0 : maybe_delay_exit(delay_exit);
102 0 :
103 0 : deinit_and_exit(wait_pg_result);
104 0 : }
105 :
106 0 : fn init() -> Result<(String, clap::ArgMatches)> {
107 0 : init_tracing_and_logging(DEFAULT_LOG_LEVEL)?;
108 :
109 0 : opentelemetry::global::set_error_handler(|err| {
110 0 : tracing::info!("OpenTelemetry error: {err}");
111 0 : })
112 0 : .expect("global error handler lock poisoned");
113 :
114 0 : let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
115 0 : thread::spawn(move || {
116 0 : for sig in signals.forever() {
117 0 : handle_exit_signal(sig);
118 0 : }
119 0 : });
120 0 :
121 0 : let build_tag = option_env!("BUILD_TAG")
122 0 : .unwrap_or(BUILD_TAG_DEFAULT)
123 0 : .to_string();
124 0 : info!("build_tag: {build_tag}");
125 :
126 0 : Ok((build_tag, cli().get_matches()))
127 0 : }
128 :
129 0 : fn process_cli(matches: &clap::ArgMatches) -> Result<ProcessCliResult> {
130 0 : let pgbin_default = "postgres";
131 0 : let pgbin = matches
132 0 : .get_one::<String>("pgbin")
133 0 : .map(|s| s.as_str())
134 0 : .unwrap_or(pgbin_default);
135 0 :
136 0 : let ext_remote_storage = matches
137 0 : .get_one::<String>("remote-ext-config")
138 0 : // Compatibility hack: if the control plane specified any remote-ext-config
139 0 : // use the default value for extension storage proxy gateway.
140 0 : // Remove this once the control plane is updated to pass the gateway URL
141 0 : .map(|conf| {
142 0 : if conf.starts_with("http") {
143 0 : conf.trim_end_matches('/')
144 : } else {
145 0 : "http://pg-ext-s3-gateway"
146 : }
147 0 : });
148 0 :
149 0 : let http_port = *matches
150 0 : .get_one::<u16>("http-port")
151 0 : .expect("http-port is required");
152 0 : let pgdata = matches
153 0 : .get_one::<String>("pgdata")
154 0 : .expect("PGDATA path is required");
155 0 : let connstr = matches
156 0 : .get_one::<String>("connstr")
157 0 : .expect("Postgres connection string is required");
158 0 : let spec_json = matches.get_one::<String>("spec");
159 0 : let spec_path = matches.get_one::<String>("spec-path");
160 0 : let resize_swap_on_bind = matches.get_flag("resize-swap-on-bind");
161 0 : let set_disk_quota_for_fs = matches.get_one::<String>("set-disk-quota-for-fs");
162 0 :
163 0 : Ok(ProcessCliResult {
164 0 : connstr,
165 0 : pgdata,
166 0 : pgbin,
167 0 : ext_remote_storage,
168 0 : http_port,
169 0 : spec_json,
170 0 : spec_path,
171 0 : resize_swap_on_bind,
172 0 : set_disk_quota_for_fs,
173 0 : })
174 0 : }
175 :
176 : struct ProcessCliResult<'clap> {
177 : connstr: &'clap str,
178 : pgdata: &'clap str,
179 : pgbin: &'clap str,
180 : ext_remote_storage: Option<&'clap str>,
181 : http_port: u16,
182 : spec_json: Option<&'clap String>,
183 : spec_path: Option<&'clap String>,
184 : resize_swap_on_bind: bool,
185 : set_disk_quota_for_fs: Option<&'clap String>,
186 : }
187 :
188 0 : fn startup_context_from_env() -> Option<opentelemetry::ContextGuard> {
189 0 : // Extract OpenTelemetry context for the startup actions from the
190 0 : // TRACEPARENT and TRACESTATE env variables, and attach it to the current
191 0 : // tracing context.
192 0 : //
193 0 : // This is used to propagate the context for the 'start_compute' operation
194 0 : // from the neon control plane. This allows linking together the wider
195 0 : // 'start_compute' operation that creates the compute container, with the
196 0 : // startup actions here within the container.
197 0 : //
198 0 : // There is no standard for passing context in env variables, but a lot of
199 0 : // tools use TRACEPARENT/TRACESTATE, so we use that convention too. See
200 0 : // https://github.com/open-telemetry/opentelemetry-specification/issues/740
201 0 : //
202 0 : // Switch to the startup context here, and exit it once the startup has
203 0 : // completed and Postgres is up and running.
204 0 : //
205 0 : // If this pod is pre-created without binding it to any particular endpoint
206 0 : // yet, this isn't the right place to enter the startup context. In that
207 0 : // case, the control plane should pass the tracing context as part of the
208 0 : // /configure API call.
209 0 : //
210 0 : // NOTE: This is supposed to only cover the *startup* actions. Once
211 0 : // postgres is configured and up-and-running, we exit this span. Any other
212 0 : // actions that are performed on incoming HTTP requests, for example, are
213 0 : // performed in separate spans.
214 0 : //
215 0 : // XXX: If the pod is restarted, we perform the startup actions in the same
216 0 : // context as the original startup actions, which probably doesn't make
217 0 : // sense.
218 0 : let mut startup_tracing_carrier: HashMap<String, String> = HashMap::new();
219 0 : if let Ok(val) = std::env::var("TRACEPARENT") {
220 0 : startup_tracing_carrier.insert("traceparent".to_string(), val);
221 0 : }
222 0 : if let Ok(val) = std::env::var("TRACESTATE") {
223 0 : startup_tracing_carrier.insert("tracestate".to_string(), val);
224 0 : }
225 0 : if !startup_tracing_carrier.is_empty() {
226 : use opentelemetry::propagation::TextMapPropagator;
227 : use opentelemetry_sdk::propagation::TraceContextPropagator;
228 0 : let guard = TraceContextPropagator::new()
229 0 : .extract(&startup_tracing_carrier)
230 0 : .attach();
231 0 : info!("startup tracing context attached");
232 0 : Some(guard)
233 : } else {
234 0 : None
235 : }
236 0 : }
237 :
238 0 : fn try_spec_from_cli(
239 0 : matches: &clap::ArgMatches,
240 0 : ProcessCliResult {
241 0 : spec_json,
242 0 : spec_path,
243 0 : ..
244 0 : }: &ProcessCliResult,
245 0 : ) -> Result<CliSpecParams> {
246 0 : let compute_id = matches.get_one::<String>("compute-id");
247 0 : let control_plane_uri = matches.get_one::<String>("control-plane-uri");
248 :
249 : // First, try to get cluster spec from the cli argument
250 0 : if let Some(spec_json) = spec_json {
251 0 : info!("got spec from cli argument {}", spec_json);
252 : return Ok(CliSpecParams {
253 0 : spec: Some(serde_json::from_str(spec_json)?),
254 : live_config_allowed: false,
255 : });
256 0 : }
257 :
258 : // Second, try to read it from the file if path is provided
259 0 : if let Some(spec_path) = spec_path {
260 0 : let file = File::open(Path::new(spec_path))?;
261 : return Ok(CliSpecParams {
262 0 : spec: Some(serde_json::from_reader(file)?),
263 : live_config_allowed: true,
264 : });
265 0 : }
266 :
267 0 : let Some(compute_id) = compute_id else {
268 0 : panic!(
269 0 : "compute spec should be provided by one of the following ways: \
270 0 : --spec OR --spec-path OR --control-plane-uri and --compute-id"
271 0 : );
272 : };
273 0 : let Some(control_plane_uri) = control_plane_uri else {
274 0 : panic!("must specify both --control-plane-uri and --compute-id or none");
275 : };
276 :
277 0 : match get_spec_from_control_plane(control_plane_uri, compute_id) {
278 0 : Ok(spec) => Ok(CliSpecParams {
279 0 : spec,
280 0 : live_config_allowed: true,
281 0 : }),
282 0 : Err(e) => {
283 0 : error!(
284 0 : "cannot get response from control plane: {}\n\
285 0 : neither spec nor confirmation that compute is in the Empty state was received",
286 : e
287 : );
288 0 : Err(e)
289 : }
290 : }
291 0 : }
292 :
293 : struct CliSpecParams {
294 : /// If a spec was provided via CLI or file, the [`ComputeSpec`]
295 : spec: Option<ComputeSpec>,
296 : live_config_allowed: bool,
297 : }
298 :
299 0 : fn wait_spec(
300 0 : build_tag: String,
301 0 : ProcessCliResult {
302 0 : connstr,
303 0 : pgdata,
304 0 : pgbin,
305 0 : ext_remote_storage,
306 0 : resize_swap_on_bind,
307 0 : set_disk_quota_for_fs,
308 0 : http_port,
309 0 : ..
310 0 : }: ProcessCliResult,
311 0 : CliSpecParams {
312 0 : spec,
313 0 : live_config_allowed,
314 0 : }: CliSpecParams,
315 0 : ) -> Result<WaitSpecResult> {
316 0 : let mut new_state = ComputeState::new();
317 : let spec_set;
318 :
319 0 : if let Some(spec) = spec {
320 0 : let pspec = ParsedSpec::try_from(spec).map_err(|msg| anyhow::anyhow!(msg))?;
321 0 : info!("new pspec.spec: {:?}", pspec.spec);
322 0 : new_state.pspec = Some(pspec);
323 0 : spec_set = true;
324 0 : } else {
325 0 : spec_set = false;
326 0 : }
327 0 : let connstr = Url::parse(connstr).context("cannot parse connstr as a URL")?;
328 0 : let conn_conf = postgres::config::Config::from_str(connstr.as_str())
329 0 : .context("cannot build postgres config from connstr")?;
330 0 : let tokio_conn_conf = tokio_postgres::config::Config::from_str(connstr.as_str())
331 0 : .context("cannot build tokio postgres config from connstr")?;
332 0 : let compute_node = ComputeNode {
333 0 : connstr,
334 0 : conn_conf,
335 0 : tokio_conn_conf,
336 0 : pgdata: pgdata.to_string(),
337 0 : pgbin: pgbin.to_string(),
338 0 : pgversion: get_pg_version_string(pgbin),
339 0 : http_port,
340 0 : live_config_allowed,
341 0 : state: Mutex::new(new_state),
342 0 : state_changed: Condvar::new(),
343 0 : ext_remote_storage: ext_remote_storage.map(|s| s.to_string()),
344 0 : ext_download_progress: RwLock::new(HashMap::new()),
345 0 : build_tag,
346 0 : };
347 0 : let compute = Arc::new(compute_node);
348 0 :
349 0 : // If this is a pooled VM, prewarm before starting HTTP server and becoming
350 0 : // available for binding. Prewarming helps Postgres start quicker later,
351 0 : // because QEMU will already have its memory allocated from the host, and
352 0 : // the necessary binaries will already be cached.
353 0 : if !spec_set {
354 0 : compute.prewarm_postgres()?;
355 0 : }
356 :
357 : // Launch http service first, so that we can serve control-plane requests
358 : // while configuration is still in progress.
359 0 : let _http_handle =
360 0 : launch_http_server(http_port, &compute).expect("cannot launch http endpoint thread");
361 0 :
362 0 : if !spec_set {
363 : // No spec provided, hang waiting for it.
364 0 : info!("no compute spec provided, waiting");
365 :
366 0 : let mut state = compute.state.lock().unwrap();
367 0 : while state.status != ComputeStatus::ConfigurationPending {
368 0 : state = compute.state_changed.wait(state).unwrap();
369 0 :
370 0 : if state.status == ComputeStatus::ConfigurationPending {
371 0 : info!("got spec, continue configuration");
372 : // Spec is already set by the http server handler.
373 0 : break;
374 0 : }
375 : }
376 :
377 : // Record for how long we slept waiting for the spec.
378 0 : let now = Utc::now();
379 0 : state.metrics.wait_for_spec_ms = now
380 0 : .signed_duration_since(state.start_time)
381 0 : .to_std()
382 0 : .unwrap()
383 0 : .as_millis() as u64;
384 0 :
385 0 : // Reset start time, so that the total startup time that is calculated later will
386 0 : // not include the time that we waited for the spec.
387 0 : state.start_time = now;
388 0 : }
389 :
390 0 : launch_lsn_lease_bg_task_for_static(&compute);
391 0 :
392 0 : Ok(WaitSpecResult {
393 0 : compute,
394 0 : resize_swap_on_bind,
395 0 : set_disk_quota_for_fs: set_disk_quota_for_fs.cloned(),
396 0 : })
397 0 : }
398 :
399 : struct WaitSpecResult {
400 : compute: Arc<ComputeNode>,
401 : resize_swap_on_bind: bool,
402 : set_disk_quota_for_fs: Option<String>,
403 : }
404 :
405 0 : fn start_postgres(
406 0 : // need to allow unused because `matches` is only used if target_os = "linux"
407 0 : #[allow(unused_variables)] matches: &clap::ArgMatches,
408 0 : WaitSpecResult {
409 0 : compute,
410 0 : resize_swap_on_bind,
411 0 : set_disk_quota_for_fs,
412 0 : }: WaitSpecResult,
413 0 : ) -> Result<(Option<PostgresHandle>, StartPostgresResult)> {
414 0 : // We got all we need, update the state.
415 0 : let mut state = compute.state.lock().unwrap();
416 0 : state.set_status(ComputeStatus::Init, &compute.state_changed);
417 0 :
418 0 : info!(
419 0 : "running compute with features: {:?}",
420 0 : state.pspec.as_ref().unwrap().spec.features
421 : );
422 : // before we release the mutex, fetch the swap size (if any) for later.
423 0 : let swap_size_bytes = state.pspec.as_ref().unwrap().spec.swap_size_bytes;
424 0 : let disk_quota_bytes = state.pspec.as_ref().unwrap().spec.disk_quota_bytes;
425 0 : drop(state);
426 0 :
427 0 : // Launch remaining service threads
428 0 : let _monitor_handle = launch_monitor(&compute);
429 0 : let _configurator_handle = launch_configurator(&compute);
430 0 :
431 0 : let mut prestartup_failed = false;
432 0 : let mut delay_exit = false;
433 :
434 : // Resize swap to the desired size if the compute spec says so
435 0 : if let (Some(size_bytes), true) = (swap_size_bytes, resize_swap_on_bind) {
436 : // To avoid 'swapoff' hitting postgres startup, we need to run resize-swap to completion
437 : // *before* starting postgres.
438 : //
439 : // In theory, we could do this asynchronously if SkipSwapon was enabled for VMs, but this
440 : // carries a risk of introducing hard-to-debug issues - e.g. if postgres sometimes gets
441 : // OOM-killed during startup because swap wasn't available yet.
442 0 : match resize_swap(size_bytes) {
443 : Ok(()) => {
444 0 : let size_mib = size_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
445 0 : info!(%size_bytes, %size_mib, "resized swap");
446 : }
447 0 : Err(err) => {
448 0 : let err = err.context("failed to resize swap");
449 0 : error!("{err:#}");
450 :
451 : // Mark compute startup as failed; don't try to start postgres, and report this
452 : // error to the control plane when it next asks.
453 0 : prestartup_failed = true;
454 0 : compute.set_failed_status(err);
455 0 : delay_exit = true;
456 : }
457 : }
458 0 : }
459 :
460 : // Set disk quota if the compute spec says so
461 0 : if let (Some(disk_quota_bytes), Some(disk_quota_fs_mountpoint)) =
462 0 : (disk_quota_bytes, set_disk_quota_for_fs)
463 : {
464 0 : match set_disk_quota(disk_quota_bytes, &disk_quota_fs_mountpoint) {
465 : Ok(()) => {
466 0 : let size_mib = disk_quota_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
467 0 : info!(%disk_quota_bytes, %size_mib, "set disk quota");
468 : }
469 0 : Err(err) => {
470 0 : let err = err.context("failed to set disk quota");
471 0 : error!("{err:#}");
472 :
473 : // Mark compute startup as failed; don't try to start postgres, and report this
474 : // error to the control plane when it next asks.
475 0 : prestartup_failed = true;
476 0 : compute.set_failed_status(err);
477 0 : delay_exit = true;
478 : }
479 : }
480 0 : }
481 :
482 : // Start Postgres
483 0 : let mut pg = None;
484 0 : if !prestartup_failed {
485 0 : pg = match compute.start_compute() {
486 0 : Ok(pg) => Some(pg),
487 0 : Err(err) => {
488 0 : error!("could not start the compute node: {:#}", err);
489 0 : compute.set_failed_status(err);
490 0 : delay_exit = true;
491 0 : None
492 : }
493 : };
494 : } else {
495 0 : warn!("skipping postgres startup because pre-startup step failed");
496 : }
497 :
498 : // Start the vm-monitor if directed to. The vm-monitor only runs on linux
499 : // because it requires cgroups.
500 : cfg_if::cfg_if! {
501 : if #[cfg(target_os = "linux")] {
502 : use std::env;
503 : use tokio_util::sync::CancellationToken;
504 0 : let vm_monitor_addr = matches
505 0 : .get_one::<String>("vm-monitor-addr")
506 0 : .expect("--vm-monitor-addr should always be set because it has a default arg");
507 0 : let file_cache_connstr = matches.get_one::<String>("filecache-connstr");
508 0 : let cgroup = matches.get_one::<String>("cgroup");
509 :
510 : // Only make a runtime if we need to.
511 : // Note: it seems like you can make a runtime in an inner scope and
512 : // if you start a task in it it won't be dropped. However, make it
513 : // in the outermost scope just to be safe.
514 0 : let rt = if env::var_os("AUTOSCALING").is_some() {
515 0 : Some(
516 0 : tokio::runtime::Builder::new_multi_thread()
517 0 : .worker_threads(4)
518 0 : .enable_all()
519 0 : .build()
520 0 : .expect("failed to create tokio runtime for monitor")
521 0 : )
522 : } else {
523 0 : None
524 : };
525 :
526 : // This token is used internally by the monitor to clean up all threads
527 0 : let token = CancellationToken::new();
528 0 :
529 0 : let vm_monitor = rt.as_ref().map(|rt| {
530 0 : rt.spawn(vm_monitor::start(
531 0 : Box::leak(Box::new(vm_monitor::Args {
532 0 : cgroup: cgroup.cloned(),
533 0 : pgconnstr: file_cache_connstr.cloned(),
534 0 : addr: vm_monitor_addr.clone(),
535 0 : })),
536 0 : token.clone(),
537 0 : ))
538 0 : });
539 0 : }
540 0 : }
541 0 :
542 0 : Ok((
543 0 : pg,
544 0 : StartPostgresResult {
545 0 : delay_exit,
546 0 : compute,
547 0 : #[cfg(target_os = "linux")]
548 0 : rt,
549 0 : #[cfg(target_os = "linux")]
550 0 : token,
551 0 : #[cfg(target_os = "linux")]
552 0 : vm_monitor,
553 0 : },
554 0 : ))
555 0 : }
556 :
557 : type PostgresHandle = (std::process::Child, std::thread::JoinHandle<()>);
558 :
559 : struct StartPostgresResult {
560 : delay_exit: bool,
561 : // passed through from WaitSpecResult
562 : compute: Arc<ComputeNode>,
563 :
564 : #[cfg(target_os = "linux")]
565 : rt: Option<tokio::runtime::Runtime>,
566 : #[cfg(target_os = "linux")]
567 : token: tokio_util::sync::CancellationToken,
568 : #[cfg(target_os = "linux")]
569 : vm_monitor: Option<tokio::task::JoinHandle<Result<()>>>,
570 : }
571 :
572 0 : fn wait_postgres(pg: Option<PostgresHandle>) -> Result<WaitPostgresResult> {
573 0 : // Wait for the child Postgres process forever. In this state Ctrl+C will
574 0 : // propagate to Postgres and it will be shut down as well.
575 0 : let mut exit_code = None;
576 0 : if let Some((mut pg, logs_handle)) = pg {
577 0 : let ecode = pg
578 0 : .wait()
579 0 : .expect("failed to start waiting on Postgres process");
580 0 : PG_PID.store(0, Ordering::SeqCst);
581 0 :
582 0 : // Process has exited, so we can join the logs thread.
583 0 : let _ = logs_handle
584 0 : .join()
585 0 : .map_err(|e| tracing::error!("log thread panicked: {:?}", e));
586 0 :
587 0 : info!("Postgres exited with code {}, shutting down", ecode);
588 0 : exit_code = ecode.code()
589 0 : }
590 :
591 0 : Ok(WaitPostgresResult { exit_code })
592 0 : }
593 :
594 : struct WaitPostgresResult {
595 : exit_code: Option<i32>,
596 : }
597 :
598 0 : fn cleanup_after_postgres_exit(
599 0 : StartPostgresResult {
600 0 : mut delay_exit,
601 0 : compute,
602 0 : #[cfg(target_os = "linux")]
603 0 : vm_monitor,
604 0 : #[cfg(target_os = "linux")]
605 0 : token,
606 0 : #[cfg(target_os = "linux")]
607 0 : rt,
608 0 : }: StartPostgresResult,
609 0 : ) -> Result<bool> {
610 : // Terminate the vm_monitor so it releases the file watcher on
611 : // /sys/fs/cgroup/neon-postgres.
612 : // Note: the vm-monitor only runs on linux because it requires cgroups.
613 : cfg_if::cfg_if! {
614 : if #[cfg(target_os = "linux")] {
615 0 : if let Some(handle) = vm_monitor {
616 0 : // Kills all threads spawned by the monitor
617 0 : token.cancel();
618 0 : // Kills the actual task running the monitor
619 0 : handle.abort();
620 0 :
621 0 : // If handle is some, rt must have been used to produce it, and
622 0 : // hence is also some
623 0 : rt.unwrap().shutdown_timeout(Duration::from_secs(2));
624 0 : }
625 : }
626 : }
627 :
628 : // Maybe sync safekeepers again, to speed up next startup
629 0 : let compute_state = compute.state.lock().unwrap().clone();
630 0 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
631 0 : if matches!(pspec.spec.mode, compute_api::spec::ComputeMode::Primary) {
632 0 : info!("syncing safekeepers on shutdown");
633 0 : let storage_auth_token = pspec.storage_auth_token.clone();
634 0 : let lsn = compute.sync_safekeepers(storage_auth_token)?;
635 0 : info!("synced safekeepers at lsn {lsn}");
636 0 : }
637 :
638 0 : let mut state = compute.state.lock().unwrap();
639 0 : if state.status == ComputeStatus::TerminationPending {
640 0 : state.status = ComputeStatus::Terminated;
641 0 : compute.state_changed.notify_all();
642 0 : // we were asked to terminate gracefully, don't exit to avoid restart
643 0 : delay_exit = true
644 0 : }
645 0 : drop(state);
646 :
647 0 : if let Err(err) = compute.check_for_core_dumps() {
648 0 : error!("error while checking for core dumps: {err:?}");
649 0 : }
650 :
651 0 : Ok(delay_exit)
652 0 : }
653 :
654 0 : fn maybe_delay_exit(delay_exit: bool) {
655 0 : // If launch failed, keep serving HTTP requests for a while, so the cloud
656 0 : // control plane can get the actual error.
657 0 : if delay_exit {
658 0 : info!("giving control plane 30s to collect the error before shutdown");
659 0 : thread::sleep(Duration::from_secs(30));
660 0 : }
661 0 : }
662 :
663 0 : fn deinit_and_exit(WaitPostgresResult { exit_code }: WaitPostgresResult) -> ! {
664 0 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
665 0 : // pending traces before we exit. Shutting down OTEL tracing provider may
666 0 : // hang for quite some time, see, for example:
667 0 : // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
668 0 : // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
669 0 : //
670 0 : // Yet, we want computes to shut down fast enough, as we may need a new one
671 0 : // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
672 0 : // complete, then just error out and exit the main thread.
673 0 : info!("shutting down tracing");
674 0 : let (sender, receiver) = mpsc::channel();
675 0 : let _ = thread::spawn(move || {
676 0 : tracing_utils::shutdown_tracing();
677 0 : sender.send(()).ok()
678 0 : });
679 0 : let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
680 0 : if shutdown_res.is_err() {
681 0 : error!("timed out while shutting down tracing, exiting anyway");
682 0 : }
683 :
684 0 : info!("shutting down");
685 0 : exit(exit_code.unwrap_or(1))
686 : }
687 :
688 1 : fn cli() -> clap::Command {
689 1 : // Env variable is set by `cargo`
690 1 : let version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown");
691 1 : clap::Command::new("compute_ctl")
692 1 : .version(version)
693 1 : .arg(
694 1 : Arg::new("http-port")
695 1 : .long("http-port")
696 1 : .value_name("HTTP_PORT")
697 1 : .default_value("3080")
698 1 : .value_parser(clap::value_parser!(u16))
699 1 : .required(false),
700 1 : )
701 1 : .arg(
702 1 : Arg::new("connstr")
703 1 : .short('C')
704 1 : .long("connstr")
705 1 : .value_name("DATABASE_URL")
706 1 : .required(true),
707 1 : )
708 1 : .arg(
709 1 : Arg::new("pgdata")
710 1 : .short('D')
711 1 : .long("pgdata")
712 1 : .value_name("DATADIR")
713 1 : .required(true),
714 1 : )
715 1 : .arg(
716 1 : Arg::new("pgbin")
717 1 : .short('b')
718 1 : .long("pgbin")
719 1 : .default_value("postgres")
720 1 : .value_name("POSTGRES_PATH"),
721 1 : )
722 1 : .arg(
723 1 : Arg::new("spec")
724 1 : .short('s')
725 1 : .long("spec")
726 1 : .value_name("SPEC_JSON"),
727 1 : )
728 1 : .arg(
729 1 : Arg::new("spec-path")
730 1 : .short('S')
731 1 : .long("spec-path")
732 1 : .value_name("SPEC_PATH"),
733 1 : )
734 1 : .arg(
735 1 : Arg::new("compute-id")
736 1 : .short('i')
737 1 : .long("compute-id")
738 1 : .value_name("COMPUTE_ID"),
739 1 : )
740 1 : .arg(
741 1 : Arg::new("control-plane-uri")
742 1 : .short('p')
743 1 : .long("control-plane-uri")
744 1 : .value_name("CONTROL_PLANE_API_BASE_URI"),
745 1 : )
746 1 : .arg(
747 1 : Arg::new("remote-ext-config")
748 1 : .short('r')
749 1 : .long("remote-ext-config")
750 1 : .value_name("REMOTE_EXT_CONFIG"),
751 1 : )
752 1 : // TODO(fprasx): we currently have default arguments because the cloud PR
753 1 : // to pass them in hasn't been merged yet. We should get rid of them once
754 1 : // the PR is merged.
755 1 : .arg(
756 1 : Arg::new("vm-monitor-addr")
757 1 : .long("vm-monitor-addr")
758 1 : .default_value("0.0.0.0:10301")
759 1 : .value_name("VM_MONITOR_ADDR"),
760 1 : )
761 1 : .arg(
762 1 : Arg::new("cgroup")
763 1 : .long("cgroup")
764 1 : .default_value("neon-postgres")
765 1 : .value_name("CGROUP"),
766 1 : )
767 1 : .arg(
768 1 : Arg::new("filecache-connstr")
769 1 : .long("filecache-connstr")
770 1 : .default_value(
771 1 : "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor",
772 1 : )
773 1 : .value_name("FILECACHE_CONNSTR"),
774 1 : )
775 1 : .arg(
776 1 : Arg::new("resize-swap-on-bind")
777 1 : .long("resize-swap-on-bind")
778 1 : .action(clap::ArgAction::SetTrue),
779 1 : )
780 1 : .arg(
781 1 : Arg::new("set-disk-quota-for-fs")
782 1 : .long("set-disk-quota-for-fs")
783 1 : .value_name("SET_DISK_QUOTA_FOR_FS")
784 1 : )
785 1 : }
786 :
787 : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
788 : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
789 : /// wait for termination which would be easy then.
790 0 : fn handle_exit_signal(sig: i32) {
791 0 : info!("received {sig} termination signal");
792 0 : forward_termination_signal();
793 0 : exit(1);
794 : }
795 :
796 : #[test]
797 1 : fn verify_cli() {
798 1 : cli().debug_assert()
799 1 : }
|