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::{
13 : Config, Service, MAX_UNAVAILABLE_INTERVAL_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT,
14 : };
15 : use tokio::signal::unix::SignalKind;
16 : use tokio_util::sync::CancellationToken;
17 : use utils::auth::{JwtAuth, SwappableJwtAuth};
18 : use utils::logging::{self, LogFormat};
19 :
20 : use utils::sentry_init::init_sentry;
21 : use utils::{project_build_tag, project_git_version, tcp_listener};
22 :
23 : project_git_version!(GIT_VERSION);
24 : project_build_tag!(BUILD_TAG);
25 :
26 : use diesel_migrations::{embed_migrations, EmbeddedMigrations};
27 : pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
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 : /// URL to control plane compute notification endpoint
51 : #[arg(long)]
52 : compute_hook_url: Option<String>,
53 :
54 : /// URL to connect to postgres, like postgresql://localhost:1234/storage_controller
55 : #[arg(long)]
56 : database_url: Option<String>,
57 :
58 : /// Flag to enable dev mode, which permits running without auth
59 : #[arg(long, default_value = "false")]
60 0 : dev: bool,
61 :
62 : /// Grace period before marking unresponsive pageserver offline
63 : #[arg(long)]
64 : max_unavailable_interval: Option<humantime::Duration>,
65 :
66 : /// Size threshold for automatically splitting shards (disabled by default)
67 : #[arg(long)]
68 : split_threshold: Option<u64>,
69 :
70 : /// Maximum number of reconcilers that may run in parallel
71 : #[arg(long)]
72 : reconciler_concurrency: Option<usize>,
73 :
74 : /// How long to wait for the initial database connection to be available.
75 : #[arg(long, default_value = "5s")]
76 0 : db_connect_timeout: humantime::Duration,
77 :
78 : /// `neon_local` sets this to the path of the neon_local repo dir.
79 : /// Only relevant for testing.
80 : // TODO: make `cfg(feature = "testing")`
81 : #[arg(long)]
82 : neon_local_repo_dir: Option<PathBuf>,
83 : }
84 :
85 : enum StrictMode {
86 : /// In strict mode, we will require that all secrets are loaded, i.e. security features
87 : /// may not be implicitly turned off by omitting secrets in the environment.
88 : Strict,
89 : /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
90 : /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
91 : /// requests, no public key -> don't authenticate incoming requests).
92 : Dev,
93 : }
94 :
95 : impl Default for StrictMode {
96 0 : fn default() -> Self {
97 0 : Self::Strict
98 0 : }
99 : }
100 :
101 : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
102 : /// type encapsulates the logic to decide which and do the loading.
103 : struct Secrets {
104 : database_url: String,
105 : public_key: Option<JwtAuth>,
106 : jwt_token: Option<String>,
107 : control_plane_jwt_token: Option<String>,
108 : }
109 :
110 : impl Secrets {
111 : const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
112 : const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
113 : const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
114 : const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
115 :
116 : /// Load secrets from, in order of preference:
117 : /// - CLI args if database URL is provided on the CLI
118 : /// - Environment variables if DATABASE_URL is set.
119 : /// - AWS Secrets Manager secrets
120 0 : async fn load(args: &Cli) -> anyhow::Result<Self> {
121 0 : let Some(database_url) =
122 0 : Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV).await
123 : else {
124 0 : anyhow::bail!(
125 0 : "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
126 0 : )
127 : };
128 :
129 0 : let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV).await {
130 0 : Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
131 0 : None => None,
132 : };
133 :
134 0 : let this = Self {
135 0 : database_url,
136 0 : public_key,
137 0 : jwt_token: Self::load_secret(&args.jwt_token, Self::PAGESERVER_JWT_TOKEN_ENV).await,
138 0 : control_plane_jwt_token: Self::load_secret(
139 0 : &args.control_plane_jwt_token,
140 0 : Self::CONTROL_PLANE_JWT_TOKEN_ENV,
141 0 : )
142 0 : .await,
143 : };
144 :
145 0 : Ok(this)
146 0 : }
147 :
148 0 : async fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
149 0 : if let Some(v) = cli {
150 0 : Some(v.clone())
151 0 : } else if let Ok(v) = std::env::var(env_name) {
152 0 : Some(v)
153 : } else {
154 0 : None
155 : }
156 0 : }
157 : }
158 :
159 : /// Execute the diesel migrations that are built into this binary
160 0 : async fn migration_run(database_url: &str) -> anyhow::Result<()> {
161 : use diesel::PgConnection;
162 : use diesel_migrations::{HarnessWithOutput, MigrationHarness};
163 0 : let mut conn = PgConnection::establish(database_url)?;
164 :
165 0 : HarnessWithOutput::write_to_stdout(&mut conn)
166 0 : .run_pending_migrations(MIGRATIONS)
167 0 : .map(|_| ())
168 0 : .map_err(|e| anyhow::anyhow!(e))?;
169 :
170 0 : Ok(())
171 0 : }
172 :
173 0 : fn main() -> anyhow::Result<()> {
174 0 : let default_panic = std::panic::take_hook();
175 0 : std::panic::set_hook(Box::new(move |info| {
176 0 : default_panic(info);
177 0 : std::process::exit(1);
178 0 : }));
179 0 :
180 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
181 0 :
182 0 : tokio::runtime::Builder::new_current_thread()
183 0 : // We use spawn_blocking for database operations, so require approximately
184 0 : // as many blocking threads as we will open database connections.
185 0 : .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
186 0 : .enable_all()
187 0 : .build()
188 0 : .unwrap()
189 0 : .block_on(async_main())
190 0 : }
191 :
192 0 : async fn async_main() -> anyhow::Result<()> {
193 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
194 0 :
195 0 : logging::init(
196 0 : LogFormat::Plain,
197 0 : logging::TracingErrorLayerEnablement::Disabled,
198 0 : logging::Output::Stdout,
199 0 : )?;
200 :
201 0 : preinitialize_metrics();
202 0 :
203 0 : let args = Cli::parse();
204 0 : tracing::info!(
205 0 : "version: {}, launch_timestamp: {}, build_tag {}, listening on {}",
206 0 : GIT_VERSION,
207 0 : launch_ts.to_string(),
208 : BUILD_TAG,
209 : args.listen
210 : );
211 :
212 0 : let build_info = BuildInfo {
213 0 : revision: GIT_VERSION,
214 0 : build_tag: BUILD_TAG,
215 0 : };
216 :
217 0 : let strict_mode = if args.dev {
218 0 : StrictMode::Dev
219 : } else {
220 0 : StrictMode::Strict
221 : };
222 :
223 0 : let secrets = Secrets::load(&args).await?;
224 :
225 : // Validate required secrets and arguments are provided in strict mode
226 0 : match strict_mode {
227 : StrictMode::Strict
228 0 : if (secrets.public_key.is_none()
229 0 : || secrets.jwt_token.is_none()
230 0 : || secrets.control_plane_jwt_token.is_none()) =>
231 0 : {
232 0 : // Production systems should always have secrets configured: if public_key was not set
233 0 : // then we would implicitly disable auth.
234 0 : anyhow::bail!(
235 0 : "Insecure config! One or more secrets is not set. This is only permitted in `--dev` mode"
236 0 : );
237 : }
238 0 : StrictMode::Strict if args.compute_hook_url.is_none() => {
239 0 : // Production systems should always have a compute hook set, to prevent falling
240 0 : // back to trying to use neon_local.
241 0 : anyhow::bail!(
242 0 : "`--compute-hook-url` is not set: this is only permitted in `--dev` mode"
243 0 : );
244 : }
245 : StrictMode::Strict => {
246 0 : tracing::info!("Starting in strict mode: configuration is OK.")
247 : }
248 : StrictMode::Dev => {
249 0 : tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
250 : }
251 : }
252 :
253 0 : let config = Config {
254 0 : jwt_token: secrets.jwt_token,
255 0 : control_plane_jwt_token: secrets.control_plane_jwt_token,
256 0 : compute_hook_url: args.compute_hook_url,
257 0 : max_unavailable_interval: args
258 0 : .max_unavailable_interval
259 0 : .map(humantime::Duration::into)
260 0 : .unwrap_or(MAX_UNAVAILABLE_INTERVAL_DEFAULT),
261 0 : reconciler_concurrency: args
262 0 : .reconciler_concurrency
263 0 : .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
264 0 : split_threshold: args.split_threshold,
265 0 : neon_local_repo_dir: args.neon_local_repo_dir,
266 0 : };
267 0 :
268 0 : // After loading secrets & config, but before starting anything else, apply database migrations
269 0 : Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
270 :
271 0 : migration_run(&secrets.database_url)
272 0 : .await
273 0 : .context("Running database migrations")?;
274 :
275 0 : let persistence = Arc::new(Persistence::new(secrets.database_url));
276 :
277 0 : let service = Service::spawn(config, persistence.clone()).await?;
278 :
279 0 : let http_listener = tcp_listener::bind(args.listen)?;
280 :
281 0 : let auth = secrets
282 0 : .public_key
283 0 : .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
284 0 : let router = make_router(service.clone(), auth, build_info)
285 0 : .build()
286 0 : .map_err(|err| anyhow!(err))?;
287 0 : let router_service = utils::http::RouterService::new(router).unwrap();
288 0 :
289 0 : // Start HTTP server
290 0 : let server_shutdown = CancellationToken::new();
291 0 : let server = hyper::Server::from_tcp(http_listener)?
292 0 : .serve(router_service)
293 0 : .with_graceful_shutdown({
294 0 : let server_shutdown = server_shutdown.clone();
295 0 : async move {
296 0 : server_shutdown.cancelled().await;
297 0 : }
298 0 : });
299 0 : tracing::info!("Serving on {0}", args.listen);
300 0 : let server_task = tokio::task::spawn(server);
301 :
302 : // Wait until we receive a signal
303 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
304 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
305 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
306 : tokio::select! {
307 : _ = sigint.recv() => {},
308 : _ = sigterm.recv() => {},
309 : _ = sigquit.recv() => {},
310 : }
311 0 : tracing::info!("Terminating on signal");
312 :
313 : // Stop HTTP server first, so that we don't have to service requests
314 : // while shutting down Service.
315 0 : server_shutdown.cancel();
316 0 : match tokio::time::timeout(Duration::from_secs(5), server_task).await {
317 : Ok(Ok(_)) => {
318 0 : tracing::info!("Joined HTTP server task");
319 : }
320 0 : Ok(Err(e)) => {
321 0 : tracing::error!("Error joining HTTP server task: {e}")
322 : }
323 : Err(_) => {
324 0 : tracing::warn!("Timed out joining HTTP server task");
325 : // We will fall through and shut down the service anyway, any request handlers
326 : // in flight will experience cancellation & their clients will see a torn connection.
327 : }
328 : }
329 :
330 0 : service.shutdown().await;
331 0 : tracing::info!("Service shutdown complete");
332 :
333 0 : std::process::exit(0);
334 0 : }
|