/build/source/nativelink-store/src/ontap_s3_store.rs
Line | Count | Source |
1 | | // Copyright 2025 The NativeLink Authors. All rights reserved. |
2 | | // |
3 | | // Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // See LICENSE file for details |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | use core::cmp; |
16 | | use core::pin::Pin; |
17 | | use core::time::Duration; |
18 | | use std::borrow::Cow; |
19 | | use std::fs::File; |
20 | | use std::io::BufReader; |
21 | | use std::sync::Arc; |
22 | | |
23 | | use async_trait::async_trait; |
24 | | use aws_config::BehaviorVersion; |
25 | | use aws_config::default_provider::credentials::DefaultCredentialsChain; |
26 | | use aws_config::provider_config::ProviderConfig; |
27 | | use aws_sdk_s3::Client; |
28 | | use aws_sdk_s3::config::Region; |
29 | | use aws_sdk_s3::operation::create_multipart_upload::CreateMultipartUploadOutput; |
30 | | use aws_sdk_s3::operation::get_object::GetObjectError; |
31 | | use aws_sdk_s3::operation::head_object::HeadObjectError; |
32 | | use aws_sdk_s3::primitives::{ByteStream, SdkBody}; |
33 | | use aws_sdk_s3::types::builders::{CompletedMultipartUploadBuilder, CompletedPartBuilder}; |
34 | | use base64::Engine; |
35 | | use base64::prelude::BASE64_STANDARD_NO_PAD; |
36 | | use bytes::BytesMut; |
37 | | use futures::future::{Either, FusedFuture}; |
38 | | use futures::stream::{FuturesUnordered, unfold}; |
39 | | use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt}; |
40 | | use hyper_rustls::ConfigBuilderExt; |
41 | | use nativelink_config::stores::ExperimentalOntapS3Spec; |
42 | | use nativelink_error::{Code, Error, ResultExt, make_err}; |
43 | | use nativelink_metric::MetricsComponent; |
44 | | use nativelink_util::buf_channel::{ |
45 | | DropCloserReadHalf, DropCloserWriteHalf, make_buf_channel_pair, |
46 | | }; |
47 | | use nativelink_util::health_utils::{HealthStatus, HealthStatusIndicator}; |
48 | | use nativelink_util::instant_wrapper::InstantWrapper; |
49 | | use nativelink_util::retry::{Retrier, RetryResult}; |
50 | | use nativelink_util::store_trait::{RemoveCallback, StoreDriver, StoreKey, UploadSizeInfo}; |
51 | | use parking_lot::Mutex; |
52 | | use rustls::{ClientConfig, RootCertStore}; |
53 | | use rustls_pki_types::CertificateDer; |
54 | | use rustls_pki_types::pem::PemObject; |
55 | | use sha2::{Digest, Sha256}; |
56 | | use tokio::time::sleep; |
57 | | use tracing::{Level, event, warn}; |
58 | | |
59 | | use crate::cas_utils::is_zero_digest; |
60 | | use crate::common_s3_utils::{TlsClient, install_default_rustls_crypto_provider}; |
61 | | |
62 | | // S3 parts cannot be smaller than this number |
63 | | const MIN_MULTIPART_SIZE: u64 = 5 * 1024 * 1024; // 5MB |
64 | | |
65 | | // S3 parts cannot be larger than this number |
66 | | const MAX_MULTIPART_SIZE: u64 = 5 * 1024 * 1024 * 1024; // 5GB |
67 | | |
68 | | // S3 parts cannot be more than this number |
69 | | const MAX_UPLOAD_PARTS: usize = 10_000; |
70 | | |
71 | | // Default max buffer size for retrying upload requests |
72 | | const DEFAULT_MAX_RETRY_BUFFER_PER_REQUEST: usize = 20 * 1024 * 1024; // 20MB |
73 | | |
74 | | // Default limit for concurrent part uploads per multipart upload |
75 | | const DEFAULT_MULTIPART_MAX_CONCURRENT_UPLOADS: usize = 10; |
76 | | |
77 | | #[derive(Debug, MetricsComponent)] |
78 | | pub struct OntapS3Store<NowFn> { |
79 | | s3_client: Arc<Client>, |
80 | | now_fn: NowFn, |
81 | | #[metric(help = "The bucket name for the ONTAP S3 store")] |
82 | | bucket: String, |
83 | | #[metric(help = "The key prefix for the ONTAP S3 store")] |
84 | | key_prefix: String, |
85 | | retrier: Retrier, |
86 | | #[metric(help = "The number of seconds to consider an object expired")] |
87 | | consider_expired_after_s: i64, |
88 | | #[metric(help = "The number of bytes to buffer for retrying requests")] |
89 | | max_retry_buffer_per_request: usize, |
90 | | #[metric(help = "The number of concurrent uploads allowed for multipart uploads")] |
91 | | multipart_max_concurrent_uploads: usize, |
92 | | |
93 | | remove_callbacks: Mutex<Vec<RemoveCallback>>, |
94 | | } |
95 | | |
96 | 0 | pub fn load_custom_certs(cert_path: &str) -> Result<Arc<ClientConfig>, Error> { |
97 | 0 | let mut root_store = RootCertStore::empty(); |
98 | | |
99 | | // Create a BufReader from the cert file |
100 | 0 | let mut cert_reader = BufReader::new( |
101 | 0 | File::open(cert_path) |
102 | 0 | .err_tip(|| format!("Failed to open CA certificate file {cert_path}"))?, |
103 | | ); |
104 | | |
105 | | // Parse certificates |
106 | 0 | let certs = CertificateDer::pem_reader_iter(&mut cert_reader).collect::<Result<Vec<_>, _>>()?; |
107 | | |
108 | | // Add each certificate to the root store |
109 | 0 | for cert in certs { |
110 | 0 | root_store.add(cert).map_err(|e| { |
111 | 0 | Error::from_std_err(Code::Internal, &e) |
112 | 0 | .append("Failed to add certificate to root store") |
113 | 0 | })?; |
114 | | } |
115 | | |
116 | | // Build the client config with the root store |
117 | 0 | let config = ClientConfig::builder() |
118 | 0 | .with_root_certificates(root_store) |
119 | 0 | .with_no_client_auth(); |
120 | | |
121 | 0 | Ok(Arc::new(config)) |
122 | 0 | } |
123 | | |
124 | | impl<I, NowFn> OntapS3Store<NowFn> |
125 | | where |
126 | | I: InstantWrapper, |
127 | | NowFn: Fn() -> I + Send + Sync + Unpin + 'static, |
128 | | { |
129 | 3 | pub async fn new(spec: &ExperimentalOntapS3Spec, now_fn: NowFn) -> Result<Arc<Self>, Error> { |
130 | 3 | install_default_rustls_crypto_provider(); |
131 | | |
132 | | // Load custom CA config |
133 | 3 | let ca_config = if let Some(cert_path0 ) = &spec.root_certificates { |
134 | 0 | load_custom_certs(cert_path)? |
135 | | } else { |
136 | 3 | Arc::new( |
137 | 3 | ClientConfig::builder() |
138 | 3 | .with_native_roots()?0 |
139 | 3 | .with_no_client_auth(), |
140 | | ) |
141 | | }; |
142 | | |
143 | 3 | let https_connector = hyper_rustls::HttpsConnectorBuilder::new() |
144 | 3 | .with_tls_config((*ca_config).clone()) |
145 | 3 | .https_only() |
146 | 3 | .enable_http1() |
147 | 3 | .enable_http2() |
148 | 3 | .build(); |
149 | | |
150 | 3 | let http_client = TlsClient::with_https_connector(&spec.common, https_connector); |
151 | | |
152 | 3 | let credentials_provider = DefaultCredentialsChain::builder() |
153 | 3 | .configure( |
154 | 3 | ProviderConfig::without_region() |
155 | 3 | .with_region(Some(Region::new(Cow::Owned(spec.vserver_name.clone())))) |
156 | 3 | .with_http_client(http_client.clone()), |
157 | 3 | ) |
158 | 3 | .build() |
159 | 3 | .await; |
160 | | |
161 | 3 | let config = aws_sdk_s3::Config::builder() |
162 | 3 | .credentials_provider(credentials_provider) |
163 | 3 | .endpoint_url(&spec.endpoint) |
164 | 3 | .region(Region::new(spec.vserver_name.clone())) |
165 | 3 | .app_name(aws_config::AppName::new("nativelink").expect("valid app name")) |
166 | 3 | .http_client(http_client) |
167 | 3 | .force_path_style(true) |
168 | 3 | .behavior_version(BehaviorVersion::latest()) |
169 | 3 | .timeout_config( |
170 | 3 | aws_config::timeout::TimeoutConfig::builder() |
171 | 3 | .connect_timeout(Duration::from_secs(30)) |
172 | 3 | .operation_timeout(Duration::from_mins(2)) |
173 | 3 | .build(), |
174 | | ) |
175 | 3 | .build(); |
176 | | |
177 | 3 | let s3_client = Client::from_conf(config); |
178 | | |
179 | 3 | Self::new_with_client_and_jitter( |
180 | 3 | spec, |
181 | 3 | s3_client, |
182 | 3 | spec.common.retry.make_jitter_fn(), |
183 | 3 | now_fn, |
184 | | ) |
185 | 3 | } |
186 | | |
187 | 15 | pub fn new_with_client_and_jitter( |
188 | 15 | spec: &ExperimentalOntapS3Spec, |
189 | 15 | s3_client: Client, |
190 | 15 | jitter_fn: Arc<dyn (Fn(Duration) -> Duration) + Send + Sync>, |
191 | 15 | now_fn: NowFn, |
192 | 15 | ) -> Result<Arc<Self>, Error> { |
193 | 15 | Ok(Arc::new(Self { |
194 | 15 | s3_client: Arc::new(s3_client), |
195 | 15 | now_fn, |
196 | 15 | bucket: spec.bucket.clone(), |
197 | 15 | key_prefix: spec |
198 | 15 | .common |
199 | 15 | .key_prefix |
200 | 15 | .as_ref() |
201 | 15 | .unwrap_or(&String::new()) |
202 | 15 | .clone(), |
203 | 15 | retrier: Retrier::new( |
204 | 15 | Arc::new(|duration| Box::pin1 (sleep1 (duration1 ))), |
205 | 15 | jitter_fn, |
206 | 15 | spec.common.retry.clone(), |
207 | | ), |
208 | 15 | consider_expired_after_s: i64::from(spec.common.consider_expired_after_s), |
209 | 15 | max_retry_buffer_per_request: spec |
210 | 15 | .common |
211 | 15 | .max_retry_buffer_per_request |
212 | 15 | .unwrap_or(DEFAULT_MAX_RETRY_BUFFER_PER_REQUEST), |
213 | 15 | multipart_max_concurrent_uploads: spec |
214 | 15 | .common |
215 | 15 | .multipart_max_concurrent_uploads |
216 | 15 | .unwrap_or(DEFAULT_MULTIPART_MAX_CONCURRENT_UPLOADS), |
217 | 15 | remove_callbacks: Mutex::new(vec![]), |
218 | | })) |
219 | 15 | } |
220 | | |
221 | 15 | fn make_s3_path(&self, key: &StoreKey<'_>) -> String { |
222 | 15 | format!("{}{}", self.key_prefix, key.as_str()) |
223 | 15 | } |
224 | | |
225 | 9 | async fn has(self: Pin<&Self>, digest: StoreKey<'_>) -> Result<Option<u64>, Error> { |
226 | 9 | let digest_clone = digest.into_owned(); |
227 | 9 | self.retrier |
228 | 10 | .retry9 (unfold9 (()9 , move |state| { |
229 | 10 | let local_digest = digest_clone.clone(); |
230 | 10 | async move { |
231 | 10 | let result = self |
232 | 10 | .s3_client |
233 | 10 | .head_object() |
234 | 10 | .bucket(&self.bucket) |
235 | 10 | .key(self.make_s3_path(&local_digest)) |
236 | 10 | .send() |
237 | 10 | .await; |
238 | | |
239 | 10 | match result { |
240 | 8 | Ok(head_object_output) => { |
241 | 8 | if self.consider_expired_after_s != 0 |
242 | 2 | && let Some(last_modified) = head_object_output.last_modified |
243 | | { |
244 | 2 | let now_s = (self.now_fn)().unix_timestamp() as i64; |
245 | 2 | if last_modified.secs() + self.consider_expired_after_s <= now_s { |
246 | 1 | let remove_callbacks = self.remove_callbacks.lock().clone(); |
247 | 1 | let mut callbacks: FuturesUnordered<_> = remove_callbacks |
248 | 1 | .into_iter() |
249 | 1 | .map(|callback| {0 |
250 | 0 | let store_key = local_digest.borrow(); |
251 | 0 | async move { callback.callback(store_key).await } |
252 | 0 | }) |
253 | 1 | .collect(); |
254 | 1 | while callbacks.next().await.is_some() {}0 |
255 | 1 | return Some((RetryResult::Ok(None), state)); |
256 | 1 | } |
257 | 6 | } |
258 | 7 | let Some(length) = head_object_output.content_length else { |
259 | 0 | return Some((RetryResult::Ok(None), state)); |
260 | | }; |
261 | 7 | if length >= 0 { |
262 | 7 | return Some((RetryResult::Ok(Some(length as u64)), state)); |
263 | 0 | } |
264 | 0 | Some(( |
265 | 0 | RetryResult::Err(make_err!( |
266 | 0 | Code::InvalidArgument, |
267 | 0 | "Negative content length in ONTAP S3: {length:?}" |
268 | 0 | )), |
269 | 0 | state, |
270 | 0 | )) |
271 | | } |
272 | 2 | Err(sdk_error) => match sdk_error.into_service_error() { |
273 | 1 | HeadObjectError::NotFound(_) => Some((RetryResult::Ok(None), state)), |
274 | 1 | other => Some(( |
275 | 1 | RetryResult::Retry(make_err!( |
276 | 1 | Code::Unavailable, |
277 | 1 | "Unhandled HeadObjectError in ONTAP S3: {other:?}" |
278 | 1 | )), |
279 | 1 | state, |
280 | 1 | )), |
281 | | }, |
282 | | } |
283 | 10 | } |
284 | 10 | })) |
285 | 9 | .await |
286 | 9 | } |
287 | | } |
288 | | |
289 | | #[async_trait] |
290 | | impl<I, NowFn> StoreDriver for OntapS3Store<NowFn> |
291 | | where |
292 | | I: InstantWrapper, |
293 | | NowFn: Fn() -> I + Send + Sync + Unpin + 'static, |
294 | | { |
295 | 0 | async fn post_init(self: Arc<Self>) -> Result<(), Error> { |
296 | | Ok(()) |
297 | 0 | } |
298 | | |
299 | | async fn has_with_results( |
300 | | self: Pin<&Self>, |
301 | | keys: &[StoreKey<'_>], |
302 | | results: &mut [Option<u64>], |
303 | 10 | ) -> Result<(), Error> { |
304 | | keys.iter() |
305 | | .zip(results.iter_mut()) |
306 | 10 | .map(|(key, result)| async move { |
307 | 10 | if is_zero_digest(key.borrow()) { |
308 | 1 | *result = Some(0); |
309 | 1 | return Ok::<_, Error>(()); |
310 | 9 | } |
311 | | |
312 | 9 | match self.has(key.borrow()).await { |
313 | 9 | Ok(size) => { |
314 | 9 | *result = size; |
315 | 9 | if size.is_none() { |
316 | 2 | event!( |
317 | 2 | Level::INFO, |
318 | 2 | key = %key.as_str(), |
319 | | "Object not found in ONTAP S3" |
320 | | ); |
321 | 7 | } |
322 | 9 | Ok(()) |
323 | | } |
324 | 0 | Err(err) => { |
325 | 0 | event!( |
326 | 0 | Level::ERROR, |
327 | 0 | key = %key.as_str(), |
328 | | error = ?err, |
329 | | "Error checking object existence" |
330 | | ); |
331 | 0 | Err(err) |
332 | | } |
333 | | } |
334 | 20 | }) |
335 | | .collect::<FuturesUnordered<_>>() |
336 | | .try_collect() |
337 | | .await |
338 | 10 | } |
339 | | |
340 | | async fn update( |
341 | | self: Pin<&Self>, |
342 | | key: StoreKey<'_>, |
343 | | mut reader: DropCloserReadHalf, |
344 | | size_info: UploadSizeInfo, |
345 | 2 | ) -> Result<u64, Error> { |
346 | | let s3_path = &self.make_s3_path(&key); |
347 | | |
348 | | let max_size = match size_info { |
349 | | UploadSizeInfo::ExactSize(sz) | UploadSizeInfo::MaxSize(sz) => sz, |
350 | | }; |
351 | | |
352 | | // For small files, use simple upload. For larger files or unknown size, use multipart |
353 | | if max_size < MIN_MULTIPART_SIZE && matches!(size_info, UploadSizeInfo::ExactSize(_)) { |
354 | | let UploadSizeInfo::ExactSize(sz) = size_info else { |
355 | | unreachable!("upload_size must be UploadSizeInfo::ExactSize here"); |
356 | | }; |
357 | | reader.set_max_recent_data_size( |
358 | | u64::try_from(self.max_retry_buffer_per_request) |
359 | | .err_tip(|| "Could not convert max_retry_buffer_per_request to u64")?, |
360 | | ); |
361 | | return self.retrier.retry( |
362 | 1 | unfold(reader, move |mut reader| async move { |
363 | 1 | let (mut tx, mut rx) = make_buf_channel_pair(); |
364 | | |
365 | 1 | let result = { |
366 | 1 | let reader_ref = &mut reader; |
367 | 1 | let (upload_res, bind_res): (Result<u64, Error>, Result<(), Error>) = tokio::join!(async move { |
368 | 1 | let raw_body_bytes = { |
369 | 1 | let mut raw_body_chunks = BytesMut::new(); |
370 | | loop { |
371 | 51 | match rx.recv().await { |
372 | 51 | Ok(chunk) => { |
373 | 51 | if chunk.is_empty() { |
374 | 1 | break Ok(raw_body_chunks.freeze()); |
375 | 50 | } |
376 | 50 | raw_body_chunks.extend_from_slice(&chunk); |
377 | | } |
378 | 0 | Err(err) => { |
379 | 0 | break Err(err); |
380 | | } |
381 | | } |
382 | | } |
383 | | }; |
384 | 1 | let internal_res = match raw_body_bytes { |
385 | 1 | Ok(body_bytes) => { |
386 | 1 | let hash = Sha256::digest(&body_bytes); |
387 | 1 | let body_len: u64 = body_bytes.len().try_into().unwrap_or(0); |
388 | 1 | let send_res = self.s3_client |
389 | 1 | .put_object() |
390 | 1 | .bucket(&self.bucket) |
391 | 1 | .key(s3_path.clone()) |
392 | 1 | .content_length(sz as i64) |
393 | 1 | .body( |
394 | 1 | ByteStream::from(body_bytes) |
395 | | ) |
396 | 1 | .set_checksum_algorithm(Some(aws_sdk_s3::types::ChecksumAlgorithm::Sha256)) |
397 | 1 | .set_checksum_sha256(Some(BASE64_STANDARD_NO_PAD.encode(hash))) |
398 | 1 | .customize() |
399 | 1 | .mutate_request(|req| {req.headers_mut().insert("x-amz-content-sha256", "UNSIGNED-PAYLOAD");}) |
400 | 1 | .send(); |
401 | 1 | Either::Left(send_res.map_ok_or_else(|e| Err( |
402 | 1 | Error::from_std_err0 (Code::Aborted0 , &e0 )), move |_| Ok(body_len))) |
403 | | } |
404 | 0 | Err(collect_err) => { |
405 | 0 | async fn make_collect_err(collect_err: Error) -> Result<u64, Error> { |
406 | 0 | Err(collect_err) |
407 | 0 | } |
408 | | |
409 | 0 | warn!( |
410 | | ?collect_err, |
411 | | "Failed to get body"); |
412 | 0 | let future_err = make_collect_err(collect_err); |
413 | 0 | Either::Right(future_err) |
414 | | } |
415 | | }; |
416 | 1 | internal_res.await |
417 | 1 | }, |
418 | 1 | tx.bind_buffered(reader_ref) |
419 | | ); |
420 | 1 | match (upload_res, bind_res) { |
421 | 1 | (Ok(size), Ok(())) => Ok(size), |
422 | 0 | (Err(e), _) | (_, Err(e)) => Err(e), |
423 | | } |
424 | 1 | .err_tip(|| "Failed to upload file to ONTAP S3 in single chunk") |
425 | | }; |
426 | | |
427 | 1 | let retry_result = result.map_or_else( |
428 | 0 | |mut err| { |
429 | 0 | err.code = Code::Aborted; |
430 | 0 | let bytes_received = reader.get_bytes_received(); |
431 | 0 | if let Err(try_reset_err) = reader.try_reset_stream() { |
432 | 0 | event!( |
433 | 0 | Level::ERROR, |
434 | | ?bytes_received, |
435 | | err = ?try_reset_err, |
436 | | "Unable to reset stream after failed upload in OntapS3Store::update" |
437 | | ); |
438 | 0 | return RetryResult::Err( |
439 | 0 | err |
440 | 0 | .merge(try_reset_err) |
441 | 0 | .append( |
442 | 0 | format!( |
443 | 0 | "Failed to retry upload with {bytes_received} bytes received in OntapS3Store::update" |
444 | 0 | ) |
445 | 0 | ) |
446 | 0 | ); |
447 | 0 | } |
448 | 0 | let err = err.append( |
449 | 0 | format!( |
450 | | "Retry on upload happened with {bytes_received} bytes received in OntapS3Store::update" |
451 | | ) |
452 | | ); |
453 | 0 | event!(Level::INFO, ?err, ?bytes_received, "Retryable ONTAP S3 error"); |
454 | 0 | RetryResult::Retry(err) |
455 | 0 | }, |
456 | | RetryResult::Ok |
457 | | ); |
458 | 1 | Some((retry_result, reader)) |
459 | 2 | }) |
460 | | ).await; |
461 | | } |
462 | | |
463 | | // Handle multipart upload for large files |
464 | | let upload_id = &self |
465 | | .retrier |
466 | 1 | .retry(unfold((), move |()| async move { |
467 | 1 | let retry_result = self |
468 | 1 | .s3_client |
469 | 1 | .create_multipart_upload() |
470 | 1 | .bucket(&self.bucket) |
471 | 1 | .key(s3_path) |
472 | 1 | .send() |
473 | 1 | .await |
474 | 1 | .map_or_else( |
475 | 0 | |e| { |
476 | 0 | RetryResult::Retry( |
477 | 0 | Error::from_std_err(Code::Aborted, &e) |
478 | 0 | .append("Failed to create multipart upload to ONTAP S3"), |
479 | 0 | ) |
480 | 0 | }, |
481 | 1 | |CreateMultipartUploadOutput { upload_id, .. }| { |
482 | 1 | upload_id.map_or_else( |
483 | 0 | || { |
484 | 0 | RetryResult::Err(make_err!( |
485 | 0 | Code::Internal, |
486 | 0 | "Expected upload_id to be set by ONTAP S3 response" |
487 | 0 | )) |
488 | 0 | }, |
489 | | RetryResult::Ok, |
490 | | ) |
491 | 1 | }, |
492 | | ); |
493 | 1 | Some((retry_result, ())) |
494 | 2 | })) |
495 | | .await?; |
496 | | |
497 | | let bytes_per_upload_part = |
498 | | (max_size / (MIN_MULTIPART_SIZE - 1)).clamp(MIN_MULTIPART_SIZE, MAX_MULTIPART_SIZE); |
499 | | |
500 | 1 | let upload_parts = move || async move { |
501 | 1 | let (tx, mut rx) = tokio::sync::mpsc::channel(self.multipart_max_concurrent_uploads); |
502 | | |
503 | 1 | let read_stream_fut = ( |
504 | 1 | async move { |
505 | 1 | let retrier = &Pin::get_ref(self).retrier; |
506 | 1 | let mut total_uploaded = 0; |
507 | 4 | for part_number in 1..i32::MAX1 { |
508 | 4 | let write_buf = reader |
509 | 4 | .consume( |
510 | | Some( |
511 | 4 | usize |
512 | 4 | ::try_from(bytes_per_upload_part) |
513 | 4 | .err_tip( |
514 | | || "Could not convert bytes_per_upload_part to usize" |
515 | 0 | )? |
516 | | ) |
517 | 4 | ).await |
518 | 4 | .err_tip(|| "Failed to read chunk in ontap_s3_store")?0 ; |
519 | 4 | if write_buf.is_empty() { |
520 | 1 | break; |
521 | 3 | } |
522 | | |
523 | 3 | total_uploaded += write_buf.len() as u64; |
524 | | |
525 | 3 | tx |
526 | 3 | .send( |
527 | 3 | retrier.retry( |
528 | 3 | unfold(write_buf, move |write_buf| async move { |
529 | 3 | let retry_result = self.s3_client |
530 | 3 | .upload_part() |
531 | 3 | .bucket(&self.bucket) |
532 | 3 | .key(s3_path) |
533 | 3 | .upload_id(upload_id) |
534 | 3 | .body(ByteStream::new(SdkBody::from(write_buf.clone()))) |
535 | 3 | .part_number(part_number) |
536 | 3 | .send().await |
537 | 3 | .map_or_else( |
538 | 0 | |e| { |
539 | 0 | RetryResult::Retry( |
540 | 0 | Error::from_std_err( |
541 | 0 | Code::Aborted,&e).append( |
542 | 0 | "Failed to upload part {part_number} in ONTAP S3 store" |
543 | 0 | ) |
544 | 0 | ) |
545 | 0 | }, |
546 | 3 | |mut response| { |
547 | 3 | RetryResult::Ok( |
548 | 3 | CompletedPartBuilder::default() |
549 | 3 | .set_e_tag(response.e_tag.take()) |
550 | 3 | .part_number(part_number) |
551 | 3 | .build() |
552 | 3 | ) |
553 | 3 | } |
554 | | ); |
555 | 3 | Some((retry_result, write_buf)) |
556 | 6 | }) |
557 | | ) |
558 | 3 | ).await |
559 | 3 | .map_err(|err| {0 |
560 | 0 | Error::from_std_err(Code::Internal, &err).append("Failed to send part to channel in ontap_s3_store") |
561 | 0 | })?; |
562 | | } |
563 | 1 | Result::<_, Error>::Ok(total_uploaded) |
564 | | } |
565 | 1 | ).fuse(); |
566 | | |
567 | 1 | let mut upload_futures = FuturesUnordered::new(); |
568 | 1 | let mut total_uploaded = 0; |
569 | 1 | let mut completed_parts = Vec::with_capacity( |
570 | 1 | usize::try_from(cmp::min( |
571 | 1 | MAX_UPLOAD_PARTS as u64, |
572 | 1 | max_size / bytes_per_upload_part + 1, |
573 | | )) |
574 | 1 | .err_tip(|| "Could not convert u64 to usize")?0 , |
575 | | ); |
576 | | |
577 | 1 | tokio::pin!(read_stream_fut); |
578 | | loop { |
579 | 8 | if read_stream_fut.is_terminated() && rx7 .is_empty7 () && upload_futures2 .is_empty2 () { |
580 | 1 | break; |
581 | 7 | } |
582 | 7 | tokio::select! { |
583 | 7 | result1 = &mut read_stream_fut => { |
584 | 1 | total_uploaded = result?0 ; |
585 | | }, |
586 | 7 | Some(upload_result3 ) = upload_futures.next() => completed_parts3 .push3 (upload_result3 ?0 ), |
587 | 7 | Some(fut3 ) = rx.recv() => upload_futures3 .push3 (fut3 ), |
588 | | } |
589 | | } |
590 | | |
591 | 1 | completed_parts.sort_unstable_by_key(|part| part.part_number); |
592 | | |
593 | 1 | self.retrier |
594 | 1 | .retry(unfold(completed_parts, move |completed_parts| async move { |
595 | | Some(( |
596 | 1 | self.s3_client |
597 | 1 | .complete_multipart_upload() |
598 | 1 | .bucket(&self.bucket) |
599 | 1 | .key(s3_path) |
600 | 1 | .multipart_upload( |
601 | 1 | CompletedMultipartUploadBuilder::default() |
602 | 1 | .set_parts(Some(completed_parts.clone())) |
603 | 1 | .build(), |
604 | 1 | ) |
605 | 1 | .upload_id(upload_id) |
606 | 1 | .send() |
607 | 1 | .await |
608 | 1 | .map_or_else( |
609 | 0 | |e| { |
610 | 0 | RetryResult::Retry( |
611 | 0 | Error::from_std_err(Code::Aborted, &e).append( |
612 | 0 | "Failed to complete multipart upload in ONTAP S3 store", |
613 | 0 | ), |
614 | 0 | ) |
615 | 0 | }, |
616 | 1 | |_| RetryResult::Ok(total_uploaded), |
617 | | ), |
618 | 1 | completed_parts, |
619 | | )) |
620 | 2 | })) |
621 | 1 | .await |
622 | 2 | }; |
623 | | |
624 | | upload_parts() |
625 | 0 | .or_else(move |mut e| async move { |
626 | 0 | let abort_res = self |
627 | 0 | .s3_client |
628 | 0 | .abort_multipart_upload() |
629 | 0 | .bucket(&self.bucket) |
630 | 0 | .key(s3_path) |
631 | 0 | .upload_id(upload_id) |
632 | 0 | .send() |
633 | 0 | .await; |
634 | 0 | if let Err(abort_err) = abort_res { |
635 | 0 | let err = Error::from_std_err(Code::Aborted, &abort_err) |
636 | 0 | .append("Failed to abort multipart upload in ONTAP S3 store"); |
637 | 0 | event!(Level::INFO, ?err, "Multipart upload error"); |
638 | 0 | e = e.merge(err); |
639 | 0 | } |
640 | 0 | Err(e) |
641 | 0 | }) |
642 | | .await |
643 | 2 | } |
644 | | |
645 | | async fn get_part( |
646 | | self: Pin<&Self>, |
647 | | key: StoreKey<'_>, |
648 | | writer: &mut DropCloserWriteHalf, |
649 | | offset: u64, |
650 | | length: Option<u64>, |
651 | 4 | ) -> Result<(), Error> { |
652 | | if is_zero_digest(key.borrow()) { |
653 | | writer |
654 | | .send_eof() |
655 | | .err_tip(|| "Failed to send zero EOF in ONTAP S3 store get_part")?; |
656 | | return Ok(()); |
657 | | } |
658 | | |
659 | | let s3_path = &self.make_s3_path(&key); |
660 | | let end_read_byte = length |
661 | 2 | .map_or(Some(None), |length| Some(offset.checked_add(length))) |
662 | | .err_tip(|| "Integer overflow protection triggered")?; |
663 | | |
664 | | self.retrier |
665 | 3 | .retry(unfold(writer, move |writer| async move { |
666 | 3 | let result = self |
667 | 3 | .s3_client |
668 | 3 | .get_object() |
669 | 3 | .bucket(&self.bucket) |
670 | 3 | .key(s3_path) |
671 | 3 | .range(format!( |
672 | | "bytes={}-{}", |
673 | 3 | offset + writer.get_bytes_written(), |
674 | 3 | end_read_byte.map_or_else(String::new, |v| v2 .to_string2 ()) |
675 | | )) |
676 | 3 | .send() |
677 | 3 | .await; |
678 | | |
679 | 3 | match result { |
680 | 3 | Ok(head_object_output) => { |
681 | 3 | let mut s3_in_stream = head_object_output.body; |
682 | 3 | let _bytes_sent = 0; |
683 | | |
684 | 7 | while let Some(maybe_bytes4 ) = s3_in_stream.next().await { |
685 | 4 | match maybe_bytes { |
686 | 4 | Ok(bytes) => { |
687 | 4 | if bytes.is_empty() { |
688 | 1 | continue; |
689 | 3 | } |
690 | | |
691 | | // Clone bytes before sending |
692 | 3 | let bytes_clone = bytes.clone(); |
693 | | |
694 | | // More robust sending mechanism |
695 | 3 | match writer.send(bytes).await { |
696 | 3 | Ok(()) => { |
697 | 3 | let _ = bytes_clone.len(); |
698 | 3 | } |
699 | 0 | Err(e) => { |
700 | 0 | return Some(( |
701 | 0 | RetryResult::Err(Error::from_std_err( |
702 | 0 | Code::Aborted,&e).append( |
703 | 0 | "Error sending bytes to consumer in ONTAP S3" |
704 | 0 | )), |
705 | 0 | writer, |
706 | 0 | )); |
707 | | } |
708 | | } |
709 | | } |
710 | 0 | Err(e) => { |
711 | 0 | return Some(( |
712 | 0 | RetryResult::Retry( |
713 | 0 | Error::from_std_err(Code::Aborted, &e) |
714 | 0 | .append("Bad bytestream element in ONTAP S3"), |
715 | 0 | ), |
716 | 0 | writer, |
717 | 0 | )); |
718 | | } |
719 | | } |
720 | | } |
721 | | |
722 | | // EOF handling |
723 | 3 | if let Err(e0 ) = writer.send_eof() { |
724 | 0 | return Some(( |
725 | 0 | RetryResult::Err( |
726 | 0 | Error::from_std_err(Code::Aborted, &e) |
727 | 0 | .append("Failed to send EOF to consumer in ONTAP S3"), |
728 | 0 | ), |
729 | 0 | writer, |
730 | 0 | )); |
731 | 3 | } |
732 | | |
733 | 3 | Some((RetryResult::Ok(()), writer)) |
734 | | } |
735 | 0 | Err(sdk_error) => match sdk_error.into_service_error() { |
736 | 0 | GetObjectError::NoSuchKey(e) => Some(( |
737 | 0 | RetryResult::Err( |
738 | 0 | Error::from_std_err(Code::NotFound, &e) |
739 | 0 | .append("No such key in ONTAP S3"), |
740 | 0 | ), |
741 | 0 | writer, |
742 | 0 | )), |
743 | 0 | other => Some(( |
744 | 0 | RetryResult::Retry( |
745 | 0 | Error::from_std_err(Code::Unavailable, &other) |
746 | 0 | .append("Unhandled GetObjectError in ONTAP S3"), |
747 | 0 | ), |
748 | 0 | writer, |
749 | 0 | )), |
750 | | }, |
751 | | } |
752 | 6 | })) |
753 | | .await |
754 | 4 | } |
755 | | |
756 | 0 | fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver { |
757 | 0 | self |
758 | 0 | } |
759 | | |
760 | 0 | fn as_any<'a>(&'a self) -> &'a (dyn core::any::Any + Sync + Send + 'static) { |
761 | 0 | self |
762 | 0 | } |
763 | | |
764 | 0 | fn as_any_arc(self: Arc<Self>) -> Arc<dyn core::any::Any + Sync + Send + 'static> { |
765 | 0 | self |
766 | 0 | } |
767 | | |
768 | 3 | fn register_remove_callback(self: Arc<Self>, callback: RemoveCallback) -> Result<(), Error> { |
769 | 3 | self.remove_callbacks.lock().push(callback); |
770 | 3 | Ok(()) |
771 | 3 | } |
772 | | } |
773 | | |
774 | | #[async_trait] |
775 | | impl<I, NowFn> HealthStatusIndicator for OntapS3Store<NowFn> |
776 | | where |
777 | | I: InstantWrapper, |
778 | | NowFn: Fn() -> I + Send + Sync + Unpin + 'static, |
779 | | { |
780 | 0 | fn get_name(&self) -> &'static str { |
781 | 0 | "OntapS3Store" |
782 | 0 | } |
783 | | |
784 | 0 | async fn check_health(&self, namespace: Cow<'static, str>) -> HealthStatus { |
785 | | StoreDriver::check_health(Pin::new(self), namespace).await |
786 | 0 | } |
787 | | } |