Line data Source code
1 : use std::{ops::Bound, sync::Arc};
2 :
3 : use anyhow::Context;
4 : use bytes::Bytes;
5 : use postgres_ffi::ControlFileData;
6 : use remote_storage::{
7 : Download, DownloadError, DownloadOpts, GenericRemoteStorage, Listing, ListingObject, RemotePath,
8 : };
9 : use serde::de::DeserializeOwned;
10 : use tokio_util::sync::CancellationToken;
11 : use tracing::{debug, info, instrument};
12 : use utils::lsn::Lsn;
13 :
14 : use crate::{assert_u64_eq_usize::U64IsUsize, config::PageServerConf};
15 :
16 : use super::{importbucket_format, index_part_format};
17 :
18 0 : pub async fn new(
19 0 : conf: &'static PageServerConf,
20 0 : location: &index_part_format::Location,
21 0 : cancel: CancellationToken,
22 0 : ) -> Result<RemoteStorageWrapper, anyhow::Error> {
23 0 : // FIXME: we probably want some timeout, and we might be able to assume the max file
24 0 : // size on S3 is 1GiB (postgres segment size). But the problem is that the individual
25 0 : // downloaders don't know enough about concurrent downloads to make a guess on the
26 0 : // expected bandwidth and resulting best timeout.
27 0 : let timeout = std::time::Duration::from_secs(24 * 60 * 60);
28 0 : let location_storage = match location {
29 : #[cfg(feature = "testing")]
30 0 : index_part_format::Location::LocalFs { path } => {
31 0 : GenericRemoteStorage::LocalFs(remote_storage::LocalFs::new(path.clone(), timeout)?)
32 : }
33 : index_part_format::Location::AwsS3 {
34 0 : region,
35 0 : bucket,
36 0 : key,
37 0 : } => {
38 0 : // TODO: think about security implications of letting the client specify the bucket & prefix.
39 0 : // It's the most flexible right now, but, possibly we want to move bucket name into PS conf
40 0 : // and force the timeline_id into the prefix?
41 0 : GenericRemoteStorage::AwsS3(Arc::new(
42 0 : remote_storage::S3Bucket::new(
43 0 : &remote_storage::S3Config {
44 0 : bucket_name: bucket.clone(),
45 0 : prefix_in_bucket: Some(key.clone()),
46 0 : bucket_region: region.clone(),
47 0 : endpoint: conf
48 0 : .import_pgdata_aws_endpoint_url
49 0 : .clone()
50 0 : .map(|url| url.to_string()), // by specifying None here, remote_storage/aws-sdk-rust will infer from env
51 0 : concurrency_limit: 100.try_into().unwrap(), // TODO: think about this
52 0 : max_keys_per_list_response: Some(1000), // TODO: think about this
53 0 : upload_storage_class: None, // irrelevant
54 0 : },
55 0 : timeout,
56 0 : )
57 0 : .await
58 0 : .context("setup s3 bucket")?,
59 : ))
60 : }
61 : };
62 0 : let storage_wrapper = RemoteStorageWrapper::new(location_storage, cancel);
63 0 : Ok(storage_wrapper)
64 0 : }
65 :
66 : /// Wrap [`remote_storage`] APIs to make it look a bit more like a filesystem API
67 : /// such as [`tokio::fs`], which was used in the original implementation of the import code.
68 : #[derive(Clone)]
69 : pub struct RemoteStorageWrapper {
70 : storage: GenericRemoteStorage,
71 : cancel: CancellationToken,
72 : }
73 :
74 : impl RemoteStorageWrapper {
75 0 : pub fn new(storage: GenericRemoteStorage, cancel: CancellationToken) -> Self {
76 0 : Self { storage, cancel }
77 0 : }
78 :
79 0 : #[instrument(level = tracing::Level::DEBUG, skip_all, fields(%path))]
80 : pub async fn listfilesindir(
81 : &self,
82 : path: &RemotePath,
83 : ) -> Result<Vec<(RemotePath, usize)>, DownloadError> {
84 : assert!(
85 : path.object_name().is_some(),
86 : "must specify dirname, without trailing slash"
87 : );
88 : let path = path.add_trailing_slash();
89 :
90 : let res = crate::tenant::remote_timeline_client::download::download_retry_forever(
91 0 : || async {
92 0 : let Listing { keys, prefixes: _ } = self
93 0 : .storage
94 0 : .list(
95 0 : Some(&path),
96 0 : remote_storage::ListingMode::WithDelimiter,
97 0 : None,
98 0 : &self.cancel,
99 0 : )
100 0 : .await?;
101 0 : let res = keys
102 0 : .into_iter()
103 0 : .map(|ListingObject { key, size, .. }| (key, size.into_usize()))
104 0 : .collect();
105 0 : Ok(res)
106 0 : },
107 : &format!("listfilesindir {path:?}"),
108 : &self.cancel,
109 : )
110 : .await;
111 : debug!(?res, "returning");
112 : res
113 : }
114 :
115 0 : #[instrument(level = tracing::Level::DEBUG, skip_all, fields(%path))]
116 : pub async fn listdir(&self, path: &RemotePath) -> Result<Vec<RemotePath>, DownloadError> {
117 : assert!(
118 : path.object_name().is_some(),
119 : "must specify dirname, without trailing slash"
120 : );
121 : let path = path.add_trailing_slash();
122 :
123 : let res = crate::tenant::remote_timeline_client::download::download_retry_forever(
124 0 : || async {
125 0 : let Listing { keys, prefixes } = self
126 0 : .storage
127 0 : .list(
128 0 : Some(&path),
129 0 : remote_storage::ListingMode::WithDelimiter,
130 0 : None,
131 0 : &self.cancel,
132 0 : )
133 0 : .await?;
134 0 : let res = keys
135 0 : .into_iter()
136 0 : .map(|ListingObject { key, .. }| key)
137 0 : .chain(prefixes.into_iter())
138 0 : .collect();
139 0 : Ok(res)
140 0 : },
141 : &format!("listdir {path:?}"),
142 : &self.cancel,
143 : )
144 : .await;
145 : debug!(?res, "returning");
146 : res
147 : }
148 :
149 0 : #[instrument(level = tracing::Level::DEBUG, skip_all, fields(%path))]
150 : pub async fn get(&self, path: &RemotePath) -> Result<Bytes, DownloadError> {
151 : let res = crate::tenant::remote_timeline_client::download::download_retry_forever(
152 0 : || async {
153 : let Download {
154 0 : download_stream, ..
155 0 : } = self
156 0 : .storage
157 0 : .download(path, &DownloadOpts::default(), &self.cancel)
158 0 : .await?;
159 0 : let mut reader = tokio_util::io::StreamReader::new(download_stream);
160 0 :
161 0 : // XXX optimize this, can we get the capacity hint from somewhere?
162 0 : let mut buf = Vec::new();
163 0 : tokio::io::copy_buf(&mut reader, &mut buf).await?;
164 0 : Ok(Bytes::from(buf))
165 0 : },
166 : &format!("download {path:?}"),
167 : &self.cancel,
168 : )
169 : .await;
170 0 : debug!(len = res.as_ref().ok().map(|buf| buf.len()), "done");
171 : res
172 : }
173 :
174 0 : pub async fn get_spec(&self) -> Result<Option<importbucket_format::Spec>, anyhow::Error> {
175 0 : self.get_json(&RemotePath::from_string("spec.json").unwrap())
176 0 : .await
177 0 : .context("get spec")
178 0 : }
179 :
180 0 : #[instrument(level = tracing::Level::DEBUG, skip_all, fields(%path))]
181 : pub async fn get_json<T: DeserializeOwned>(
182 : &self,
183 : path: &RemotePath,
184 : ) -> Result<Option<T>, DownloadError> {
185 : let buf = match self.get(path).await {
186 : Ok(buf) => buf,
187 : Err(DownloadError::NotFound) => return Ok(None),
188 : Err(err) => return Err(err),
189 : };
190 : let res = serde_json::from_slice(&buf)
191 : .context("serialize")
192 : // TODO: own error type
193 : .map_err(DownloadError::Other)?;
194 : Ok(Some(res))
195 : }
196 :
197 0 : #[instrument(level = tracing::Level::DEBUG, skip_all, fields(%path))]
198 : pub async fn put_json<T>(&self, path: &RemotePath, value: &T) -> anyhow::Result<()>
199 : where
200 : T: serde::Serialize,
201 : {
202 : let buf = serde_json::to_vec(value)?;
203 : let bytes = Bytes::from(buf);
204 : utils::backoff::retry(
205 0 : || async {
206 0 : let size = bytes.len();
207 0 : let bytes = futures::stream::once(futures::future::ready(Ok(bytes.clone())));
208 0 : self.storage
209 0 : .upload_storage_object(bytes, size, path, &self.cancel)
210 0 : .await
211 0 : },
212 : remote_storage::TimeoutOrCancel::caused_by_cancel,
213 : 1,
214 : u32::MAX,
215 : &format!("put json {path}"),
216 : &self.cancel,
217 : )
218 : .await
219 : .expect("practically infinite retries")
220 : }
221 :
222 0 : #[instrument(level = tracing::Level::DEBUG, skip_all, fields(%path))]
223 : pub async fn get_range(
224 : &self,
225 : path: &RemotePath,
226 : start_inclusive: u64,
227 : end_exclusive: u64,
228 : ) -> Result<Vec<u8>, DownloadError> {
229 : let len = end_exclusive
230 : .checked_sub(start_inclusive)
231 : .unwrap()
232 : .into_usize();
233 : let res = crate::tenant::remote_timeline_client::download::download_retry_forever(
234 0 : || async {
235 : let Download {
236 0 : download_stream, ..
237 0 : } = self
238 0 : .storage
239 0 : .download(
240 0 : path,
241 0 : &DownloadOpts {
242 0 : etag: None,
243 0 : byte_start: Bound::Included(start_inclusive),
244 0 : byte_end: Bound::Excluded(end_exclusive)
245 0 : },
246 0 : &self.cancel)
247 0 : .await?;
248 0 : let mut reader = tokio_util::io::StreamReader::new(download_stream);
249 0 :
250 0 : let mut buf = Vec::with_capacity(len);
251 0 : tokio::io::copy_buf(&mut reader, &mut buf).await?;
252 0 : Ok(buf)
253 0 : },
254 : &format!("download range len=0x{len:x} [0x{start_inclusive:x},0x{end_exclusive:x}) from {path:?}"),
255 : &self.cancel,
256 : )
257 : .await;
258 0 : debug!(len = res.as_ref().ok().map(|buf| buf.len()), "done");
259 : res
260 : }
261 :
262 0 : pub fn pgdata(&self) -> RemotePath {
263 0 : RemotePath::from_string("pgdata").unwrap()
264 0 : }
265 :
266 0 : pub async fn get_control_file(&self) -> Result<ControlFile, anyhow::Error> {
267 0 : let control_file_path = self.pgdata().join("global/pg_control");
268 0 : info!("get control file from {control_file_path}");
269 0 : let control_file_buf = self.get(&control_file_path).await?;
270 0 : ControlFile::new(control_file_buf)
271 0 : }
272 : }
273 :
274 : pub struct ControlFile {
275 : control_file_data: ControlFileData,
276 : control_file_buf: Bytes,
277 : }
278 :
279 : impl ControlFile {
280 0 : pub(crate) fn new(control_file_buf: Bytes) -> Result<Self, anyhow::Error> {
281 : // XXX ControlFileData is version-specific, we're always using v14 here. v17 had changes.
282 0 : let control_file_data = ControlFileData::decode(&control_file_buf)?;
283 0 : let control_file = ControlFile {
284 0 : control_file_data,
285 0 : control_file_buf,
286 0 : };
287 0 : control_file.try_pg_version()?; // so that we can offer infallible pg_version()
288 0 : Ok(control_file)
289 0 : }
290 0 : pub(crate) fn base_lsn(&self) -> Lsn {
291 0 : Lsn(self.control_file_data.checkPoint).align()
292 0 : }
293 0 : pub(crate) fn pg_version(&self) -> u32 {
294 0 : self.try_pg_version()
295 0 : .expect("prepare() checks that try_pg_version doesn't error")
296 0 : }
297 0 : pub(crate) fn control_file_data(&self) -> &ControlFileData {
298 0 : &self.control_file_data
299 0 : }
300 0 : pub(crate) fn control_file_buf(&self) -> &Bytes {
301 0 : &self.control_file_buf
302 0 : }
303 0 : fn try_pg_version(&self) -> anyhow::Result<u32> {
304 0 : Ok(match self.control_file_data.catalog_version_no {
305 : // thesea are from catversion.h
306 0 : 202107181 => 14,
307 0 : 202209061 => 15,
308 0 : 202307071 => 16,
309 : /* XXX pg17 */
310 0 : catversion => {
311 0 : anyhow::bail!("unrecognized catalog version {catversion}")
312 : }
313 : })
314 0 : }
315 : }
|