Line data Source code
1 : use std::collections::HashMap;
2 :
3 : use futures::Future;
4 : use pageserver_api::config::NodeMetadata;
5 : use pageserver_api::controller_api::{AvailabilityZone, NodeRegisterRequest};
6 : use pageserver_api::shard::TenantShardId;
7 : use pageserver_api::upcall_api::{
8 : ReAttachRequest, ReAttachResponse, ReAttachResponseTenant, ValidateRequest,
9 : ValidateRequestTenant, ValidateResponse,
10 : };
11 : use serde::Serialize;
12 : use serde::de::DeserializeOwned;
13 : use tokio_util::sync::CancellationToken;
14 : use url::Url;
15 : use utils::generation::Generation;
16 : use utils::id::NodeId;
17 : use utils::{backoff, failpoint_support};
18 :
19 : use crate::config::PageServerConf;
20 : use crate::virtual_file::on_fatal_io_error;
21 :
22 : /// The Pageserver's client for using the storage controller upcall API: this is a small API
23 : /// for dealing with generations (see docs/rfcs/025-generation-numbers.md).
24 : pub struct StorageControllerUpcallClient {
25 : http_client: reqwest::Client,
26 : base_url: Url,
27 : node_id: NodeId,
28 : cancel: CancellationToken,
29 : }
30 :
31 : /// Represent operations which internally retry on all errors other than
32 : /// cancellation token firing: the only way they can fail is ShuttingDown.
33 : pub enum RetryForeverError {
34 : ShuttingDown,
35 : }
36 :
37 : pub trait StorageControllerUpcallApi {
38 : fn re_attach(
39 : &self,
40 : conf: &PageServerConf,
41 : ) -> impl Future<
42 : Output = Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError>,
43 : > + Send;
44 : fn validate(
45 : &self,
46 : tenants: Vec<(TenantShardId, Generation)>,
47 : ) -> impl Future<Output = Result<HashMap<TenantShardId, bool>, RetryForeverError>> + Send;
48 : }
49 :
50 : impl StorageControllerUpcallClient {
51 : /// A None return value indicates that the input `conf` object does not have control
52 : /// plane API enabled.
53 0 : pub fn new(conf: &'static PageServerConf, cancel: &CancellationToken) -> Option<Self> {
54 0 : let mut url = match conf.control_plane_api.as_ref() {
55 0 : Some(u) => u.clone(),
56 0 : None => return None,
57 : };
58 :
59 0 : if let Ok(mut segs) = url.path_segments_mut() {
60 0 : // This ensures that `url` ends with a slash if it doesn't already.
61 0 : // That way, we can subsequently use join() to safely attach extra path elements.
62 0 : segs.pop_if_empty().push("");
63 0 : }
64 :
65 0 : let mut client = reqwest::ClientBuilder::new();
66 :
67 0 : if let Some(jwt) = &conf.control_plane_api_token {
68 0 : let mut headers = reqwest::header::HeaderMap::new();
69 0 : headers.insert(
70 0 : "Authorization",
71 0 : format!("Bearer {}", jwt.get_contents()).parse().unwrap(),
72 0 : );
73 0 : client = client.default_headers(headers);
74 0 : }
75 :
76 0 : Some(Self {
77 0 : http_client: client.build().expect("Failed to construct HTTP client"),
78 0 : base_url: url,
79 0 : node_id: conf.id,
80 0 : cancel: cancel.clone(),
81 0 : })
82 0 : }
83 :
84 : #[tracing::instrument(skip_all)]
85 : async fn retry_http_forever<R, T>(
86 : &self,
87 : url: &url::Url,
88 : request: R,
89 : ) -> Result<T, RetryForeverError>
90 : where
91 : R: Serialize,
92 : T: DeserializeOwned,
93 : {
94 : let res = backoff::retry(
95 0 : || async {
96 0 : let response = self
97 0 : .http_client
98 0 : .post(url.clone())
99 0 : .json(&request)
100 0 : .send()
101 0 : .await?;
102 :
103 0 : response.error_for_status_ref()?;
104 0 : response.json::<T>().await
105 0 : },
106 0 : |_| false,
107 : 3,
108 : u32::MAX,
109 : "storage controller upcall",
110 : &self.cancel,
111 : )
112 : .await
113 : .ok_or(RetryForeverError::ShuttingDown)?
114 : .expect("We retry forever, this should never be reached");
115 :
116 : Ok(res)
117 : }
118 :
119 0 : pub(crate) fn base_url(&self) -> &Url {
120 0 : &self.base_url
121 0 : }
122 : }
123 :
124 : impl StorageControllerUpcallApi for StorageControllerUpcallClient {
125 : /// Block until we get a successful response, or error out if we are shut down
126 : #[tracing::instrument(skip_all)] // so that warning logs from retry_http_forever have context
127 : async fn re_attach(
128 : &self,
129 : conf: &PageServerConf,
130 : ) -> Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError> {
131 : let url = self
132 : .base_url
133 : .join("re-attach")
134 : .expect("Failed to build re-attach path");
135 :
136 : // Include registration content in the re-attach request if a metadata file is readable
137 : let metadata_path = conf.metadata_path();
138 : let register = match tokio::fs::read_to_string(&metadata_path).await {
139 : Ok(metadata_str) => match serde_json::from_str::<NodeMetadata>(&metadata_str) {
140 : Ok(m) => {
141 : // Since we run one time at startup, be generous in our logging and
142 : // dump all metadata.
143 : tracing::info!(
144 : "Loaded node metadata: postgres {}:{}, http {}:{}, other fields: {:?}",
145 : m.postgres_host,
146 : m.postgres_port,
147 : m.http_host,
148 : m.http_port,
149 : m.other
150 : );
151 :
152 : let az_id = {
153 : let az_id_from_metadata = m
154 : .other
155 : .get("availability_zone_id")
156 0 : .and_then(|jv| jv.as_str().map(|str| str.to_owned()));
157 :
158 : match az_id_from_metadata {
159 : Some(az_id) => Some(AvailabilityZone(az_id)),
160 : None => {
161 : tracing::warn!(
162 : "metadata.json does not contain an 'availability_zone_id' field"
163 : );
164 : conf.availability_zone.clone().map(AvailabilityZone)
165 : }
166 : }
167 : };
168 :
169 : if az_id.is_none() {
170 : panic!(
171 : "Availablity zone id could not be inferred from metadata.json or pageserver config"
172 : );
173 : }
174 :
175 : Some(NodeRegisterRequest {
176 : node_id: conf.id,
177 : listen_pg_addr: m.postgres_host,
178 : listen_pg_port: m.postgres_port,
179 : listen_http_addr: m.http_host,
180 : listen_http_port: m.http_port,
181 : listen_https_port: m.https_port,
182 : availability_zone_id: az_id.expect("Checked above"),
183 : })
184 : }
185 : Err(e) => {
186 : tracing::error!("Unreadable metadata in {metadata_path}: {e}");
187 : None
188 : }
189 : },
190 : Err(e) => {
191 : if e.kind() == std::io::ErrorKind::NotFound {
192 : // This is legal: we may have been deployed with some external script
193 : // doing registration for us.
194 : tracing::info!("Metadata file not found at {metadata_path}");
195 : } else {
196 : on_fatal_io_error(&e, &format!("Loading metadata at {metadata_path}"))
197 : }
198 : None
199 : }
200 : };
201 :
202 : let request = ReAttachRequest {
203 : node_id: self.node_id,
204 : register: register.clone(),
205 : };
206 :
207 : let response: ReAttachResponse = self.retry_http_forever(&url, request).await?;
208 : tracing::info!(
209 : "Received re-attach response with {} tenants (node {}, register: {:?})",
210 : response.tenants.len(),
211 : self.node_id,
212 : register,
213 : );
214 :
215 : failpoint_support::sleep_millis_async!("control-plane-client-re-attach");
216 :
217 : Ok(response
218 : .tenants
219 : .into_iter()
220 0 : .map(|rart| (rart.id, rart))
221 : .collect::<HashMap<_, _>>())
222 : }
223 :
224 : /// Block until we get a successful response, or error out if we are shut down
225 : #[tracing::instrument(skip_all)] // so that warning logs from retry_http_forever have context
226 : async fn validate(
227 : &self,
228 : tenants: Vec<(TenantShardId, Generation)>,
229 : ) -> Result<HashMap<TenantShardId, bool>, RetryForeverError> {
230 : let url = self
231 : .base_url
232 : .join("validate")
233 : .expect("Failed to build validate path");
234 :
235 : // When sending validate requests, break them up into chunks so that we
236 : // avoid possible edge cases of generating any HTTP requests that
237 : // require database I/O across many thousands of tenants.
238 : let mut result: HashMap<TenantShardId, bool> = HashMap::with_capacity(tenants.len());
239 : for tenant_chunk in (tenants).chunks(128) {
240 : let request = ValidateRequest {
241 : tenants: tenant_chunk
242 : .iter()
243 0 : .map(|(id, generation)| ValidateRequestTenant {
244 0 : id: *id,
245 0 : r#gen: (*generation).into().expect(
246 0 : "Generation should always be valid for a Tenant doing deletions",
247 0 : ),
248 0 : })
249 : .collect(),
250 : };
251 :
252 : failpoint_support::sleep_millis_async!(
253 : "control-plane-client-validate-sleep",
254 : &self.cancel
255 : );
256 : if self.cancel.is_cancelled() {
257 : return Err(RetryForeverError::ShuttingDown);
258 : }
259 :
260 : let response: ValidateResponse = self.retry_http_forever(&url, request).await?;
261 : for rt in response.tenants {
262 : result.insert(rt.id, rt.valid);
263 : }
264 : }
265 :
266 : Ok(result.into_iter().collect())
267 : }
268 : }
|