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 : //! -c /var/db/postgres/configs/config.json \
33 : //! -b /usr/local/bin/postgres \
34 : //! -r http://pg-ext-s3-gateway \
35 : //! ```
36 : use std::ffi::OsString;
37 : use std::fs::File;
38 : use std::process::exit;
39 : use std::sync::mpsc;
40 : use std::thread;
41 : use std::time::Duration;
42 :
43 : use anyhow::{Context, Result};
44 : use clap::Parser;
45 : use compute_api::responses::ComputeConfig;
46 : use compute_tools::compute::{
47 : BUILD_TAG, ComputeNode, ComputeNodeParams, forward_termination_signal,
48 : };
49 : use compute_tools::extension_server::get_pg_version_string;
50 : use compute_tools::logger::*;
51 : use compute_tools::params::*;
52 : use compute_tools::spec::*;
53 : use rlimit::{Resource, setrlimit};
54 : use signal_hook::consts::{SIGINT, SIGQUIT, SIGTERM};
55 : use signal_hook::iterator::Signals;
56 : use tracing::{error, info};
57 : use url::Url;
58 : use utils::failpoint_support;
59 :
60 : // Compatibility hack: if the control plane specified any remote-ext-config
61 : // use the default value for extension storage proxy gateway.
62 : // Remove this once the control plane is updated to pass the gateway URL
63 2 : fn parse_remote_ext_base_url(arg: &str) -> Result<String> {
64 : const FALLBACK_PG_EXT_GATEWAY_BASE_URL: &str =
65 : "http://pg-ext-s3-gateway.pg-ext-s3-gateway.svc.cluster.local";
66 :
67 2 : Ok(if arg.starts_with("http") {
68 1 : arg
69 : } else {
70 1 : FALLBACK_PG_EXT_GATEWAY_BASE_URL
71 : }
72 2 : .to_owned())
73 2 : }
74 :
75 : #[derive(Parser)]
76 : #[command(rename_all = "kebab-case")]
77 : struct Cli {
78 : #[arg(short = 'b', long, default_value = "postgres", env = "POSTGRES_PATH")]
79 0 : pub pgbin: String,
80 :
81 : /// The base URL for the remote extension storage proxy gateway.
82 : /// Should be in the form of `http(s)://<gateway-hostname>[:<port>]`.
83 : #[arg(short = 'r', long, value_parser = parse_remote_ext_base_url, alias = "remote-ext-config")]
84 : pub remote_ext_base_url: Option<String>,
85 :
86 : /// The port to bind the external listening HTTP server to. Clients running
87 : /// outside the compute will talk to the compute through this port. Keep
88 : /// the previous name for this argument around for a smoother release
89 : /// with the control plane.
90 1 : #[arg(long, default_value_t = 3080)]
91 0 : pub external_http_port: u16,
92 :
93 : /// The port to bind the internal listening HTTP server to. Clients include
94 : /// the neon extension (for installing remote extensions) and local_proxy.
95 1 : #[arg(long, default_value_t = 3081)]
96 0 : pub internal_http_port: u16,
97 :
98 : #[arg(short = 'D', long, value_name = "DATADIR")]
99 0 : pub pgdata: String,
100 :
101 : #[arg(short = 'C', long, value_name = "DATABASE_URL")]
102 0 : pub connstr: String,
103 :
104 : #[cfg(target_os = "linux")]
105 : #[arg(long, default_value = "neon-postgres")]
106 0 : pub cgroup: String,
107 :
108 : #[cfg(target_os = "linux")]
109 : #[arg(
110 : long,
111 : default_value = "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor"
112 : )]
113 0 : pub filecache_connstr: String,
114 :
115 : #[cfg(target_os = "linux")]
116 : #[arg(long, default_value = "0.0.0.0:10301")]
117 0 : pub vm_monitor_addr: String,
118 :
119 : #[arg(long, action = clap::ArgAction::SetTrue)]
120 0 : pub resize_swap_on_bind: bool,
121 :
122 : #[arg(long)]
123 : pub set_disk_quota_for_fs: Option<String>,
124 :
125 : #[arg(short = 'c', long)]
126 : pub config: Option<OsString>,
127 :
128 : #[arg(short = 'i', long, group = "compute-id")]
129 0 : pub compute_id: String,
130 :
131 : #[arg(
132 : short = 'p',
133 : long,
134 : conflicts_with = "config",
135 : value_name = "CONTROL_PLANE_API_BASE_URL",
136 : requires = "compute-id"
137 : )]
138 : pub control_plane_uri: Option<String>,
139 : }
140 :
141 0 : fn main() -> Result<()> {
142 0 : let cli = Cli::parse();
143 0 :
144 0 : let scenario = failpoint_support::init();
145 :
146 : // For historical reasons, the main thread that processes the config and launches postgres
147 : // is synchronous, but we always have this tokio runtime available and we "enter" it so
148 : // that you can use tokio::spawn() and tokio::runtime::Handle::current().block_on(...)
149 : // from all parts of compute_ctl.
150 0 : let runtime = tokio::runtime::Builder::new_multi_thread()
151 0 : .enable_all()
152 0 : .build()?;
153 0 : let _rt_guard = runtime.enter();
154 0 :
155 0 : runtime.block_on(init())?;
156 :
157 : // enable core dumping for all child processes
158 0 : setrlimit(Resource::CORE, rlimit::INFINITY, rlimit::INFINITY)?;
159 :
160 0 : let connstr = Url::parse(&cli.connstr).context("cannot parse connstr as a URL")?;
161 :
162 0 : let config = get_config(&cli)?;
163 :
164 0 : let compute_node = ComputeNode::new(
165 0 : ComputeNodeParams {
166 0 : compute_id: cli.compute_id,
167 0 : connstr,
168 0 : pgdata: cli.pgdata.clone(),
169 0 : pgbin: cli.pgbin.clone(),
170 0 : pgversion: get_pg_version_string(&cli.pgbin),
171 0 : external_http_port: cli.external_http_port,
172 0 : internal_http_port: cli.internal_http_port,
173 0 : remote_ext_base_url: cli.remote_ext_base_url.clone(),
174 0 : resize_swap_on_bind: cli.resize_swap_on_bind,
175 0 : set_disk_quota_for_fs: cli.set_disk_quota_for_fs,
176 0 : #[cfg(target_os = "linux")]
177 0 : filecache_connstr: cli.filecache_connstr,
178 0 : #[cfg(target_os = "linux")]
179 0 : cgroup: cli.cgroup,
180 0 : #[cfg(target_os = "linux")]
181 0 : vm_monitor_addr: cli.vm_monitor_addr,
182 0 : },
183 0 : config,
184 0 : )?;
185 :
186 0 : let exit_code = compute_node.run()?;
187 :
188 0 : scenario.teardown();
189 0 :
190 0 : deinit_and_exit(exit_code);
191 0 : }
192 :
193 0 : async fn init() -> Result<()> {
194 0 : init_tracing_and_logging(DEFAULT_LOG_LEVEL).await?;
195 :
196 0 : let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
197 0 : thread::spawn(move || {
198 0 : for sig in signals.forever() {
199 0 : handle_exit_signal(sig);
200 0 : }
201 0 : });
202 0 :
203 0 : info!("compute build_tag: {}", &BUILD_TAG.to_string());
204 :
205 0 : Ok(())
206 0 : }
207 :
208 0 : fn get_config(cli: &Cli) -> Result<ComputeConfig> {
209 : // First, read the config from the path if provided
210 0 : if let Some(ref config) = cli.config {
211 0 : let file = File::open(config)?;
212 0 : return Ok(serde_json::from_reader(&file)?);
213 0 : }
214 0 :
215 0 : // If the config wasn't provided in the CLI arguments, then retrieve it from
216 0 : // the control plane
217 0 : match get_config_from_control_plane(cli.control_plane_uri.as_ref().unwrap(), &cli.compute_id) {
218 0 : Ok(config) => Ok(config),
219 0 : Err(e) => {
220 0 : error!(
221 0 : "cannot get response from control plane: {}\n\
222 0 : neither spec nor confirmation that compute is in the Empty state was received",
223 : e
224 : );
225 0 : Err(e)
226 : }
227 : }
228 0 : }
229 :
230 0 : fn deinit_and_exit(exit_code: Option<i32>) -> ! {
231 0 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
232 0 : // pending traces before we exit. Shutting down OTEL tracing provider may
233 0 : // hang for quite some time, see, for example:
234 0 : // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
235 0 : // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
236 0 : //
237 0 : // Yet, we want computes to shut down fast enough, as we may need a new one
238 0 : // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
239 0 : // complete, then just error out and exit the main thread.
240 0 : info!("shutting down tracing");
241 0 : let (sender, receiver) = mpsc::channel();
242 0 : let _ = thread::spawn(move || {
243 0 : tracing_utils::shutdown_tracing();
244 0 : sender.send(()).ok()
245 0 : });
246 0 : let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
247 0 : if shutdown_res.is_err() {
248 0 : error!("timed out while shutting down tracing, exiting anyway");
249 0 : }
250 :
251 0 : info!("shutting down");
252 0 : exit(exit_code.unwrap_or(1))
253 : }
254 :
255 : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
256 : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
257 : /// wait for termination which would be easy then.
258 0 : fn handle_exit_signal(sig: i32) {
259 0 : info!("received {sig} termination signal");
260 0 : forward_termination_signal();
261 0 : exit(1);
262 : }
263 :
264 : #[cfg(test)]
265 : mod test {
266 : use clap::CommandFactory;
267 :
268 : use super::Cli;
269 :
270 : #[test]
271 1 : fn verify_cli() {
272 1 : Cli::command().debug_assert()
273 1 : }
274 :
275 : #[test]
276 1 : fn parse_pg_ext_gateway_base_url() {
277 1 : let arg = "http://pg-ext-s3-gateway2";
278 1 : let result = super::parse_remote_ext_base_url(arg).unwrap();
279 1 : assert_eq!(result, arg);
280 :
281 1 : let arg = "pg-ext-s3-gateway";
282 1 : let result = super::parse_remote_ext_base_url(arg).unwrap();
283 1 : assert_eq!(
284 1 : result,
285 1 : "http://pg-ext-s3-gateway.pg-ext-s3-gateway.svc.cluster.local"
286 1 : );
287 1 : }
288 : }
|