Line data Source code
1 : /// The attachment service mimics the aspects of the control plane API
2 : /// that are required for a pageserver to operate.
3 : ///
4 : /// This enables running & testing pageservers without a full-blown
5 : /// deployment of the Neon cloud platform.
6 : ///
7 : use anyhow::{anyhow, Context};
8 : use attachment_service::http::make_router;
9 : use attachment_service::metrics::preinitialize_metrics;
10 : use attachment_service::persistence::Persistence;
11 : use attachment_service::service::{Config, Service};
12 : use aws_config::{self, BehaviorVersion, Region};
13 : use camino::Utf8PathBuf;
14 : use clap::Parser;
15 : use diesel::Connection;
16 : use metrics::launch_timestamp::LaunchTimestamp;
17 : use std::sync::Arc;
18 : use tokio::signal::unix::SignalKind;
19 : use tokio_util::sync::CancellationToken;
20 : use utils::auth::{JwtAuth, SwappableJwtAuth};
21 : use utils::logging::{self, LogFormat};
22 :
23 : use utils::{project_build_tag, project_git_version, tcp_listener};
24 :
25 : project_git_version!(GIT_VERSION);
26 : project_build_tag!(BUILD_TAG);
27 :
28 : use diesel_migrations::{embed_migrations, EmbeddedMigrations};
29 : pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
30 :
31 0 : #[derive(Parser)]
32 : #[command(author, version, about, long_about = None)]
33 : #[command(arg_required_else_help(true))]
34 : struct Cli {
35 : /// Host and port to listen on, like `127.0.0.1:1234`
36 : #[arg(short, long)]
37 0 : listen: std::net::SocketAddr,
38 :
39 : /// Public key for JWT authentication of clients
40 : #[arg(long)]
41 : public_key: Option<String>,
42 :
43 : /// Token for authenticating this service with the pageservers it controls
44 : #[arg(long)]
45 : jwt_token: Option<String>,
46 :
47 : /// Token for authenticating this service with the control plane, when calling
48 : /// the compute notification endpoint
49 : #[arg(long)]
50 : control_plane_jwt_token: Option<String>,
51 :
52 : /// URL to control plane compute notification endpoint
53 : #[arg(long)]
54 : compute_hook_url: Option<String>,
55 :
56 : /// Path to the .json file to store state (will be created if it doesn't exist)
57 : #[arg(short, long)]
58 : path: Option<Utf8PathBuf>,
59 :
60 : /// URL to connect to postgres, like postgresql://localhost:1234/attachment_service
61 : #[arg(long)]
62 : database_url: Option<String>,
63 : }
64 :
65 : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
66 : /// type encapsulates the logic to decide which and do the loading.
67 : struct Secrets {
68 : database_url: String,
69 : public_key: Option<JwtAuth>,
70 : jwt_token: Option<String>,
71 : control_plane_jwt_token: Option<String>,
72 : }
73 :
74 : impl Secrets {
75 : const DATABASE_URL_SECRET: &'static str = "rds-neon-storage-controller-url";
76 : const PAGESERVER_JWT_TOKEN_SECRET: &'static str =
77 : "neon-storage-controller-pageserver-jwt-token";
78 : const CONTROL_PLANE_JWT_TOKEN_SECRET: &'static str =
79 : "neon-storage-controller-control-plane-jwt-token";
80 : const PUBLIC_KEY_SECRET: &'static str = "neon-storage-controller-public-key";
81 :
82 0 : async fn load(args: &Cli) -> anyhow::Result<Self> {
83 0 : match &args.database_url {
84 0 : Some(url) => Self::load_cli(url, args),
85 0 : None => Self::load_aws_sm().await,
86 : }
87 0 : }
88 :
89 0 : async fn load_aws_sm() -> anyhow::Result<Self> {
90 0 : let Ok(region) = std::env::var("AWS_REGION") else {
91 0 : anyhow::bail!("AWS_REGION is not set, cannot load secrets automatically: either set this, or use CLI args to supply secrets");
92 : };
93 0 : let config = aws_config::defaults(BehaviorVersion::v2023_11_09())
94 0 : .region(Region::new(region.clone()))
95 0 : .load()
96 0 : .await;
97 :
98 0 : let asm = aws_sdk_secretsmanager::Client::new(&config);
99 :
100 0 : let Some(database_url) = asm
101 0 : .get_secret_value()
102 0 : .secret_id(Self::DATABASE_URL_SECRET)
103 0 : .send()
104 0 : .await?
105 0 : .secret_string()
106 0 : .map(str::to_string)
107 : else {
108 0 : anyhow::bail!(
109 0 : "Database URL secret not found at {region}/{}",
110 0 : Self::DATABASE_URL_SECRET
111 0 : )
112 : };
113 :
114 0 : let jwt_token = asm
115 0 : .get_secret_value()
116 0 : .secret_id(Self::PAGESERVER_JWT_TOKEN_SECRET)
117 0 : .send()
118 0 : .await?
119 0 : .secret_string()
120 0 : .map(str::to_string);
121 0 : if jwt_token.is_none() {
122 0 : tracing::warn!("No pageserver JWT token set: this will only work if authentication is disabled on the pageserver");
123 0 : }
124 :
125 0 : let control_plane_jwt_token = asm
126 0 : .get_secret_value()
127 0 : .secret_id(Self::CONTROL_PLANE_JWT_TOKEN_SECRET)
128 0 : .send()
129 0 : .await?
130 0 : .secret_string()
131 0 : .map(str::to_string);
132 0 : if jwt_token.is_none() {
133 0 : tracing::warn!("No control plane JWT token set: this will only work if authentication is disabled on the pageserver");
134 0 : }
135 :
136 0 : let public_key = asm
137 0 : .get_secret_value()
138 0 : .secret_id(Self::PUBLIC_KEY_SECRET)
139 0 : .send()
140 0 : .await?
141 0 : .secret_string()
142 0 : .map(str::to_string);
143 0 : let public_key = match public_key {
144 0 : Some(key) => Some(JwtAuth::from_key(key)?),
145 : None => {
146 0 : tracing::warn!(
147 0 : "No public key set: inccoming HTTP requests will not be authenticated"
148 0 : );
149 0 : None
150 : }
151 : };
152 :
153 0 : Ok(Self {
154 0 : database_url,
155 0 : public_key,
156 0 : jwt_token,
157 0 : control_plane_jwt_token,
158 0 : })
159 0 : }
160 :
161 0 : fn load_cli(database_url: &str, args: &Cli) -> anyhow::Result<Self> {
162 0 : let public_key = match &args.public_key {
163 0 : None => None,
164 0 : Some(key) => Some(JwtAuth::from_key(key.clone()).context("Loading public key")?),
165 : };
166 0 : Ok(Self {
167 0 : database_url: database_url.to_owned(),
168 0 : public_key,
169 0 : jwt_token: args.jwt_token.clone(),
170 0 : control_plane_jwt_token: args.control_plane_jwt_token.clone(),
171 0 : })
172 0 : }
173 : }
174 :
175 : /// Execute the diesel migrations that are built into this binary
176 0 : async fn migration_run(database_url: &str) -> anyhow::Result<()> {
177 : use diesel::PgConnection;
178 : use diesel_migrations::{HarnessWithOutput, MigrationHarness};
179 0 : let mut conn = PgConnection::establish(database_url)?;
180 :
181 0 : HarnessWithOutput::write_to_stdout(&mut conn)
182 0 : .run_pending_migrations(MIGRATIONS)
183 0 : .map(|_| ())
184 0 : .map_err(|e| anyhow::anyhow!(e))?;
185 :
186 0 : Ok(())
187 0 : }
188 :
189 0 : fn main() -> anyhow::Result<()> {
190 0 : tokio::runtime::Builder::new_current_thread()
191 0 : // We use spawn_blocking for database operations, so require approximately
192 0 : // as many blocking threads as we will open database connections.
193 0 : .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
194 0 : .enable_all()
195 0 : .build()
196 0 : .unwrap()
197 0 : .block_on(async_main())
198 0 : }
199 :
200 0 : async fn async_main() -> anyhow::Result<()> {
201 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
202 0 :
203 0 : logging::init(
204 0 : LogFormat::Plain,
205 0 : logging::TracingErrorLayerEnablement::Disabled,
206 0 : logging::Output::Stdout,
207 0 : )?;
208 :
209 0 : preinitialize_metrics();
210 0 :
211 0 : let args = Cli::parse();
212 0 : tracing::info!(
213 0 : "version: {}, launch_timestamp: {}, build_tag {}, state at {}, listening on {}",
214 0 : GIT_VERSION,
215 0 : launch_ts.to_string(),
216 0 : BUILD_TAG,
217 0 : args.path.as_ref().unwrap_or(&Utf8PathBuf::from("<none>")),
218 0 : args.listen
219 0 : );
220 :
221 0 : let secrets = Secrets::load(&args).await?;
222 :
223 0 : let config = Config {
224 0 : jwt_token: secrets.jwt_token,
225 0 : control_plane_jwt_token: secrets.control_plane_jwt_token,
226 0 : compute_hook_url: args.compute_hook_url,
227 0 : };
228 0 :
229 0 : // After loading secrets & config, but before starting anything else, apply database migrations
230 0 : migration_run(&secrets.database_url)
231 0 : .await
232 0 : .context("Running database migrations")?;
233 :
234 0 : let json_path = args.path;
235 0 : let persistence = Arc::new(Persistence::new(secrets.database_url, json_path.clone()));
236 :
237 0 : let service = Service::spawn(config, persistence.clone()).await?;
238 :
239 0 : let http_listener = tcp_listener::bind(args.listen)?;
240 :
241 0 : let auth = secrets
242 0 : .public_key
243 0 : .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
244 0 : let router = make_router(service.clone(), auth)
245 0 : .build()
246 0 : .map_err(|err| anyhow!(err))?;
247 0 : let router_service = utils::http::RouterService::new(router).unwrap();
248 0 :
249 0 : // Start HTTP server
250 0 : let server_shutdown = CancellationToken::new();
251 0 : let server = hyper::Server::from_tcp(http_listener)?
252 0 : .serve(router_service)
253 0 : .with_graceful_shutdown({
254 0 : let server_shutdown = server_shutdown.clone();
255 0 : async move {
256 0 : server_shutdown.cancelled().await;
257 0 : }
258 0 : });
259 0 : tracing::info!("Serving on {0}", args.listen);
260 0 : let server_task = tokio::task::spawn(server);
261 :
262 : // Wait until we receive a signal
263 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
264 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
265 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
266 0 : tokio::select! {
267 0 : _ = sigint.recv() => {},
268 0 : _ = sigterm.recv() => {},
269 0 : _ = sigquit.recv() => {},
270 0 : }
271 0 : tracing::info!("Terminating on signal");
272 :
273 0 : if json_path.is_some() {
274 : // Write out a JSON dump on shutdown: this is used in compat tests to avoid passing
275 : // full postgres dumps around.
276 0 : if let Err(e) = persistence.write_tenants_json().await {
277 0 : tracing::error!("Failed to write JSON on shutdown: {e}")
278 0 : }
279 0 : }
280 :
281 : // Stop HTTP server first, so that we don't have to service requests
282 : // while shutting down Service
283 0 : server_shutdown.cancel();
284 0 : if let Err(e) = server_task.await {
285 0 : tracing::error!("Error joining HTTP server task: {e}")
286 0 : }
287 0 : tracing::info!("Joined HTTP server task");
288 :
289 0 : service.shutdown().await;
290 0 : tracing::info!("Service shutdown complete");
291 :
292 0 : std::process::exit(0);
293 0 : }
|