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