mito2/
access_layer.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (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//     http://www.apache.org/licenses/LICENSE-2.0
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
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18use async_stream::try_stream;
19use common_time::Timestamp;
20use either::Either;
21use futures::{Stream, TryStreamExt};
22use object_store::services::Fs;
23use object_store::util::{join_dir, with_instrument_layers};
24use object_store::{ATOMIC_WRITE_DIR, ErrorKind, OLD_ATOMIC_WRITE_DIR, ObjectStore};
25use smallvec::SmallVec;
26use snafu::ResultExt;
27use store_api::metadata::RegionMetadataRef;
28use store_api::region_request::PathType;
29use store_api::sst_entry::StorageSstEntry;
30use store_api::storage::{FileId, RegionId, SequenceNumber};
31
32use crate::cache::CacheManagerRef;
33use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey};
34use crate::cache::write_cache::SstUploadRequest;
35use crate::config::{BloomFilterConfig, FulltextIndexConfig, IndexConfig, InvertedIndexConfig};
36use crate::error::{CleanDirSnafu, DeleteIndexSnafu, DeleteSstSnafu, OpenDalSnafu, Result};
37use crate::metrics::{COMPACTION_STAGE_ELAPSED, FLUSH_ELAPSED};
38use crate::read::{FlatSource, Source};
39use crate::region::options::IndexOptions;
40use crate::sst::file::{FileHandle, RegionFileId};
41use crate::sst::index::IndexerBuilderImpl;
42use crate::sst::index::intermediate::IntermediateManager;
43use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager};
44use crate::sst::location::{self, region_dir_from_table_dir};
45use crate::sst::parquet::reader::ParquetReaderBuilder;
46use crate::sst::parquet::writer::ParquetWriter;
47use crate::sst::parquet::{SstInfo, WriteOptions};
48use crate::sst::{DEFAULT_WRITE_BUFFER_SIZE, DEFAULT_WRITE_CONCURRENCY};
49
50pub type AccessLayerRef = Arc<AccessLayer>;
51/// SST write results.
52pub type SstInfoArray = SmallVec<[SstInfo; 2]>;
53
54/// Write operation type.
55#[derive(Eq, PartialEq, Debug)]
56pub enum WriteType {
57    /// Writes from flush
58    Flush,
59    /// Writes from compaction.
60    Compaction,
61}
62
63#[derive(Debug)]
64pub struct Metrics {
65    pub(crate) write_type: WriteType,
66    pub(crate) iter_source: Duration,
67    pub(crate) write_batch: Duration,
68    pub(crate) update_index: Duration,
69    pub(crate) upload_parquet: Duration,
70    pub(crate) upload_puffin: Duration,
71    pub(crate) compact_memtable: Duration,
72}
73
74impl Metrics {
75    pub(crate) fn new(write_type: WriteType) -> Self {
76        Self {
77            write_type,
78            iter_source: Default::default(),
79            write_batch: Default::default(),
80            update_index: Default::default(),
81            upload_parquet: Default::default(),
82            upload_puffin: Default::default(),
83            compact_memtable: Default::default(),
84        }
85    }
86
87    pub(crate) fn merge(mut self, other: Self) -> Self {
88        assert_eq!(self.write_type, other.write_type);
89        self.iter_source += other.iter_source;
90        self.write_batch += other.write_batch;
91        self.update_index += other.update_index;
92        self.upload_parquet += other.upload_parquet;
93        self.upload_puffin += other.upload_puffin;
94        self.compact_memtable += other.compact_memtable;
95        self
96    }
97
98    pub(crate) fn observe(self) {
99        match self.write_type {
100            WriteType::Flush => {
101                FLUSH_ELAPSED
102                    .with_label_values(&["iter_source"])
103                    .observe(self.iter_source.as_secs_f64());
104                FLUSH_ELAPSED
105                    .with_label_values(&["write_batch"])
106                    .observe(self.write_batch.as_secs_f64());
107                FLUSH_ELAPSED
108                    .with_label_values(&["update_index"])
109                    .observe(self.update_index.as_secs_f64());
110                FLUSH_ELAPSED
111                    .with_label_values(&["upload_parquet"])
112                    .observe(self.upload_parquet.as_secs_f64());
113                FLUSH_ELAPSED
114                    .with_label_values(&["upload_puffin"])
115                    .observe(self.upload_puffin.as_secs_f64());
116                if !self.compact_memtable.is_zero() {
117                    FLUSH_ELAPSED
118                        .with_label_values(&["compact_memtable"])
119                        .observe(self.upload_puffin.as_secs_f64());
120                }
121            }
122            WriteType::Compaction => {
123                COMPACTION_STAGE_ELAPSED
124                    .with_label_values(&["iter_source"])
125                    .observe(self.iter_source.as_secs_f64());
126                COMPACTION_STAGE_ELAPSED
127                    .with_label_values(&["write_batch"])
128                    .observe(self.write_batch.as_secs_f64());
129                COMPACTION_STAGE_ELAPSED
130                    .with_label_values(&["update_index"])
131                    .observe(self.update_index.as_secs_f64());
132                COMPACTION_STAGE_ELAPSED
133                    .with_label_values(&["upload_parquet"])
134                    .observe(self.upload_parquet.as_secs_f64());
135                COMPACTION_STAGE_ELAPSED
136                    .with_label_values(&["upload_puffin"])
137                    .observe(self.upload_puffin.as_secs_f64());
138            }
139        };
140    }
141}
142
143/// A layer to access SST files under the same directory.
144pub struct AccessLayer {
145    table_dir: String,
146    /// Path type for generating file paths.
147    path_type: PathType,
148    /// Target object store.
149    object_store: ObjectStore,
150    /// Puffin manager factory for index.
151    puffin_manager_factory: PuffinManagerFactory,
152    /// Intermediate manager for inverted index.
153    intermediate_manager: IntermediateManager,
154}
155
156impl std::fmt::Debug for AccessLayer {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.debug_struct("AccessLayer")
159            .field("table_dir", &self.table_dir)
160            .finish()
161    }
162}
163
164impl AccessLayer {
165    /// Returns a new [AccessLayer] for specific `table_dir`.
166    pub fn new(
167        table_dir: impl Into<String>,
168        path_type: PathType,
169        object_store: ObjectStore,
170        puffin_manager_factory: PuffinManagerFactory,
171        intermediate_manager: IntermediateManager,
172    ) -> AccessLayer {
173        AccessLayer {
174            table_dir: table_dir.into(),
175            path_type,
176            object_store,
177            puffin_manager_factory,
178            intermediate_manager,
179        }
180    }
181
182    /// Returns the directory of the table.
183    pub fn table_dir(&self) -> &str {
184        &self.table_dir
185    }
186
187    /// Returns the object store of the layer.
188    pub fn object_store(&self) -> &ObjectStore {
189        &self.object_store
190    }
191
192    /// Returns the path type of the layer.
193    pub fn path_type(&self) -> PathType {
194        self.path_type
195    }
196
197    /// Returns the puffin manager factory.
198    pub fn puffin_manager_factory(&self) -> &PuffinManagerFactory {
199        &self.puffin_manager_factory
200    }
201
202    /// Returns the intermediate manager.
203    pub fn intermediate_manager(&self) -> &IntermediateManager {
204        &self.intermediate_manager
205    }
206
207    /// Build the puffin manager.
208    pub(crate) fn build_puffin_manager(&self) -> SstPuffinManager {
209        let store = self.object_store.clone();
210        let path_provider =
211            RegionFilePathFactory::new(self.table_dir().to_string(), self.path_type());
212        self.puffin_manager_factory.build(store, path_provider)
213    }
214
215    /// Deletes a SST file (and its index file if it has one) with given file id.
216    pub(crate) async fn delete_sst(&self, region_file_id: &RegionFileId) -> Result<()> {
217        let path = location::sst_file_path(&self.table_dir, *region_file_id, self.path_type);
218        self.object_store
219            .delete(&path)
220            .await
221            .context(DeleteSstSnafu {
222                file_id: region_file_id.file_id(),
223            })?;
224
225        let path = location::index_file_path(&self.table_dir, *region_file_id, self.path_type);
226        self.object_store
227            .delete(&path)
228            .await
229            .context(DeleteIndexSnafu {
230                file_id: region_file_id.file_id(),
231            })?;
232
233        Ok(())
234    }
235
236    /// Returns the directory of the region in the table.
237    pub fn build_region_dir(&self, region_id: RegionId) -> String {
238        region_dir_from_table_dir(&self.table_dir, region_id, self.path_type)
239    }
240
241    /// Returns a reader builder for specific `file`.
242    pub(crate) fn read_sst(&self, file: FileHandle) -> ParquetReaderBuilder {
243        ParquetReaderBuilder::new(
244            self.table_dir.clone(),
245            self.path_type,
246            file,
247            self.object_store.clone(),
248        )
249    }
250
251    /// Writes a SST with specific `file_id` and `metadata` to the layer.
252    ///
253    /// Returns the info of the SST. If no data written, returns None.
254    pub async fn write_sst(
255        &self,
256        request: SstWriteRequest,
257        write_opts: &WriteOptions,
258        write_type: WriteType,
259    ) -> Result<(SstInfoArray, Metrics)> {
260        let region_id = request.metadata.region_id;
261        let cache_manager = request.cache_manager.clone();
262
263        let (sst_info, metrics) = if let Some(write_cache) = cache_manager.write_cache() {
264            // Write to the write cache.
265            write_cache
266                .write_and_upload_sst(
267                    request,
268                    SstUploadRequest {
269                        dest_path_provider: RegionFilePathFactory::new(
270                            self.table_dir.clone(),
271                            self.path_type,
272                        ),
273                        remote_store: self.object_store.clone(),
274                    },
275                    write_opts,
276                    write_type,
277                )
278                .await?
279        } else {
280            // Write cache is disabled.
281            let store = self.object_store.clone();
282            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
283            let indexer_builder = IndexerBuilderImpl {
284                build_type: request.op_type.into(),
285                metadata: request.metadata.clone(),
286                row_group_size: write_opts.row_group_size,
287                puffin_manager: self
288                    .puffin_manager_factory
289                    .build(store, path_provider.clone()),
290                intermediate_manager: self.intermediate_manager.clone(),
291                index_options: request.index_options,
292                inverted_index_config: request.inverted_index_config,
293                fulltext_index_config: request.fulltext_index_config,
294                bloom_filter_index_config: request.bloom_filter_index_config,
295            };
296            // We disable write cache on file system but we still use atomic write.
297            // TODO(yingwen): If we support other non-fs stores without the write cache, then
298            // we may have find a way to check whether we need the cleaner.
299            let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
300            let mut writer = ParquetWriter::new_with_object_store(
301                self.object_store.clone(),
302                request.metadata,
303                request.index_config,
304                indexer_builder,
305                path_provider,
306                Metrics::new(write_type),
307            )
308            .await
309            .with_file_cleaner(cleaner);
310            let ssts = match request.source {
311                Either::Left(source) => {
312                    writer
313                        .write_all(source, request.max_sequence, write_opts)
314                        .await?
315                }
316                Either::Right(flat_source) => {
317                    writer.write_all_flat(flat_source, write_opts).await?
318                }
319            };
320            let metrics = writer.into_metrics();
321            (ssts, metrics)
322        };
323
324        // Put parquet metadata to cache manager.
325        if !sst_info.is_empty() {
326            for sst in &sst_info {
327                if let Some(parquet_metadata) = &sst.file_metadata {
328                    cache_manager.put_parquet_meta_data(
329                        RegionFileId::new(region_id, sst.file_id),
330                        parquet_metadata.clone(),
331                    )
332                }
333            }
334        }
335
336        Ok((sst_info, metrics))
337    }
338
339    /// Puts encoded SST bytes to the write cache (if enabled) and uploads it to the object store.
340    pub(crate) async fn put_sst(
341        &self,
342        data: &bytes::Bytes,
343        region_id: RegionId,
344        sst_info: &SstInfo,
345        cache_manager: &CacheManagerRef,
346    ) -> Result<Metrics> {
347        if let Some(write_cache) = cache_manager.write_cache() {
348            // Write to cache and upload to remote store
349            let upload_request = SstUploadRequest {
350                dest_path_provider: RegionFilePathFactory::new(
351                    self.table_dir.clone(),
352                    self.path_type,
353                ),
354                remote_store: self.object_store.clone(),
355            };
356            write_cache
357                .put_and_upload_sst(data, region_id, sst_info, upload_request)
358                .await
359        } else {
360            let start = Instant::now();
361            let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
362            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
363            let sst_file_path =
364                path_provider.build_sst_file_path(RegionFileId::new(region_id, sst_info.file_id));
365            let mut writer = self
366                .object_store
367                .writer_with(&sst_file_path)
368                .chunk(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
369                .concurrent(DEFAULT_WRITE_CONCURRENCY)
370                .await
371                .context(OpenDalSnafu)?;
372            if let Err(err) = writer.write(data.clone()).await.context(OpenDalSnafu) {
373                cleaner.clean_by_file_id(sst_info.file_id).await;
374                return Err(err);
375            }
376            if let Err(err) = writer.close().await.context(OpenDalSnafu) {
377                cleaner.clean_by_file_id(sst_info.file_id).await;
378                return Err(err);
379            }
380            let mut metrics = Metrics::new(WriteType::Flush);
381            metrics.write_batch = start.elapsed();
382            Ok(metrics)
383        }
384    }
385
386    /// Lists the SST entries from the storage layer in the table directory.
387    pub fn storage_sst_entries(&self) -> impl Stream<Item = Result<StorageSstEntry>> + use<> {
388        let object_store = self.object_store.clone();
389        let table_dir = self.table_dir.clone();
390
391        try_stream! {
392            let mut lister = object_store
393                .lister_with(table_dir.as_str())
394                .recursive(true)
395                .await
396                .context(OpenDalSnafu)?;
397
398            while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
399                let metadata = entry.metadata();
400                if metadata.is_dir() {
401                    continue;
402                }
403
404                let path = entry.path();
405                if !path.ends_with(".parquet") && !path.ends_with(".puffin") {
406                    continue;
407                }
408
409                let file_size = metadata.content_length();
410                let file_size = if file_size == 0 { None } else { Some(file_size) };
411                let last_modified_ms = metadata
412                    .last_modified()
413                    .map(|ts| Timestamp::new_millisecond(ts.timestamp_millis()));
414
415                let entry = StorageSstEntry {
416                    file_path: path.to_string(),
417                    file_size,
418                    last_modified_ms,
419                    node_id: None,
420                };
421
422                yield entry;
423            }
424        }
425    }
426}
427
428/// `OperationType` represents the origin of the `SstWriteRequest`.
429#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
430pub enum OperationType {
431    Flush,
432    Compact,
433}
434
435/// Contents to build a SST.
436pub struct SstWriteRequest {
437    pub op_type: OperationType,
438    pub metadata: RegionMetadataRef,
439    pub source: Either<Source, FlatSource>,
440    pub cache_manager: CacheManagerRef,
441    #[allow(dead_code)]
442    pub storage: Option<String>,
443    pub max_sequence: Option<SequenceNumber>,
444
445    /// Configs for index
446    pub index_options: IndexOptions,
447    pub index_config: IndexConfig,
448    pub inverted_index_config: InvertedIndexConfig,
449    pub fulltext_index_config: FulltextIndexConfig,
450    pub bloom_filter_index_config: BloomFilterConfig,
451}
452
453/// Cleaner to remove temp files on the atomic write dir.
454pub(crate) struct TempFileCleaner {
455    region_id: RegionId,
456    object_store: ObjectStore,
457}
458
459impl TempFileCleaner {
460    /// Constructs the cleaner for the region and store.
461    pub(crate) fn new(region_id: RegionId, object_store: ObjectStore) -> Self {
462        Self {
463            region_id,
464            object_store,
465        }
466    }
467
468    /// Removes the SST and index file from the local atomic dir by the file id.
469    pub(crate) async fn clean_by_file_id(&self, file_id: FileId) {
470        let sst_key = IndexKey::new(self.region_id, file_id, FileType::Parquet).to_string();
471        let index_key = IndexKey::new(self.region_id, file_id, FileType::Puffin).to_string();
472
473        Self::clean_atomic_dir_files(&self.object_store, &[&sst_key, &index_key]).await;
474    }
475
476    /// Removes the files from the local atomic dir by their names.
477    pub(crate) async fn clean_atomic_dir_files(
478        local_store: &ObjectStore,
479        names_to_remove: &[&str],
480    ) {
481        // We don't know the actual suffix of the file under atomic dir, so we have
482        // to list the dir. The cost should be acceptable as there won't be to many files.
483        let Ok(entries) = local_store.list(ATOMIC_WRITE_DIR).await.inspect_err(|e| {
484            if e.kind() != ErrorKind::NotFound {
485                common_telemetry::error!(e; "Failed to list tmp files for {:?}", names_to_remove)
486            }
487        }) else {
488            return;
489        };
490
491        // In our case, we can ensure the file id is unique so it is safe to remove all files
492        // with the same file id under the atomic write dir.
493        let actual_files: Vec<_> = entries
494            .into_iter()
495            .filter_map(|entry| {
496                if entry.metadata().is_dir() {
497                    return None;
498                }
499
500                // Remove name that matches files_to_remove.
501                let should_remove = names_to_remove
502                    .iter()
503                    .any(|file| entry.name().starts_with(file));
504                if should_remove {
505                    Some(entry.path().to_string())
506                } else {
507                    None
508                }
509            })
510            .collect();
511
512        common_telemetry::warn!(
513            "Clean files {:?} under atomic write dir for {:?}",
514            actual_files,
515            names_to_remove
516        );
517
518        if let Err(e) = local_store.delete_iter(actual_files).await {
519            common_telemetry::error!(e; "Failed to delete tmp file for {:?}", names_to_remove);
520        }
521    }
522}
523
524pub(crate) async fn new_fs_cache_store(root: &str) -> Result<ObjectStore> {
525    let atomic_write_dir = join_dir(root, ATOMIC_WRITE_DIR);
526    clean_dir(&atomic_write_dir).await?;
527
528    // Compatible code. Remove this after a major release.
529    let old_atomic_temp_dir = join_dir(root, OLD_ATOMIC_WRITE_DIR);
530    clean_dir(&old_atomic_temp_dir).await?;
531
532    let builder = Fs::default().root(root).atomic_write_dir(&atomic_write_dir);
533    let store = ObjectStore::new(builder).context(OpenDalSnafu)?.finish();
534
535    Ok(with_instrument_layers(store, false))
536}
537
538/// Clean the directory.
539async fn clean_dir(dir: &str) -> Result<()> {
540    if tokio::fs::try_exists(dir)
541        .await
542        .context(CleanDirSnafu { dir })?
543    {
544        tokio::fs::remove_dir_all(dir)
545            .await
546            .context(CleanDirSnafu { dir })?;
547    }
548
549    Ok(())
550}
551
552/// Path provider for SST file and index file.
553pub trait FilePathProvider: Send + Sync {
554    /// Creates index file path of given file id.
555    fn build_index_file_path(&self, file_id: RegionFileId) -> String;
556
557    /// Creates SST file path of given file id.
558    fn build_sst_file_path(&self, file_id: RegionFileId) -> String;
559}
560
561/// Path provider that builds paths in local write cache.
562#[derive(Clone)]
563pub(crate) struct WriteCachePathProvider {
564    file_cache: FileCacheRef,
565}
566
567impl WriteCachePathProvider {
568    /// Creates a new `WriteCachePathProvider` instance.
569    pub fn new(file_cache: FileCacheRef) -> Self {
570        Self { file_cache }
571    }
572}
573
574impl FilePathProvider for WriteCachePathProvider {
575    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
576        let puffin_key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Puffin);
577        self.file_cache.cache_file_path(puffin_key)
578    }
579
580    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
581        let parquet_file_key =
582            IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
583        self.file_cache.cache_file_path(parquet_file_key)
584    }
585}
586
587/// Path provider that builds paths in region storage path.
588#[derive(Clone, Debug)]
589pub(crate) struct RegionFilePathFactory {
590    pub(crate) table_dir: String,
591    pub(crate) path_type: PathType,
592}
593
594impl RegionFilePathFactory {
595    /// Creates a new `RegionFilePathFactory` instance.
596    pub fn new(table_dir: String, path_type: PathType) -> Self {
597        Self {
598            table_dir,
599            path_type,
600        }
601    }
602}
603
604impl FilePathProvider for RegionFilePathFactory {
605    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
606        location::index_file_path(&self.table_dir, file_id, self.path_type)
607    }
608
609    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
610        location::sst_file_path(&self.table_dir, file_id, self.path_type)
611    }
612}