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 0 :
249 0 : let spec;
250 0 : let mut live_config_allowed = false;
251 0 : match spec_json {
252 : // First, try to get cluster spec from the cli argument
253 0 : Some(json) => {
254 0 : info!("got spec from cli argument {}", json);
255 0 : spec = Some(serde_json::from_str(json)?);
256 : }
257 : None => {
258 : // Second, try to read it from the file if path is provided
259 0 : if let Some(sp) = spec_path {
260 0 : let path = Path::new(sp);
261 0 : let file = File::open(path)?;
262 0 : spec = Some(serde_json::from_reader(file)?);
263 0 : live_config_allowed = true;
264 0 : } else if let Some(id) = compute_id {
265 0 : if let Some(cp_base) = control_plane_uri {
266 0 : live_config_allowed = true;
267 0 : spec = match get_spec_from_control_plane(cp_base, id) {
268 0 : Ok(s) => s,
269 0 : Err(e) => {
270 0 : error!("cannot get response from control plane: {}", e);
271 0 : panic!("neither spec nor confirmation that compute is in the Empty state was received");
272 : }
273 : };
274 : } else {
275 0 : panic!("must specify both --control-plane-uri and --compute-id or none");
276 : }
277 : } else {
278 0 : panic!(
279 0 : "compute spec should be provided by one of the following ways: \
280 0 : --spec OR --spec-path OR --control-plane-uri and --compute-id"
281 0 : );
282 : }
283 : }
284 : };
285 :
286 0 : Ok(CliSpecParams {
287 0 : spec,
288 0 : live_config_allowed,
289 0 : })
290 0 : }
291 :
292 : struct CliSpecParams {
293 : /// If a spec was provided via CLI or file, the [`ComputeSpec`]
294 : spec: Option<ComputeSpec>,
295 : live_config_allowed: bool,
296 : }
297 :
298 0 : fn wait_spec(
299 0 : build_tag: String,
300 0 : ProcessCliResult {
301 0 : connstr,
302 0 : pgdata,
303 0 : pgbin,
304 0 : ext_remote_storage,
305 0 : resize_swap_on_bind,
306 0 : set_disk_quota_for_fs,
307 0 : http_port,
308 0 : ..
309 0 : }: ProcessCliResult,
310 0 : CliSpecParams {
311 0 : spec,
312 0 : live_config_allowed,
313 0 : }: CliSpecParams,
314 0 : ) -> Result<WaitSpecResult> {
315 0 : let mut new_state = ComputeState::new();
316 : let spec_set;
317 :
318 0 : if let Some(spec) = spec {
319 0 : let pspec = ParsedSpec::try_from(spec).map_err(|msg| anyhow::anyhow!(msg))?;
320 0 : info!("new pspec.spec: {:?}", pspec.spec);
321 0 : new_state.pspec = Some(pspec);
322 0 : spec_set = true;
323 0 : } else {
324 0 : spec_set = false;
325 0 : }
326 0 : let connstr = Url::parse(connstr).context("cannot parse connstr as a URL")?;
327 0 : let conn_conf = postgres::config::Config::from_str(connstr.as_str())
328 0 : .context("cannot build postgres config from connstr")?;
329 0 : let tokio_conn_conf = tokio_postgres::config::Config::from_str(connstr.as_str())
330 0 : .context("cannot build tokio postgres config from connstr")?;
331 0 : let compute_node = ComputeNode {
332 0 : connstr,
333 0 : conn_conf,
334 0 : tokio_conn_conf,
335 0 : pgdata: pgdata.to_string(),
336 0 : pgbin: pgbin.to_string(),
337 0 : pgversion: get_pg_version_string(pgbin),
338 0 : http_port,
339 0 : live_config_allowed,
340 0 : state: Mutex::new(new_state),
341 0 : state_changed: Condvar::new(),
342 0 : ext_remote_storage: ext_remote_storage.map(|s| s.to_string()),
343 0 : ext_download_progress: RwLock::new(HashMap::new()),
344 0 : build_tag,
345 0 : };
346 0 : let compute = Arc::new(compute_node);
347 0 :
348 0 : // If this is a pooled VM, prewarm before starting HTTP server and becoming
349 0 : // available for binding. Prewarming helps Postgres start quicker later,
350 0 : // because QEMU will already have its memory allocated from the host, and
351 0 : // the necessary binaries will already be cached.
352 0 : if !spec_set {
353 0 : compute.prewarm_postgres()?;
354 0 : }
355 :
356 : // Launch http service first, so that we can serve control-plane requests
357 : // while configuration is still in progress.
358 0 : let _http_handle =
359 0 : launch_http_server(http_port, &compute).expect("cannot launch http endpoint thread");
360 0 :
361 0 : if !spec_set {
362 : // No spec provided, hang waiting for it.
363 0 : info!("no compute spec provided, waiting");
364 :
365 0 : let mut state = compute.state.lock().unwrap();
366 0 : while state.status != ComputeStatus::ConfigurationPending {
367 0 : state = compute.state_changed.wait(state).unwrap();
368 0 :
369 0 : if state.status == ComputeStatus::ConfigurationPending {
370 0 : info!("got spec, continue configuration");
371 : // Spec is already set by the http server handler.
372 0 : break;
373 0 : }
374 : }
375 :
376 : // Record for how long we slept waiting for the spec.
377 0 : let now = Utc::now();
378 0 : state.metrics.wait_for_spec_ms = now
379 0 : .signed_duration_since(state.start_time)
380 0 : .to_std()
381 0 : .unwrap()
382 0 : .as_millis() as u64;
383 0 :
384 0 : // Reset start time, so that the total startup time that is calculated later will
385 0 : // not include the time that we waited for the spec.
386 0 : state.start_time = now;
387 0 : }
388 :
389 0 : launch_lsn_lease_bg_task_for_static(&compute);
390 0 :
391 0 : Ok(WaitSpecResult {
392 0 : compute,
393 0 : resize_swap_on_bind,
394 0 : set_disk_quota_for_fs: set_disk_quota_for_fs.cloned(),
395 0 : })
396 0 : }
397 :
398 : struct WaitSpecResult {
399 : compute: Arc<ComputeNode>,
400 : resize_swap_on_bind: bool,
401 : set_disk_quota_for_fs: Option<String>,
402 : }
403 :
404 0 : fn start_postgres(
405 0 : // need to allow unused because `matches` is only used if target_os = "linux"
406 0 : #[allow(unused_variables)] matches: &clap::ArgMatches,
407 0 : WaitSpecResult {
408 0 : compute,
409 0 : resize_swap_on_bind,
410 0 : set_disk_quota_for_fs,
411 0 : }: WaitSpecResult,
412 0 : ) -> Result<(Option<PostgresHandle>, StartPostgresResult)> {
413 0 : // We got all we need, update the state.
414 0 : let mut state = compute.state.lock().unwrap();
415 0 : state.set_status(ComputeStatus::Init, &compute.state_changed);
416 0 :
417 0 : info!(
418 0 : "running compute with features: {:?}",
419 0 : state.pspec.as_ref().unwrap().spec.features
420 : );
421 : // before we release the mutex, fetch the swap size (if any) for later.
422 0 : let swap_size_bytes = state.pspec.as_ref().unwrap().spec.swap_size_bytes;
423 0 : let disk_quota_bytes = state.pspec.as_ref().unwrap().spec.disk_quota_bytes;
424 0 : drop(state);
425 0 :
426 0 : // Launch remaining service threads
427 0 : let _monitor_handle = launch_monitor(&compute);
428 0 : let _configurator_handle = launch_configurator(&compute);
429 0 :
430 0 : let mut prestartup_failed = false;
431 0 : let mut delay_exit = false;
432 :
433 : // Resize swap to the desired size if the compute spec says so
434 0 : if let (Some(size_bytes), true) = (swap_size_bytes, resize_swap_on_bind) {
435 : // To avoid 'swapoff' hitting postgres startup, we need to run resize-swap to completion
436 : // *before* starting postgres.
437 : //
438 : // In theory, we could do this asynchronously if SkipSwapon was enabled for VMs, but this
439 : // carries a risk of introducing hard-to-debug issues - e.g. if postgres sometimes gets
440 : // OOM-killed during startup because swap wasn't available yet.
441 0 : match resize_swap(size_bytes) {
442 : Ok(()) => {
443 0 : let size_mib = size_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
444 0 : info!(%size_bytes, %size_mib, "resized swap");
445 : }
446 0 : Err(err) => {
447 0 : let err = err.context("failed to resize swap");
448 0 : error!("{err:#}");
449 :
450 : // Mark compute startup as failed; don't try to start postgres, and report this
451 : // error to the control plane when it next asks.
452 0 : prestartup_failed = true;
453 0 : compute.set_failed_status(err);
454 0 : delay_exit = true;
455 : }
456 : }
457 0 : }
458 :
459 : // Set disk quota if the compute spec says so
460 0 : if let (Some(disk_quota_bytes), Some(disk_quota_fs_mountpoint)) =
461 0 : (disk_quota_bytes, set_disk_quota_for_fs)
462 : {
463 0 : match set_disk_quota(disk_quota_bytes, &disk_quota_fs_mountpoint) {
464 : Ok(()) => {
465 0 : let size_mib = disk_quota_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
466 0 : info!(%disk_quota_bytes, %size_mib, "set disk quota");
467 : }
468 0 : Err(err) => {
469 0 : let err = err.context("failed to set disk quota");
470 0 : error!("{err:#}");
471 :
472 : // Mark compute startup as failed; don't try to start postgres, and report this
473 : // error to the control plane when it next asks.
474 0 : prestartup_failed = true;
475 0 : compute.set_failed_status(err);
476 0 : delay_exit = true;
477 : }
478 : }
479 0 : }
480 :
481 : // Start Postgres
482 0 : let mut pg = None;
483 0 : if !prestartup_failed {
484 0 : pg = match compute.start_compute() {
485 0 : Ok(pg) => Some(pg),
486 0 : Err(err) => {
487 0 : error!("could not start the compute node: {:#}", err);
488 0 : compute.set_failed_status(err);
489 0 : delay_exit = true;
490 0 : None
491 : }
492 : };
493 : } else {
494 0 : warn!("skipping postgres startup because pre-startup step failed");
495 : }
496 :
497 : // Start the vm-monitor if directed to. The vm-monitor only runs on linux
498 : // because it requires cgroups.
499 : cfg_if::cfg_if! {
500 : if #[cfg(target_os = "linux")] {
501 : use std::env;
502 : use tokio_util::sync::CancellationToken;
503 0 : let vm_monitor_addr = matches
504 0 : .get_one::<String>("vm-monitor-addr")
505 0 : .expect("--vm-monitor-addr should always be set because it has a default arg");
506 0 : let file_cache_connstr = matches.get_one::<String>("filecache-connstr");
507 0 : let cgroup = matches.get_one::<String>("cgroup");
508 :
509 : // Only make a runtime if we need to.
510 : // Note: it seems like you can make a runtime in an inner scope and
511 : // if you start a task in it it won't be dropped. However, make it
512 : // in the outermost scope just to be safe.
513 0 : let rt = if env::var_os("AUTOSCALING").is_some() {
514 0 : Some(
515 0 : tokio::runtime::Builder::new_multi_thread()
516 0 : .worker_threads(4)
517 0 : .enable_all()
518 0 : .build()
519 0 : .expect("failed to create tokio runtime for monitor")
520 0 : )
521 : } else {
522 0 : None
523 : };
524 :
525 : // This token is used internally by the monitor to clean up all threads
526 0 : let token = CancellationToken::new();
527 0 :
528 0 : let vm_monitor = rt.as_ref().map(|rt| {
529 0 : rt.spawn(vm_monitor::start(
530 0 : Box::leak(Box::new(vm_monitor::Args {
531 0 : cgroup: cgroup.cloned(),
532 0 : pgconnstr: file_cache_connstr.cloned(),
533 0 : addr: vm_monitor_addr.clone(),
534 0 : })),
535 0 : token.clone(),
536 0 : ))
537 0 : });
538 0 : }
539 0 : }
540 0 :
541 0 : Ok((
542 0 : pg,
543 0 : StartPostgresResult {
544 0 : delay_exit,
545 0 : compute,
546 0 : #[cfg(target_os = "linux")]
547 0 : rt,
548 0 : #[cfg(target_os = "linux")]
549 0 : token,
550 0 : #[cfg(target_os = "linux")]
551 0 : vm_monitor,
552 0 : },
553 0 : ))
554 0 : }
555 :
556 : type PostgresHandle = (std::process::Child, std::thread::JoinHandle<()>);
557 :
558 : struct StartPostgresResult {
559 : delay_exit: bool,
560 : // passed through from WaitSpecResult
561 : compute: Arc<ComputeNode>,
562 :
563 : #[cfg(target_os = "linux")]
564 : rt: Option<tokio::runtime::Runtime>,
565 : #[cfg(target_os = "linux")]
566 : token: tokio_util::sync::CancellationToken,
567 : #[cfg(target_os = "linux")]
568 : vm_monitor: Option<tokio::task::JoinHandle<Result<()>>>,
569 : }
570 :
571 0 : fn wait_postgres(pg: Option<PostgresHandle>) -> Result<WaitPostgresResult> {
572 0 : // Wait for the child Postgres process forever. In this state Ctrl+C will
573 0 : // propagate to Postgres and it will be shut down as well.
574 0 : let mut exit_code = None;
575 0 : if let Some((mut pg, logs_handle)) = pg {
576 0 : let ecode = pg
577 0 : .wait()
578 0 : .expect("failed to start waiting on Postgres process");
579 0 : PG_PID.store(0, Ordering::SeqCst);
580 0 :
581 0 : // Process has exited, so we can join the logs thread.
582 0 : let _ = logs_handle
583 0 : .join()
584 0 : .map_err(|e| tracing::error!("log thread panicked: {:?}", e));
585 0 :
586 0 : info!("Postgres exited with code {}, shutting down", ecode);
587 0 : exit_code = ecode.code()
588 0 : }
589 :
590 0 : Ok(WaitPostgresResult { exit_code })
591 0 : }
592 :
593 : struct WaitPostgresResult {
594 : exit_code: Option<i32>,
595 : }
596 :
597 0 : fn cleanup_after_postgres_exit(
598 0 : StartPostgresResult {
599 0 : mut delay_exit,
600 0 : compute,
601 0 : #[cfg(target_os = "linux")]
602 0 : vm_monitor,
603 0 : #[cfg(target_os = "linux")]
604 0 : token,
605 0 : #[cfg(target_os = "linux")]
606 0 : rt,
607 0 : }: StartPostgresResult,
608 0 : ) -> Result<bool> {
609 : // Terminate the vm_monitor so it releases the file watcher on
610 : // /sys/fs/cgroup/neon-postgres.
611 : // Note: the vm-monitor only runs on linux because it requires cgroups.
612 : cfg_if::cfg_if! {
613 : if #[cfg(target_os = "linux")] {
614 0 : if let Some(handle) = vm_monitor {
615 0 : // Kills all threads spawned by the monitor
616 0 : token.cancel();
617 0 : // Kills the actual task running the monitor
618 0 : handle.abort();
619 0 :
620 0 : // If handle is some, rt must have been used to produce it, and
621 0 : // hence is also some
622 0 : rt.unwrap().shutdown_timeout(Duration::from_secs(2));
623 0 : }
624 : }
625 : }
626 :
627 : // Maybe sync safekeepers again, to speed up next startup
628 0 : let compute_state = compute.state.lock().unwrap().clone();
629 0 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
630 0 : if matches!(pspec.spec.mode, compute_api::spec::ComputeMode::Primary) {
631 0 : info!("syncing safekeepers on shutdown");
632 0 : let storage_auth_token = pspec.storage_auth_token.clone();
633 0 : let lsn = compute.sync_safekeepers(storage_auth_token)?;
634 0 : info!("synced safekeepers at lsn {lsn}");
635 0 : }
636 :
637 0 : let mut state = compute.state.lock().unwrap();
638 0 : if state.status == ComputeStatus::TerminationPending {
639 0 : state.status = ComputeStatus::Terminated;
640 0 : compute.state_changed.notify_all();
641 0 : // we were asked to terminate gracefully, don't exit to avoid restart
642 0 : delay_exit = true
643 0 : }
644 0 : drop(state);
645 :
646 0 : if let Err(err) = compute.check_for_core_dumps() {
647 0 : error!("error while checking for core dumps: {err:?}");
648 0 : }
649 :
650 0 : Ok(delay_exit)
651 0 : }
652 :
653 0 : fn maybe_delay_exit(delay_exit: bool) {
654 0 : // If launch failed, keep serving HTTP requests for a while, so the cloud
655 0 : // control plane can get the actual error.
656 0 : if delay_exit {
657 0 : info!("giving control plane 30s to collect the error before shutdown");
658 0 : thread::sleep(Duration::from_secs(30));
659 0 : }
660 0 : }
661 :
662 0 : fn deinit_and_exit(WaitPostgresResult { exit_code }: WaitPostgresResult) -> ! {
663 0 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
664 0 : // pending traces before we exit. Shutting down OTEL tracing provider may
665 0 : // hang for quite some time, see, for example:
666 0 : // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
667 0 : // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
668 0 : //
669 0 : // Yet, we want computes to shut down fast enough, as we may need a new one
670 0 : // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
671 0 : // complete, then just error out and exit the main thread.
672 0 : info!("shutting down tracing");
673 0 : let (sender, receiver) = mpsc::channel();
674 0 : let _ = thread::spawn(move || {
675 0 : tracing_utils::shutdown_tracing();
676 0 : sender.send(()).ok()
677 0 : });
678 0 : let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
679 0 : if shutdown_res.is_err() {
680 0 : error!("timed out while shutting down tracing, exiting anyway");
681 0 : }
682 :
683 0 : info!("shutting down");
684 0 : exit(exit_code.unwrap_or(1))
685 : }
686 :
687 1 : fn cli() -> clap::Command {
688 1 : // Env variable is set by `cargo`
689 1 : let version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown");
690 1 : clap::Command::new("compute_ctl")
691 1 : .version(version)
692 1 : .arg(
693 1 : Arg::new("http-port")
694 1 : .long("http-port")
695 1 : .value_name("HTTP_PORT")
696 1 : .default_value("3080")
697 1 : .value_parser(clap::value_parser!(u16))
698 1 : .required(false),
699 1 : )
700 1 : .arg(
701 1 : Arg::new("connstr")
702 1 : .short('C')
703 1 : .long("connstr")
704 1 : .value_name("DATABASE_URL")
705 1 : .required(true),
706 1 : )
707 1 : .arg(
708 1 : Arg::new("pgdata")
709 1 : .short('D')
710 1 : .long("pgdata")
711 1 : .value_name("DATADIR")
712 1 : .required(true),
713 1 : )
714 1 : .arg(
715 1 : Arg::new("pgbin")
716 1 : .short('b')
717 1 : .long("pgbin")
718 1 : .default_value("postgres")
719 1 : .value_name("POSTGRES_PATH"),
720 1 : )
721 1 : .arg(
722 1 : Arg::new("spec")
723 1 : .short('s')
724 1 : .long("spec")
725 1 : .value_name("SPEC_JSON"),
726 1 : )
727 1 : .arg(
728 1 : Arg::new("spec-path")
729 1 : .short('S')
730 1 : .long("spec-path")
731 1 : .value_name("SPEC_PATH"),
732 1 : )
733 1 : .arg(
734 1 : Arg::new("compute-id")
735 1 : .short('i')
736 1 : .long("compute-id")
737 1 : .value_name("COMPUTE_ID"),
738 1 : )
739 1 : .arg(
740 1 : Arg::new("control-plane-uri")
741 1 : .short('p')
742 1 : .long("control-plane-uri")
743 1 : .value_name("CONTROL_PLANE_API_BASE_URI"),
744 1 : )
745 1 : .arg(
746 1 : Arg::new("remote-ext-config")
747 1 : .short('r')
748 1 : .long("remote-ext-config")
749 1 : .value_name("REMOTE_EXT_CONFIG"),
750 1 : )
751 1 : // TODO(fprasx): we currently have default arguments because the cloud PR
752 1 : // to pass them in hasn't been merged yet. We should get rid of them once
753 1 : // the PR is merged.
754 1 : .arg(
755 1 : Arg::new("vm-monitor-addr")
756 1 : .long("vm-monitor-addr")
757 1 : .default_value("0.0.0.0:10301")
758 1 : .value_name("VM_MONITOR_ADDR"),
759 1 : )
760 1 : .arg(
761 1 : Arg::new("cgroup")
762 1 : .long("cgroup")
763 1 : .default_value("neon-postgres")
764 1 : .value_name("CGROUP"),
765 1 : )
766 1 : .arg(
767 1 : Arg::new("filecache-connstr")
768 1 : .long("filecache-connstr")
769 1 : .default_value(
770 1 : "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor",
771 1 : )
772 1 : .value_name("FILECACHE_CONNSTR"),
773 1 : )
774 1 : .arg(
775 1 : Arg::new("resize-swap-on-bind")
776 1 : .long("resize-swap-on-bind")
777 1 : .action(clap::ArgAction::SetTrue),
778 1 : )
779 1 : .arg(
780 1 : Arg::new("set-disk-quota-for-fs")
781 1 : .long("set-disk-quota-for-fs")
782 1 : .value_name("SET_DISK_QUOTA_FOR_FS")
783 1 : )
784 1 : }
785 :
786 : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
787 : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
788 : /// wait for termination which would be easy then.
789 0 : fn handle_exit_signal(sig: i32) {
790 0 : info!("received {sig} termination signal");
791 0 : forward_termination_signal();
792 0 : exit(1);
793 : }
794 :
795 : #[test]
796 1 : fn verify_cli() {
797 1 : cli().debug_assert()
798 1 : }
|