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