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