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::logger::*;
53 : use compute_tools::params::*;
54 : use compute_tools::pg_isready::get_pg_isready_bin;
55 : use compute_tools::spec::*;
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 : let connstr = Url::parse(&cli.connstr).context("cannot parse connstr as a URL")?;
209 :
210 0 : let config = get_config(&cli)?;
211 :
212 0 : let compute_node = ComputeNode::new(
213 0 : ComputeNodeParams {
214 0 : compute_id: cli.compute_id,
215 0 : connstr,
216 0 : privileged_role_name: cli.privileged_role_name.clone(),
217 0 : pgdata: cli.pgdata.clone(),
218 0 : pgbin: cli.pgbin.clone(),
219 0 : pgversion: get_pg_version_string(&cli.pgbin),
220 0 : external_http_port: cli.external_http_port,
221 0 : internal_http_port: cli.internal_http_port,
222 0 : remote_ext_base_url: cli.remote_ext_base_url.clone(),
223 0 : resize_swap_on_bind: cli.resize_swap_on_bind,
224 0 : set_disk_quota_for_fs: cli.set_disk_quota_for_fs,
225 0 : #[cfg(target_os = "linux")]
226 0 : filecache_connstr: cli.filecache_connstr,
227 0 : #[cfg(target_os = "linux")]
228 0 : cgroup: cli.cgroup,
229 0 : #[cfg(target_os = "linux")]
230 0 : vm_monitor_addr: cli.vm_monitor_addr,
231 0 : installed_extensions_collection_interval: Arc::new(AtomicU64::new(
232 0 : cli.installed_extensions_collection_interval,
233 0 : )),
234 0 : pg_init_timeout: cli.pg_init_timeout.map(Duration::from_secs),
235 0 : pg_isready_bin: get_pg_isready_bin(&cli.pgbin),
236 0 : instance_id: std::env::var("INSTANCE_ID").ok(),
237 0 : lakebase_mode: cli.lakebase_mode,
238 0 : },
239 0 : config,
240 0 : )?;
241 :
242 0 : let exit_code = compute_node.run()?;
243 :
244 0 : scenario.teardown();
245 :
246 0 : deinit_and_exit(tracing_provider, exit_code);
247 0 : }
248 :
249 0 : fn init(
250 0 : dev_mode: bool,
251 0 : log_dir: Option<String>,
252 0 : ) -> Result<(
253 0 : Option<tracing_utils::Provider>,
254 0 : Option<tracing_appender::non_blocking::WorkerGuard>,
255 0 : )> {
256 0 : let (provider, file_logs_guard) = init_tracing_and_logging(DEFAULT_LOG_LEVEL, &log_dir)?;
257 :
258 0 : let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
259 0 : thread::spawn(move || {
260 0 : for sig in signals.forever() {
261 0 : handle_exit_signal(sig, dev_mode);
262 0 : }
263 0 : });
264 :
265 0 : info!("compute build_tag: {}", &BUILD_TAG.to_string());
266 :
267 0 : Ok((provider, file_logs_guard))
268 0 : }
269 :
270 0 : fn get_config(cli: &Cli) -> Result<ComputeConfig> {
271 : // First, read the config from the path if provided
272 0 : if let Some(ref config) = cli.config {
273 0 : let file = File::open(config)?;
274 0 : return Ok(serde_json::from_reader(&file)?);
275 0 : }
276 :
277 : // If the config wasn't provided in the CLI arguments, then retrieve it from
278 : // the control plane
279 0 : match get_config_from_control_plane(cli.control_plane_uri.as_ref().unwrap(), &cli.compute_id) {
280 0 : Ok(config) => Ok(config),
281 0 : Err(e) => {
282 0 : error!(
283 0 : "cannot get response from control plane: {}\n\
284 0 : neither spec nor confirmation that compute is in the Empty state was received",
285 : e
286 : );
287 0 : Err(e)
288 : }
289 : }
290 0 : }
291 :
292 0 : fn deinit_and_exit(tracing_provider: Option<tracing_utils::Provider>, exit_code: Option<i32>) -> ! {
293 0 : if let Some(p) = tracing_provider {
294 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
295 : // pending traces before we exit. Shutting down OTEL tracing provider may
296 : // hang for quite some time, see, for example:
297 : // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
298 : // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
299 : //
300 : // Yet, we want computes to shut down fast enough, as we may need a new one
301 : // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
302 : // complete, then just error out and exit the main thread.
303 0 : info!("shutting down tracing");
304 0 : let (sender, receiver) = mpsc::channel();
305 0 : let _ = thread::spawn(move || {
306 0 : _ = p.shutdown();
307 0 : sender.send(()).ok()
308 0 : });
309 0 : let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
310 0 : if shutdown_res.is_err() {
311 0 : error!("timed out while shutting down tracing, exiting anyway");
312 0 : }
313 0 : }
314 :
315 0 : info!("shutting down");
316 0 : exit(exit_code.unwrap_or(1))
317 : }
318 :
319 : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
320 : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
321 : /// wait for termination which would be easy then.
322 0 : fn handle_exit_signal(sig: i32, dev_mode: bool) {
323 0 : info!("received {sig} termination signal");
324 0 : forward_termination_signal(dev_mode);
325 0 : exit(1);
326 : }
327 :
328 : #[cfg(test)]
329 : mod test {
330 : use clap::{CommandFactory, Parser};
331 : use url::Url;
332 :
333 : use super::Cli;
334 :
335 : #[test]
336 1 : fn verify_cli() {
337 1 : Cli::command().debug_assert()
338 1 : }
339 :
340 : #[test]
341 1 : fn verify_remote_ext_base_url() {
342 1 : let cli = Cli::parse_from([
343 1 : "compute_ctl",
344 1 : "--pgdata=test",
345 1 : "--connstr=test",
346 1 : "--compute-id=test",
347 1 : "--remote-ext-base-url",
348 1 : "https://example.com/subpath",
349 1 : ]);
350 1 : assert_eq!(
351 1 : cli.remote_ext_base_url.unwrap(),
352 1 : Url::parse("https://example.com/subpath/").unwrap()
353 : );
354 :
355 1 : let cli = Cli::parse_from([
356 1 : "compute_ctl",
357 1 : "--pgdata=test",
358 1 : "--connstr=test",
359 1 : "--compute-id=test",
360 1 : "--remote-ext-base-url",
361 1 : "https://example.com//",
362 1 : ]);
363 1 : assert_eq!(
364 1 : cli.remote_ext_base_url.unwrap(),
365 1 : Url::parse("https://example.com").unwrap()
366 : );
367 :
368 1 : Cli::try_parse_from([
369 1 : "compute_ctl",
370 1 : "--pgdata=test",
371 1 : "--connstr=test",
372 1 : "--compute-id=test",
373 1 : "--remote-ext-base-url",
374 1 : "https://example.com?hello=world",
375 1 : ])
376 1 : .expect_err("URL parameters are not allowed");
377 1 : }
378 :
379 : #[test]
380 1 : fn verify_privileged_role_name() {
381 : // Valid name
382 1 : let cli = Cli::parse_from([
383 1 : "compute_ctl",
384 1 : "--pgdata=test",
385 1 : "--connstr=test",
386 1 : "--compute-id=test",
387 1 : "--privileged-role-name",
388 1 : "my_superuser",
389 1 : ]);
390 1 : assert_eq!(cli.privileged_role_name, "my_superuser");
391 :
392 : // Invalid names
393 1 : Cli::try_parse_from([
394 1 : "compute_ctl",
395 1 : "--pgdata=test",
396 1 : "--connstr=test",
397 1 : "--compute-id=test",
398 1 : "--privileged-role-name",
399 1 : "NeonSuperuser",
400 1 : ])
401 1 : .expect_err("uppercase letters are not allowed");
402 :
403 1 : Cli::try_parse_from([
404 1 : "compute_ctl",
405 1 : "--pgdata=test",
406 1 : "--connstr=test",
407 1 : "--compute-id=test",
408 1 : "--privileged-role-name",
409 1 : "$'neon_superuser",
410 1 : ])
411 1 : .expect_err("special characters are not allowed");
412 :
413 1 : Cli::try_parse_from([
414 1 : "compute_ctl",
415 1 : "--pgdata=test",
416 1 : "--connstr=test",
417 1 : "--compute-id=test",
418 1 : "--privileged-role-name",
419 1 : "",
420 1 : ])
421 1 : .expect_err("empty name is not allowed");
422 1 : }
423 : }
|