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