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