Line data Source code
1 : //! Helper functions to upload files to remote storage with a RemoteStorage
2 :
3 : use anyhow::{bail, Context};
4 : use bytes::Bytes;
5 : use camino::Utf8Path;
6 : use fail::fail_point;
7 : use pageserver_api::shard::TenantShardId;
8 : use std::io::{ErrorKind, SeekFrom};
9 : use std::time::SystemTime;
10 : use tokio::fs::{self, File};
11 : use tokio::io::AsyncSeekExt;
12 : use tokio_util::sync::CancellationToken;
13 : use utils::{backoff, pausable_failpoint};
14 :
15 : use super::index::IndexPart;
16 : use super::manifest::TenantManifest;
17 : use super::Generation;
18 : use crate::tenant::remote_timeline_client::{
19 : remote_index_path, remote_initdb_archive_path, remote_initdb_preserved_archive_path,
20 : remote_tenant_manifest_path,
21 : };
22 : use remote_storage::{GenericRemoteStorage, RemotePath, TimeTravelError};
23 : use utils::id::{TenantId, TimelineId};
24 :
25 : use tracing::info;
26 :
27 : /// Serializes and uploads the given index part data to the remote storage.
28 2985 : pub(crate) async fn upload_index_part(
29 2985 : storage: &GenericRemoteStorage,
30 2985 : tenant_shard_id: &TenantShardId,
31 2985 : timeline_id: &TimelineId,
32 2985 : generation: Generation,
33 2985 : index_part: &IndexPart,
34 2985 : cancel: &CancellationToken,
35 2985 : ) -> anyhow::Result<()> {
36 2985 : tracing::trace!("uploading new index part");
37 :
38 2985 : fail_point!("before-upload-index", |_| {
39 0 : bail!("failpoint before-upload-index")
40 2985 : });
41 2985 : pausable_failpoint!("before-upload-index-pausable");
42 :
43 : // Safety: refuse to persist invalid index metadata, to mitigate the impact of any bug that produces this
44 : // (this should never happen)
45 2982 : index_part.validate().map_err(|e| anyhow::anyhow!(e))?;
46 :
47 : // FIXME: this error comes too late
48 2982 : let serialized = index_part.to_json_bytes()?;
49 2982 : let serialized = Bytes::from(serialized);
50 2982 :
51 2982 : let index_part_size = serialized.len();
52 2982 :
53 2982 : let remote_path = remote_index_path(tenant_shard_id, timeline_id, generation);
54 2982 : storage
55 2982 : .upload_storage_object(
56 2982 : futures::stream::once(futures::future::ready(Ok(serialized))),
57 2982 : index_part_size,
58 2982 : &remote_path,
59 2982 : cancel,
60 2982 : )
61 2982 : .await
62 2965 : .with_context(|| format!("upload index part for '{tenant_shard_id} / {timeline_id}'"))
63 2965 : }
64 : /// Serializes and uploads the given tenant manifest data to the remote storage.
65 4 : pub(crate) async fn upload_tenant_manifest(
66 4 : storage: &GenericRemoteStorage,
67 4 : tenant_shard_id: &TenantShardId,
68 4 : generation: Generation,
69 4 : tenant_manifest: &TenantManifest,
70 4 : cancel: &CancellationToken,
71 4 : ) -> anyhow::Result<()> {
72 4 : tracing::trace!("uploading new tenant manifest");
73 :
74 4 : fail_point!("before-upload-manifest", |_| {
75 0 : bail!("failpoint before-upload-manifest")
76 4 : });
77 4 : pausable_failpoint!("before-upload-manifest-pausable");
78 :
79 4 : let serialized = tenant_manifest.to_json_bytes()?;
80 4 : let serialized = Bytes::from(serialized);
81 4 :
82 4 : let tenant_manifest_site = serialized.len();
83 4 :
84 4 : let remote_path = remote_tenant_manifest_path(tenant_shard_id, generation);
85 4 : storage
86 4 : .upload_storage_object(
87 4 : futures::stream::once(futures::future::ready(Ok(serialized))),
88 4 : tenant_manifest_site,
89 4 : &remote_path,
90 4 : cancel,
91 4 : )
92 4 : .await
93 4 : .with_context(|| format!("upload tenant manifest for '{tenant_shard_id}'"))
94 4 : }
95 :
96 : /// Attempts to upload given layer files.
97 : /// No extra checks for overlapping files is made and any files that are already present remotely will be overwritten, if submitted during the upload.
98 : ///
99 : /// On an error, bumps the retries count and reschedules the entire task.
100 3347 : pub(super) async fn upload_timeline_layer<'a>(
101 3347 : storage: &'a GenericRemoteStorage,
102 3347 : local_path: &'a Utf8Path,
103 3347 : remote_path: &'a RemotePath,
104 3347 : metadata_size: u64,
105 3347 : cancel: &CancellationToken,
106 3347 : ) -> anyhow::Result<()> {
107 3347 : fail_point!("before-upload-layer", |_| {
108 0 : bail!("failpoint before-upload-layer")
109 3347 : });
110 :
111 3347 : pausable_failpoint!("before-upload-layer-pausable");
112 :
113 3176 : let source_file_res = fs::File::open(&local_path).await;
114 3136 : let source_file = match source_file_res {
115 3136 : Ok(source_file) => source_file,
116 0 : Err(e) if e.kind() == ErrorKind::NotFound => {
117 0 : // If we encounter this arm, it wasn't intended, but it's also not
118 0 : // a big problem, if it's because the file was deleted before an
119 0 : // upload. However, a nonexistent file can also be indicative of
120 0 : // something worse, like when a file is scheduled for upload before
121 0 : // it has been written to disk yet.
122 0 : //
123 0 : // This is tested against `test_compaction_delete_before_upload`
124 0 : info!(path = %local_path, "File to upload doesn't exist. Likely the file has been deleted and an upload is not required any more.");
125 0 : return Ok(());
126 : }
127 0 : Err(e) => Err(e).with_context(|| format!("open a source file for layer {local_path:?}"))?,
128 : };
129 :
130 3136 : let fs_size = source_file
131 3136 : .metadata()
132 3136 : .await
133 3120 : .with_context(|| format!("get the source file metadata for layer {local_path:?}"))?
134 3120 : .len();
135 3120 :
136 3120 : if metadata_size != fs_size {
137 0 : bail!("File {local_path:?} has its current FS size {fs_size} diferent from initially determined {metadata_size}");
138 3120 : }
139 :
140 3120 : let fs_size = usize::try_from(fs_size)
141 3120 : .with_context(|| format!("convert {local_path:?} size {fs_size} usize"))?;
142 :
143 3120 : let reader = tokio_util::io::ReaderStream::with_capacity(source_file, super::BUFFER_SIZE);
144 3120 :
145 3120 : storage
146 3120 : .upload(reader, fs_size, remote_path, None, cancel)
147 3120 : .await
148 3092 : .with_context(|| format!("upload layer from local path '{local_path}'"))
149 3092 : }
150 :
151 0 : pub(super) async fn copy_timeline_layer(
152 0 : storage: &GenericRemoteStorage,
153 0 : source_path: &RemotePath,
154 0 : target_path: &RemotePath,
155 0 : cancel: &CancellationToken,
156 0 : ) -> anyhow::Result<()> {
157 0 : fail_point!("before-copy-layer", |_| {
158 0 : bail!("failpoint before-copy-layer")
159 0 : });
160 :
161 0 : pausable_failpoint!("before-copy-layer-pausable");
162 :
163 0 : storage
164 0 : .copy_object(source_path, target_path, cancel)
165 0 : .await
166 0 : .with_context(|| format!("copy layer {source_path} to {target_path}"))
167 0 : }
168 :
169 : /// Uploads the given `initdb` data to the remote storage.
170 0 : pub(crate) async fn upload_initdb_dir(
171 0 : storage: &GenericRemoteStorage,
172 0 : tenant_id: &TenantId,
173 0 : timeline_id: &TimelineId,
174 0 : mut initdb_tar_zst: File,
175 0 : size: u64,
176 0 : cancel: &CancellationToken,
177 0 : ) -> anyhow::Result<()> {
178 0 : tracing::trace!("uploading initdb dir");
179 :
180 : // We might have read somewhat into the file already in the prior retry attempt
181 0 : initdb_tar_zst.seek(SeekFrom::Start(0)).await?;
182 :
183 0 : let file = tokio_util::io::ReaderStream::with_capacity(initdb_tar_zst, super::BUFFER_SIZE);
184 0 :
185 0 : let remote_path = remote_initdb_archive_path(tenant_id, timeline_id);
186 0 : storage
187 0 : .upload_storage_object(file, size as usize, &remote_path, cancel)
188 0 : .await
189 0 : .with_context(|| format!("upload initdb dir for '{tenant_id} / {timeline_id}'"))
190 0 : }
191 :
192 0 : pub(crate) async fn preserve_initdb_archive(
193 0 : storage: &GenericRemoteStorage,
194 0 : tenant_id: &TenantId,
195 0 : timeline_id: &TimelineId,
196 0 : cancel: &CancellationToken,
197 0 : ) -> anyhow::Result<()> {
198 0 : let source_path = remote_initdb_archive_path(tenant_id, timeline_id);
199 0 : let dest_path = remote_initdb_preserved_archive_path(tenant_id, timeline_id);
200 0 : storage
201 0 : .copy_object(&source_path, &dest_path, cancel)
202 0 : .await
203 0 : .with_context(|| format!("backing up initdb archive for '{tenant_id} / {timeline_id}'"))
204 0 : }
205 :
206 0 : pub(crate) async fn time_travel_recover_tenant(
207 0 : storage: &GenericRemoteStorage,
208 0 : tenant_shard_id: &TenantShardId,
209 0 : timestamp: SystemTime,
210 0 : done_if_after: SystemTime,
211 0 : cancel: &CancellationToken,
212 0 : ) -> Result<(), TimeTravelError> {
213 0 : let warn_after = 3;
214 0 : let max_attempts = 10;
215 0 : let mut prefixes = Vec::with_capacity(2);
216 0 : if tenant_shard_id.is_shard_zero() {
217 0 : // Also recover the unsharded prefix for a shard of zero:
218 0 : // - if the tenant is totally unsharded, the unsharded prefix contains all the data
219 0 : // - if the tenant is sharded, we still want to recover the initdb data, but we only
220 0 : // want to do it once, so let's do it on the 0 shard
221 0 : let timelines_path_unsharded =
222 0 : super::remote_timelines_path_unsharded(&tenant_shard_id.tenant_id);
223 0 : prefixes.push(timelines_path_unsharded);
224 0 : }
225 0 : if !tenant_shard_id.is_unsharded() {
226 0 : // If the tenant is sharded, we need to recover the sharded prefix
227 0 : let timelines_path = super::remote_timelines_path(tenant_shard_id);
228 0 : prefixes.push(timelines_path);
229 0 : }
230 0 : for prefix in &prefixes {
231 0 : backoff::retry(
232 0 : || async {
233 0 : storage
234 0 : .time_travel_recover(Some(prefix), timestamp, done_if_after, cancel)
235 0 : .await
236 0 : },
237 0 : |e| !matches!(e, TimeTravelError::Other(_)),
238 0 : warn_after,
239 0 : max_attempts,
240 0 : "time travel recovery of tenant prefix",
241 0 : cancel,
242 0 : )
243 0 : .await
244 0 : .ok_or_else(|| TimeTravelError::Cancelled)
245 0 : .and_then(|x| x)?;
246 : }
247 0 : Ok(())
248 0 : }
|