Line data Source code
1 : use anyhow::{anyhow, Context};
2 : use clap::Parser;
3 : use hyper0::Uri;
4 : use metrics::launch_timestamp::LaunchTimestamp;
5 : use metrics::BuildInfo;
6 : use std::path::PathBuf;
7 : use std::sync::Arc;
8 : use std::time::Duration;
9 : use storage_controller::http::make_router;
10 : use storage_controller::metrics::preinitialize_metrics;
11 : use storage_controller::persistence::Persistence;
12 : use storage_controller::service::chaos_injector::ChaosInjector;
13 : use storage_controller::service::{
14 : Config, Service, HEARTBEAT_INTERVAL_DEFAULT, LONG_RECONCILE_THRESHOLD_DEFAULT,
15 : MAX_OFFLINE_INTERVAL_DEFAULT, MAX_WARMING_UP_INTERVAL_DEFAULT,
16 : PRIORITY_RECONCILER_CONCURRENCY_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT,
17 : };
18 : use tokio::signal::unix::SignalKind;
19 : use tokio_util::sync::CancellationToken;
20 : use tracing::Instrument;
21 : use utils::auth::{JwtAuth, SwappableJwtAuth};
22 : use utils::logging::{self, LogFormat};
23 :
24 : use utils::sentry_init::init_sentry;
25 : use utils::{project_build_tag, project_git_version, tcp_listener};
26 :
27 : project_git_version!(GIT_VERSION);
28 : project_build_tag!(BUILD_TAG);
29 :
30 : #[derive(Parser)]
31 : #[command(author, version, about, long_about = None)]
32 : #[command(arg_required_else_help(true))]
33 : struct Cli {
34 : /// Host and port to listen on, like `127.0.0.1:1234`
35 : #[arg(short, long)]
36 0 : listen: std::net::SocketAddr,
37 :
38 : /// Public key for JWT authentication of clients
39 : #[arg(long)]
40 : public_key: Option<String>,
41 :
42 : /// Token for authenticating this service with the pageservers it controls
43 : #[arg(long)]
44 : jwt_token: Option<String>,
45 :
46 : /// Token for authenticating this service with the control plane, when calling
47 : /// the compute notification endpoint
48 : #[arg(long)]
49 : control_plane_jwt_token: Option<String>,
50 :
51 : #[arg(long)]
52 : peer_jwt_token: Option<String>,
53 :
54 : /// URL to control plane compute notification endpoint
55 : #[arg(long)]
56 : compute_hook_url: Option<String>,
57 :
58 : /// URL to connect to postgres, like postgresql://localhost:1234/storage_controller
59 : #[arg(long)]
60 : database_url: Option<String>,
61 :
62 : /// Flag to enable dev mode, which permits running without auth
63 : #[arg(long, default_value = "false")]
64 0 : dev: bool,
65 :
66 : /// Grace period before marking unresponsive pageserver offline
67 : #[arg(long)]
68 : max_offline_interval: Option<humantime::Duration>,
69 :
70 : /// More tolerant grace period before marking unresponsive pagserver offline used
71 : /// around pageserver restarts
72 : #[arg(long)]
73 : max_warming_up_interval: Option<humantime::Duration>,
74 :
75 : /// Size threshold for automatically splitting shards (disabled by default)
76 : #[arg(long)]
77 : split_threshold: Option<u64>,
78 :
79 : /// Maximum number of normal-priority reconcilers that may run in parallel
80 : #[arg(long)]
81 : reconciler_concurrency: Option<usize>,
82 :
83 : /// Maximum number of high-priority reconcilers that may run in parallel
84 : #[arg(long)]
85 : priority_reconciler_concurrency: Option<usize>,
86 :
87 : /// How long to wait for the initial database connection to be available.
88 : #[arg(long, default_value = "5s")]
89 0 : db_connect_timeout: humantime::Duration,
90 :
91 : #[arg(long, default_value = "false")]
92 0 : start_as_candidate: bool,
93 :
94 : // TODO: make this mandatory once the helm chart gets updated
95 : #[arg(long)]
96 : address_for_peers: Option<Uri>,
97 :
98 : /// `neon_local` sets this to the path of the neon_local repo dir.
99 : /// Only relevant for testing.
100 : // TODO: make `cfg(feature = "testing")`
101 : #[arg(long)]
102 : neon_local_repo_dir: Option<PathBuf>,
103 :
104 : /// Chaos testing
105 : #[arg(long)]
106 : chaos_interval: Option<humantime::Duration>,
107 :
108 : // Maximum acceptable lag for the secondary location while draining
109 : // a pageserver
110 : #[arg(long)]
111 : max_secondary_lag_bytes: Option<u64>,
112 :
113 : // Period with which to send heartbeats to registered nodes
114 : #[arg(long)]
115 : heartbeat_interval: Option<humantime::Duration>,
116 :
117 : #[arg(long)]
118 : long_reconcile_threshold: Option<humantime::Duration>,
119 : }
120 :
121 : enum StrictMode {
122 : /// In strict mode, we will require that all secrets are loaded, i.e. security features
123 : /// may not be implicitly turned off by omitting secrets in the environment.
124 : Strict,
125 : /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
126 : /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
127 : /// requests, no public key -> don't authenticate incoming requests).
128 : Dev,
129 : }
130 :
131 : impl Default for StrictMode {
132 0 : fn default() -> Self {
133 0 : Self::Strict
134 0 : }
135 : }
136 :
137 : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
138 : /// type encapsulates the logic to decide which and do the loading.
139 : struct Secrets {
140 : database_url: String,
141 : public_key: Option<JwtAuth>,
142 : jwt_token: Option<String>,
143 : control_plane_jwt_token: Option<String>,
144 : peer_jwt_token: Option<String>,
145 : }
146 :
147 : impl Secrets {
148 : const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
149 : const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
150 : const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
151 : const PEER_JWT_TOKEN_ENV: &'static str = "PEER_JWT_TOKEN";
152 : const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
153 :
154 : /// Load secrets from, in order of preference:
155 : /// - CLI args if database URL is provided on the CLI
156 : /// - Environment variables if DATABASE_URL is set.
157 0 : async fn load(args: &Cli) -> anyhow::Result<Self> {
158 0 : let Some(database_url) = Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV)
159 : else {
160 0 : anyhow::bail!(
161 0 : "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
162 0 : )
163 : };
164 :
165 0 : let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV) {
166 0 : Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
167 0 : None => None,
168 : };
169 :
170 0 : let this = Self {
171 0 : database_url,
172 0 : public_key,
173 0 : jwt_token: Self::load_secret(&args.jwt_token, Self::PAGESERVER_JWT_TOKEN_ENV),
174 0 : control_plane_jwt_token: Self::load_secret(
175 0 : &args.control_plane_jwt_token,
176 0 : Self::CONTROL_PLANE_JWT_TOKEN_ENV,
177 0 : ),
178 0 : peer_jwt_token: Self::load_secret(&args.peer_jwt_token, Self::PEER_JWT_TOKEN_ENV),
179 0 : };
180 0 :
181 0 : Ok(this)
182 0 : }
183 :
184 0 : fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
185 0 : if let Some(v) = cli {
186 0 : Some(v.clone())
187 0 : } else if let Ok(v) = std::env::var(env_name) {
188 0 : Some(v)
189 : } else {
190 0 : None
191 : }
192 0 : }
193 : }
194 :
195 0 : fn main() -> anyhow::Result<()> {
196 0 : logging::init(
197 0 : LogFormat::Plain,
198 0 : logging::TracingErrorLayerEnablement::Disabled,
199 0 : logging::Output::Stdout,
200 0 : )?;
201 :
202 : // log using tracing so we don't get confused output by default hook writing to stderr
203 0 : utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
204 0 :
205 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
206 0 :
207 0 : let hook = std::panic::take_hook();
208 0 : std::panic::set_hook(Box::new(move |info| {
209 0 : // let sentry send a message (and flush)
210 0 : // and trace the error
211 0 : hook(info);
212 0 :
213 0 : std::process::exit(1);
214 0 : }));
215 0 :
216 0 : tokio::runtime::Builder::new_current_thread()
217 0 : // We use spawn_blocking for database operations, so require approximately
218 0 : // as many blocking threads as we will open database connections.
219 0 : .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
220 0 : .enable_all()
221 0 : .build()
222 0 : .unwrap()
223 0 : .block_on(async_main())
224 0 : }
225 :
226 0 : async fn async_main() -> anyhow::Result<()> {
227 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
228 0 :
229 0 : preinitialize_metrics();
230 0 :
231 0 : let args = Cli::parse();
232 0 : tracing::info!(
233 0 : "version: {}, launch_timestamp: {}, build_tag {}, listening on {}",
234 0 : GIT_VERSION,
235 0 : launch_ts.to_string(),
236 : BUILD_TAG,
237 : args.listen
238 : );
239 :
240 0 : let build_info = BuildInfo {
241 0 : revision: GIT_VERSION,
242 0 : build_tag: BUILD_TAG,
243 0 : };
244 :
245 0 : let strict_mode = if args.dev {
246 0 : StrictMode::Dev
247 : } else {
248 0 : StrictMode::Strict
249 : };
250 :
251 0 : let secrets = Secrets::load(&args).await?;
252 :
253 : // Validate required secrets and arguments are provided in strict mode
254 0 : match strict_mode {
255 : StrictMode::Strict
256 0 : if (secrets.public_key.is_none()
257 0 : || secrets.jwt_token.is_none()
258 0 : || secrets.control_plane_jwt_token.is_none()) =>
259 0 : {
260 0 : // Production systems should always have secrets configured: if public_key was not set
261 0 : // then we would implicitly disable auth.
262 0 : anyhow::bail!(
263 0 : "Insecure config! One or more secrets is not set. This is only permitted in `--dev` mode"
264 0 : );
265 : }
266 0 : StrictMode::Strict if args.compute_hook_url.is_none() => {
267 0 : // Production systems should always have a compute hook set, to prevent falling
268 0 : // back to trying to use neon_local.
269 0 : anyhow::bail!(
270 0 : "`--compute-hook-url` is not set: this is only permitted in `--dev` mode"
271 0 : );
272 : }
273 : StrictMode::Strict => {
274 0 : tracing::info!("Starting in strict mode: configuration is OK.")
275 : }
276 : StrictMode::Dev => {
277 0 : tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
278 : }
279 : }
280 :
281 0 : let config = Config {
282 0 : jwt_token: secrets.jwt_token,
283 0 : control_plane_jwt_token: secrets.control_plane_jwt_token,
284 0 : peer_jwt_token: secrets.peer_jwt_token,
285 0 : compute_hook_url: args.compute_hook_url,
286 0 : max_offline_interval: args
287 0 : .max_offline_interval
288 0 : .map(humantime::Duration::into)
289 0 : .unwrap_or(MAX_OFFLINE_INTERVAL_DEFAULT),
290 0 : max_warming_up_interval: args
291 0 : .max_warming_up_interval
292 0 : .map(humantime::Duration::into)
293 0 : .unwrap_or(MAX_WARMING_UP_INTERVAL_DEFAULT),
294 0 : reconciler_concurrency: args
295 0 : .reconciler_concurrency
296 0 : .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
297 0 : priority_reconciler_concurrency: args
298 0 : .priority_reconciler_concurrency
299 0 : .unwrap_or(PRIORITY_RECONCILER_CONCURRENCY_DEFAULT),
300 0 : split_threshold: args.split_threshold,
301 0 : neon_local_repo_dir: args.neon_local_repo_dir,
302 0 : max_secondary_lag_bytes: args.max_secondary_lag_bytes,
303 0 : heartbeat_interval: args
304 0 : .heartbeat_interval
305 0 : .map(humantime::Duration::into)
306 0 : .unwrap_or(HEARTBEAT_INTERVAL_DEFAULT),
307 0 : long_reconcile_threshold: args
308 0 : .long_reconcile_threshold
309 0 : .map(humantime::Duration::into)
310 0 : .unwrap_or(LONG_RECONCILE_THRESHOLD_DEFAULT),
311 0 : address_for_peers: args.address_for_peers,
312 0 : start_as_candidate: args.start_as_candidate,
313 0 : http_service_port: args.listen.port() as i32,
314 0 : };
315 0 :
316 0 : // Validate that we can connect to the database
317 0 : Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
318 :
319 0 : let persistence = Arc::new(Persistence::new(secrets.database_url).await);
320 :
321 0 : let service = Service::spawn(config, persistence.clone()).await?;
322 :
323 0 : let http_listener = tcp_listener::bind(args.listen)?;
324 :
325 0 : let auth = secrets
326 0 : .public_key
327 0 : .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
328 0 : let router = make_router(service.clone(), auth, build_info)
329 0 : .build()
330 0 : .map_err(|err| anyhow!(err))?;
331 0 : let router_service = http_utils::RouterService::new(router).unwrap();
332 0 :
333 0 : // Start HTTP server
334 0 : let server_shutdown = CancellationToken::new();
335 0 : let server = hyper0::Server::from_tcp(http_listener)?
336 0 : .serve(router_service)
337 0 : .with_graceful_shutdown({
338 0 : let server_shutdown = server_shutdown.clone();
339 0 : async move {
340 0 : server_shutdown.cancelled().await;
341 0 : }
342 0 : });
343 0 : tracing::info!("Serving on {0}", args.listen);
344 0 : let server_task = tokio::task::spawn(server);
345 0 :
346 0 : let chaos_task = args.chaos_interval.map(|interval| {
347 0 : let service = service.clone();
348 0 : let cancel = CancellationToken::new();
349 0 : let cancel_bg = cancel.clone();
350 0 : (
351 0 : tokio::task::spawn(
352 0 : async move {
353 0 : let mut chaos_injector = ChaosInjector::new(service, interval.into());
354 0 : chaos_injector.run(cancel_bg).await
355 0 : }
356 0 : .instrument(tracing::info_span!("chaos_injector")),
357 : ),
358 0 : cancel,
359 0 : )
360 0 : });
361 :
362 : // Wait until we receive a signal
363 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
364 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
365 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
366 0 : tokio::select! {
367 0 : _ = sigint.recv() => {},
368 0 : _ = sigterm.recv() => {},
369 0 : _ = sigquit.recv() => {},
370 : }
371 0 : tracing::info!("Terminating on signal");
372 :
373 : // Stop HTTP server first, so that we don't have to service requests
374 : // while shutting down Service.
375 0 : server_shutdown.cancel();
376 0 : match tokio::time::timeout(Duration::from_secs(5), server_task).await {
377 : Ok(Ok(_)) => {
378 0 : tracing::info!("Joined HTTP server task");
379 : }
380 0 : Ok(Err(e)) => {
381 0 : tracing::error!("Error joining HTTP server task: {e}")
382 : }
383 : Err(_) => {
384 0 : tracing::warn!("Timed out joining HTTP server task");
385 : // We will fall through and shut down the service anyway, any request handlers
386 : // in flight will experience cancellation & their clients will see a torn connection.
387 : }
388 : }
389 :
390 : // If we were injecting chaos, stop that so that we're not calling into Service while it shuts down
391 0 : if let Some((chaos_jh, chaos_cancel)) = chaos_task {
392 0 : chaos_cancel.cancel();
393 0 : chaos_jh.await.ok();
394 0 : }
395 :
396 0 : service.shutdown().await;
397 0 : tracing::info!("Service shutdown complete");
398 :
399 0 : std::process::exit(0);
400 0 : }
|