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