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::Arc;
40 : use std::sync::atomic::AtomicU64;
41 : use std::sync::mpsc;
42 : use std::thread;
43 : use std::time::Duration;
44 :
45 : use anyhow::{Context, Result, bail};
46 : use clap::Parser;
47 : use compute_api::responses::ComputeConfig;
48 : use compute_tools::compute::{
49 : BUILD_TAG, ComputeNode, ComputeNodeParams, forward_termination_signal,
50 : };
51 : use compute_tools::extension_server::get_pg_version_string;
52 : use compute_tools::params::*;
53 : use compute_tools::pg_isready::get_pg_isready_bin;
54 : use compute_tools::spec::*;
55 : use compute_tools::{hadron_metrics, installed_extensions, logger::*};
56 : use rlimit::{Resource, setrlimit};
57 : use signal_hook::consts::{SIGINT, SIGQUIT, SIGTERM};
58 : use signal_hook::iterator::Signals;
59 : use tracing::{error, info};
60 : use url::Url;
61 : use utils::failpoint_support;
62 :
63 : #[derive(Debug, Parser)]
64 : #[command(rename_all = "kebab-case")]
65 : struct Cli {
66 : #[arg(short = 'b', long, default_value = "postgres", env = "POSTGRES_PATH")]
67 : pub pgbin: String,
68 :
69 : /// The base URL for the remote extension storage proxy gateway.
70 : #[arg(short = 'r', long, value_parser = Self::parse_remote_ext_base_url)]
71 : pub remote_ext_base_url: Option<Url>,
72 :
73 : /// The port to bind the external listening HTTP server to. Clients running
74 : /// outside the compute will talk to the compute through this port. Keep
75 : /// the previous name for this argument around for a smoother release
76 : /// with the control plane.
77 : #[arg(long, default_value_t = 3080)]
78 : pub external_http_port: u16,
79 :
80 : /// The port to bind the internal listening HTTP server to. Clients include
81 : /// the neon extension (for installing remote extensions) and local_proxy.
82 : #[arg(long, default_value_t = 3081)]
83 : pub internal_http_port: u16,
84 :
85 : #[arg(short = 'D', long, value_name = "DATADIR")]
86 : pub pgdata: String,
87 :
88 : #[arg(short = 'C', long, value_name = "DATABASE_URL")]
89 : pub connstr: String,
90 :
91 : #[arg(
92 : long,
93 : default_value = "neon_superuser",
94 : value_name = "PRIVILEGED_ROLE_NAME",
95 : value_parser = Self::parse_privileged_role_name
96 : )]
97 : pub privileged_role_name: String,
98 :
99 : #[cfg(target_os = "linux")]
100 : #[arg(long, default_value = "neon-postgres")]
101 : pub cgroup: String,
102 :
103 : #[cfg(target_os = "linux")]
104 : #[arg(
105 : long,
106 : default_value = "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor"
107 : )]
108 : pub filecache_connstr: String,
109 :
110 : #[cfg(target_os = "linux")]
111 : #[arg(long, default_value = "0.0.0.0:10301")]
112 : pub vm_monitor_addr: String,
113 :
114 : #[arg(long, action = clap::ArgAction::SetTrue)]
115 : pub resize_swap_on_bind: bool,
116 :
117 : #[arg(long)]
118 : pub set_disk_quota_for_fs: Option<String>,
119 :
120 : #[arg(short = 'c', long)]
121 : pub config: Option<OsString>,
122 :
123 : #[arg(short = 'i', long, group = "compute-id")]
124 : pub compute_id: String,
125 :
126 : #[arg(
127 : short = 'p',
128 : long,
129 : conflicts_with = "config",
130 : value_name = "CONTROL_PLANE_API_BASE_URL",
131 : requires = "compute-id"
132 : )]
133 : pub control_plane_uri: Option<String>,
134 :
135 : /// Interval in seconds for collecting installed extensions statistics
136 : #[arg(long, default_value = "3600")]
137 : pub installed_extensions_collection_interval: u64,
138 :
139 : /// Run in development mode, skipping VM-specific operations like process termination
140 : #[arg(long, action = clap::ArgAction::SetTrue)]
141 : pub dev: bool,
142 :
143 : #[arg(long)]
144 : pub pg_init_timeout: Option<u64>,
145 :
146 : #[arg(long, default_value_t = false, action = clap::ArgAction::Set)]
147 : pub lakebase_mode: bool,
148 : }
149 :
150 : impl Cli {
151 : /// Parse a URL from an argument. By default, this isn't necessary, but we
152 : /// want to do some sanity checking.
153 3 : fn parse_remote_ext_base_url(value: &str) -> Result<Url> {
154 : // Remove extra trailing slashes, and add one. We use Url::join() later
155 : // when downloading remote extensions. If the base URL is something like
156 : // http://example.com/pg-ext-s3-gateway, and join() is called with
157 : // something like "xyz", the resulting URL is http://example.com/xyz.
158 3 : let value = value.trim_end_matches('/').to_owned() + "/";
159 3 : let url = Url::parse(&value)?;
160 :
161 3 : if url.query_pairs().count() != 0 {
162 1 : bail!("parameters detected in remote extensions base URL")
163 2 : }
164 :
165 2 : Ok(url)
166 3 : }
167 :
168 : /// For simplicity, we do not escape `privileged_role_name` anywhere in the code.
169 : /// Since it's a system role, which we fully control, that's fine. Still, let's
170 : /// validate it to avoid any surprises.
171 6 : fn parse_privileged_role_name(value: &str) -> Result<String> {
172 : use regex::Regex;
173 :
174 6 : let pattern = Regex::new(r"^[a-z_]+$").unwrap();
175 :
176 6 : if !pattern.is_match(value) {
177 3 : bail!("--privileged-role-name can only contain lowercase letters and underscores")
178 3 : }
179 :
180 3 : Ok(value.to_string())
181 6 : }
182 : }
183 :
184 0 : fn main() -> Result<()> {
185 0 : let cli = Cli::parse();
186 :
187 0 : let scenario = failpoint_support::init();
188 :
189 : // For historical reasons, the main thread that processes the config and launches postgres
190 : // is synchronous, but we always have this tokio runtime available and we "enter" it so
191 : // that you can use tokio::spawn() and tokio::runtime::Handle::current().block_on(...)
192 : // from all parts of compute_ctl.
193 0 : let runtime = tokio::runtime::Builder::new_multi_thread()
194 0 : .enable_all()
195 0 : .build()?;
196 0 : let _rt_guard = runtime.enter();
197 :
198 0 : let mut log_dir = None;
199 0 : if cli.lakebase_mode {
200 0 : log_dir = std::env::var("COMPUTE_CTL_LOG_DIRECTORY").ok();
201 0 : }
202 :
203 0 : let (tracing_provider, _file_logs_guard) = init(cli.dev, log_dir)?;
204 :
205 : // enable core dumping for all child processes
206 0 : setrlimit(Resource::CORE, rlimit::INFINITY, rlimit::INFINITY)?;
207 :
208 0 : installed_extensions::initialize_metrics();
209 0 : hadron_metrics::initialize_metrics();
210 :
211 0 : let connstr = Url::parse(&cli.connstr).context("cannot parse connstr as a URL")?;
212 :
213 0 : let config = get_config(&cli)?;
214 :
215 0 : let compute_node = ComputeNode::new(
216 0 : ComputeNodeParams {
217 0 : compute_id: cli.compute_id,
218 0 : connstr,
219 0 : privileged_role_name: cli.privileged_role_name.clone(),
220 0 : pgdata: cli.pgdata.clone(),
221 0 : pgbin: cli.pgbin.clone(),
222 0 : pgversion: get_pg_version_string(&cli.pgbin),
223 0 : external_http_port: cli.external_http_port,
224 0 : internal_http_port: cli.internal_http_port,
225 0 : remote_ext_base_url: cli.remote_ext_base_url.clone(),
226 0 : resize_swap_on_bind: cli.resize_swap_on_bind,
227 0 : set_disk_quota_for_fs: cli.set_disk_quota_for_fs,
228 0 : #[cfg(target_os = "linux")]
229 0 : filecache_connstr: cli.filecache_connstr,
230 0 : #[cfg(target_os = "linux")]
231 0 : cgroup: cli.cgroup,
232 0 : #[cfg(target_os = "linux")]
233 0 : vm_monitor_addr: cli.vm_monitor_addr,
234 0 : installed_extensions_collection_interval: Arc::new(AtomicU64::new(
235 0 : cli.installed_extensions_collection_interval,
236 0 : )),
237 0 : pg_init_timeout: cli.pg_init_timeout.map(Duration::from_secs),
238 0 : pg_isready_bin: get_pg_isready_bin(&cli.pgbin),
239 0 : instance_id: std::env::var("INSTANCE_ID").ok(),
240 0 : lakebase_mode: cli.lakebase_mode,
241 0 : build_tag: BUILD_TAG.to_string(),
242 0 : control_plane_uri: cli.control_plane_uri,
243 0 : config_path_test_only: cli.config,
244 0 : },
245 0 : config,
246 0 : )?;
247 :
248 0 : let exit_code = compute_node.run()?;
249 :
250 0 : scenario.teardown();
251 :
252 0 : deinit_and_exit(tracing_provider, exit_code);
253 0 : }
254 :
255 0 : fn init(
256 0 : dev_mode: bool,
257 0 : log_dir: Option<String>,
258 0 : ) -> Result<(
259 0 : Option<tracing_utils::Provider>,
260 0 : Option<tracing_appender::non_blocking::WorkerGuard>,
261 0 : )> {
262 0 : let (provider, file_logs_guard) = init_tracing_and_logging(DEFAULT_LOG_LEVEL, &log_dir)?;
263 :
264 0 : let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
265 0 : thread::spawn(move || {
266 0 : for sig in signals.forever() {
267 0 : handle_exit_signal(sig, dev_mode);
268 0 : }
269 0 : });
270 :
271 0 : info!("compute build_tag: {}", &BUILD_TAG.to_string());
272 :
273 0 : Ok((provider, file_logs_guard))
274 0 : }
275 :
276 0 : fn get_config(cli: &Cli) -> Result<ComputeConfig> {
277 : // First, read the config from the path if provided
278 0 : if let Some(ref config) = cli.config {
279 0 : let file = File::open(config)?;
280 0 : return Ok(serde_json::from_reader(&file)?);
281 0 : }
282 :
283 : // If the config wasn't provided in the CLI arguments, then retrieve it from
284 : // the control plane
285 0 : match get_config_from_control_plane(cli.control_plane_uri.as_ref().unwrap(), &cli.compute_id) {
286 0 : Ok(config) => Ok(config),
287 0 : Err(e) => {
288 0 : error!(
289 0 : "cannot get response from control plane: {}\n\
290 0 : neither spec nor confirmation that compute is in the Empty state was received",
291 : e
292 : );
293 0 : Err(e)
294 : }
295 : }
296 0 : }
297 :
298 0 : fn deinit_and_exit(tracing_provider: Option<tracing_utils::Provider>, exit_code: Option<i32>) -> ! {
299 0 : if let Some(p) = tracing_provider {
300 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
301 : // pending traces before we exit. Shutting down OTEL tracing provider may
302 : // hang for quite some time, see, for example:
303 : // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
304 : // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
305 : //
306 : // Yet, we want computes to shut down fast enough, as we may need a new one
307 : // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
308 : // complete, then just error out and exit the main thread.
309 0 : info!("shutting down tracing");
310 0 : let (sender, receiver) = mpsc::channel();
311 0 : let _ = thread::spawn(move || {
312 0 : _ = p.shutdown();
313 0 : sender.send(()).ok()
314 0 : });
315 0 : let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
316 0 : if shutdown_res.is_err() {
317 0 : error!("timed out while shutting down tracing, exiting anyway");
318 0 : }
319 0 : }
320 :
321 0 : info!("shutting down");
322 0 : exit(exit_code.unwrap_or(1))
323 : }
324 :
325 : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
326 : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
327 : /// wait for termination which would be easy then.
328 0 : fn handle_exit_signal(sig: i32, dev_mode: bool) {
329 0 : info!("received {sig} termination signal");
330 0 : forward_termination_signal(dev_mode);
331 0 : exit(1);
332 : }
333 :
334 : #[cfg(test)]
335 : mod test {
336 : use clap::{CommandFactory, Parser};
337 : use url::Url;
338 :
339 : use super::Cli;
340 :
341 : #[test]
342 1 : fn verify_cli() {
343 1 : Cli::command().debug_assert()
344 1 : }
345 :
346 : #[test]
347 1 : fn verify_remote_ext_base_url() {
348 1 : let cli = Cli::parse_from([
349 1 : "compute_ctl",
350 1 : "--pgdata=test",
351 1 : "--connstr=test",
352 1 : "--compute-id=test",
353 1 : "--remote-ext-base-url",
354 1 : "https://example.com/subpath",
355 1 : ]);
356 1 : assert_eq!(
357 1 : cli.remote_ext_base_url.unwrap(),
358 1 : Url::parse("https://example.com/subpath/").unwrap()
359 : );
360 :
361 1 : let cli = Cli::parse_from([
362 1 : "compute_ctl",
363 1 : "--pgdata=test",
364 1 : "--connstr=test",
365 1 : "--compute-id=test",
366 1 : "--remote-ext-base-url",
367 1 : "https://example.com//",
368 1 : ]);
369 1 : assert_eq!(
370 1 : cli.remote_ext_base_url.unwrap(),
371 1 : Url::parse("https://example.com").unwrap()
372 : );
373 :
374 1 : Cli::try_parse_from([
375 1 : "compute_ctl",
376 1 : "--pgdata=test",
377 1 : "--connstr=test",
378 1 : "--compute-id=test",
379 1 : "--remote-ext-base-url",
380 1 : "https://example.com?hello=world",
381 1 : ])
382 1 : .expect_err("URL parameters are not allowed");
383 1 : }
384 :
385 : #[test]
386 1 : fn verify_privileged_role_name() {
387 : // Valid name
388 1 : let cli = Cli::parse_from([
389 1 : "compute_ctl",
390 1 : "--pgdata=test",
391 1 : "--connstr=test",
392 1 : "--compute-id=test",
393 1 : "--privileged-role-name",
394 1 : "my_superuser",
395 1 : ]);
396 1 : assert_eq!(cli.privileged_role_name, "my_superuser");
397 :
398 : // Invalid names
399 1 : Cli::try_parse_from([
400 1 : "compute_ctl",
401 1 : "--pgdata=test",
402 1 : "--connstr=test",
403 1 : "--compute-id=test",
404 1 : "--privileged-role-name",
405 1 : "NeonSuperuser",
406 1 : ])
407 1 : .expect_err("uppercase letters are not allowed");
408 :
409 1 : Cli::try_parse_from([
410 1 : "compute_ctl",
411 1 : "--pgdata=test",
412 1 : "--connstr=test",
413 1 : "--compute-id=test",
414 1 : "--privileged-role-name",
415 1 : "$'neon_superuser",
416 1 : ])
417 1 : .expect_err("special characters are not allowed");
418 :
419 1 : Cli::try_parse_from([
420 1 : "compute_ctl",
421 1 : "--pgdata=test",
422 1 : "--connstr=test",
423 1 : "--compute-id=test",
424 1 : "--privileged-role-name",
425 1 : "",
426 1 : ])
427 1 : .expect_err("empty name is not allowed");
428 1 : }
429 : }
|