Line data Source code
1 : use std::fmt::Display;
2 : use std::net::{IpAddr, Ipv6Addr, SocketAddr};
3 : use std::sync::Arc;
4 : use std::time::Duration;
5 :
6 : use anyhow::Result;
7 : use axum::Router;
8 : use axum::middleware::{self};
9 : use axum::response::IntoResponse;
10 : use axum::routing::{get, post};
11 : use compute_api::responses::ComputeCtlConfig;
12 : use http::StatusCode;
13 : use tokio::net::TcpListener;
14 : use tower::ServiceBuilder;
15 : use tower_http::{
16 : auth::AsyncRequireAuthorizationLayer, request_id::PropagateRequestIdLayer, trace::TraceLayer,
17 : };
18 : use tracing::{Span, error, info};
19 :
20 : use super::middleware::request_id::maybe_add_request_id_header;
21 : use super::{
22 : headers::X_REQUEST_ID,
23 : middleware::authorize::Authorize,
24 : routes::{
25 : check_writability, configure, database_schema, dbs_and_roles, extension_server, extensions,
26 : grants, insights, lfc, metrics, metrics_json, promote, status, terminate,
27 : },
28 : };
29 : use crate::compute::ComputeNode;
30 :
31 : /// `compute_ctl` has two servers: internal and external. The internal server
32 : /// binds to the loopback interface and handles communication from clients on
33 : /// the compute. The external server is what receives communication from the
34 : /// control plane, the metrics scraper, etc. We make the distinction because
35 : /// certain routes in `compute_ctl` only need to be exposed to local processes
36 : /// like Postgres via the neon extension and local_proxy.
37 : #[derive(Clone, Debug)]
38 : pub enum Server {
39 : Internal {
40 : port: u16,
41 : },
42 : External {
43 : port: u16,
44 : config: ComputeCtlConfig,
45 : compute_id: String,
46 : },
47 : }
48 :
49 : impl Display for Server {
50 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 0 : match self {
52 0 : Server::Internal { .. } => f.write_str("internal"),
53 0 : Server::External { .. } => f.write_str("external"),
54 : }
55 0 : }
56 : }
57 :
58 : impl From<&Server> for Router<Arc<ComputeNode>> {
59 0 : fn from(server: &Server) -> Self {
60 0 : let mut router = Router::<Arc<ComputeNode>>::new();
61 :
62 0 : router = match server {
63 : Server::Internal { .. } => {
64 0 : router = router
65 0 : .route(
66 0 : "/extension_server/{*filename}",
67 0 : post(extension_server::download_extension),
68 : )
69 0 : .route("/extensions", post(extensions::install_extension))
70 0 : .route("/grants", post(grants::add_grant));
71 :
72 : // Add in any testing support
73 0 : if cfg!(feature = "testing") {
74 : use super::routes::failpoints;
75 :
76 0 : router = router.route("/failpoints", post(failpoints::configure_failpoints));
77 0 : }
78 :
79 0 : router
80 : }
81 : Server::External {
82 0 : config, compute_id, ..
83 : } => {
84 0 : let unauthenticated_router =
85 0 : Router::<Arc<ComputeNode>>::new().route("/metrics", get(metrics::get_metrics));
86 :
87 0 : let authenticated_router = Router::<Arc<ComputeNode>>::new()
88 0 : .route("/lfc/prewarm", get(lfc::prewarm_state).post(lfc::prewarm))
89 0 : .route("/lfc/offload", get(lfc::offload_state).post(lfc::offload))
90 0 : .route("/promote", post(promote::promote))
91 0 : .route("/check_writability", post(check_writability::is_writable))
92 0 : .route("/configure", post(configure::configure))
93 0 : .route("/database_schema", get(database_schema::get_schema_dump))
94 0 : .route("/dbs_and_roles", get(dbs_and_roles::get_catalog_objects))
95 0 : .route("/insights", get(insights::get_insights))
96 0 : .route("/metrics.json", get(metrics_json::get_metrics))
97 0 : .route("/status", get(status::get_status))
98 0 : .route("/terminate", post(terminate::terminate))
99 0 : .layer(AsyncRequireAuthorizationLayer::new(Authorize::new(
100 0 : compute_id.clone(),
101 0 : config.jwks.clone(),
102 : )));
103 :
104 0 : router
105 0 : .merge(unauthenticated_router)
106 0 : .merge(authenticated_router)
107 : }
108 : };
109 :
110 0 : router
111 0 : .fallback(Server::handle_404)
112 0 : .method_not_allowed_fallback(Server::handle_405)
113 0 : .layer(
114 0 : ServiceBuilder::new()
115 0 : .layer(tower_otel::trace::HttpLayer::server(tracing::Level::INFO))
116 : // Add this middleware since we assume the request ID exists
117 0 : .layer(middleware::from_fn(maybe_add_request_id_header))
118 0 : .layer(
119 0 : TraceLayer::new_for_http()
120 0 : .on_request(|request: &http::Request<_>, _span: &Span| {
121 0 : let request_id = request
122 0 : .headers()
123 0 : .get(X_REQUEST_ID)
124 0 : .unwrap()
125 0 : .to_str()
126 0 : .unwrap();
127 :
128 0 : info!(%request_id, "{} {}", request.method(), request.uri());
129 0 : })
130 0 : .on_response(
131 0 : |response: &http::Response<_>, latency: Duration, _span: &Span| {
132 0 : let request_id = response
133 0 : .headers()
134 0 : .get(X_REQUEST_ID)
135 0 : .unwrap()
136 0 : .to_str()
137 0 : .unwrap();
138 :
139 0 : info!(
140 : %request_id,
141 0 : code = response.status().as_u16(),
142 0 : latency = latency.as_millis()
143 : );
144 0 : },
145 : ),
146 : )
147 0 : .layer(PropagateRequestIdLayer::x_request_id()),
148 : )
149 0 : }
150 : }
151 :
152 : impl Server {
153 0 : async fn handle_404() -> impl IntoResponse {
154 0 : StatusCode::NOT_FOUND
155 0 : }
156 :
157 0 : async fn handle_405() -> impl IntoResponse {
158 0 : StatusCode::METHOD_NOT_ALLOWED
159 0 : }
160 :
161 0 : async fn listener(&self) -> Result<TcpListener> {
162 0 : let addr = SocketAddr::new(self.ip(), self.port());
163 0 : let listener = TcpListener::bind(&addr).await?;
164 :
165 0 : Ok(listener)
166 0 : }
167 :
168 0 : fn ip(&self) -> IpAddr {
169 0 : match self {
170 : // TODO: Change this to Ipv6Addr::LOCALHOST when the GitHub runners
171 : // allow binding to localhost
172 0 : Server::Internal { .. } => IpAddr::from(Ipv6Addr::UNSPECIFIED),
173 0 : Server::External { .. } => IpAddr::from(Ipv6Addr::UNSPECIFIED),
174 : }
175 0 : }
176 :
177 0 : fn port(&self) -> u16 {
178 0 : match self {
179 0 : Server::Internal { port, .. } => *port,
180 0 : Server::External { port, .. } => *port,
181 : }
182 0 : }
183 :
184 0 : async fn serve(self, compute: Arc<ComputeNode>) {
185 0 : let listener = self.listener().await.unwrap_or_else(|e| {
186 : // If we can't bind, the compute cannot operate correctly
187 0 : panic!(
188 0 : "failed to bind the compute_ctl {} HTTP server to {}: {}",
189 : self,
190 0 : SocketAddr::new(self.ip(), self.port()),
191 : e
192 : );
193 : });
194 :
195 0 : if tracing::enabled!(tracing::Level::INFO) {
196 0 : let local_addr = match listener.local_addr() {
197 0 : Ok(local_addr) => local_addr,
198 0 : Err(_) => SocketAddr::new(self.ip(), self.port()),
199 : };
200 :
201 0 : info!(
202 0 : "compute_ctl {} HTTP server listening at {}",
203 : self, local_addr
204 : );
205 0 : }
206 :
207 0 : let router = Router::from(&self)
208 0 : .with_state(compute)
209 0 : .into_make_service_with_connect_info::<SocketAddr>();
210 :
211 0 : if let Err(e) = axum::serve(listener, router).await {
212 0 : error!("compute_ctl {} HTTP server error: {}", self, e);
213 0 : }
214 0 : }
215 :
216 0 : pub fn launch(self, compute: &Arc<ComputeNode>) {
217 0 : let state = Arc::clone(compute);
218 :
219 0 : info!("Launching the {} server", self);
220 :
221 0 : tokio::spawn(self.serve(state));
222 0 : }
223 : }
|