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