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 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(
217        &self,
218        region_file_id: &RegionFileId,
219        index_file_id: &RegionFileId,
220    ) -> Result<()> {
221        let path = location::sst_file_path(&self.table_dir, *region_file_id, self.path_type);
222        self.object_store
223            .delete(&path)
224            .await
225            .context(DeleteSstSnafu {
226                file_id: region_file_id.file_id(),
227            })?;
228
229        let path = location::index_file_path(&self.table_dir, *index_file_id, self.path_type);
230        self.object_store
231            .delete(&path)
232            .await
233            .context(DeleteIndexSnafu {
234                file_id: region_file_id.file_id(),
235            })?;
236
237        Ok(())
238    }
239
240    /// Returns the directory of the region in the table.
241    pub fn build_region_dir(&self, region_id: RegionId) -> String {
242        region_dir_from_table_dir(&self.table_dir, region_id, self.path_type)
243    }
244
245    /// Returns a reader builder for specific `file`.
246    pub(crate) fn read_sst(&self, file: FileHandle) -> ParquetReaderBuilder {
247        ParquetReaderBuilder::new(
248            self.table_dir.clone(),
249            self.path_type,
250            file,
251            self.object_store.clone(),
252        )
253    }
254
255    /// Writes a SST with specific `file_id` and `metadata` to the layer.
256    ///
257    /// Returns the info of the SST. If no data written, returns None.
258    pub async fn write_sst(
259        &self,
260        request: SstWriteRequest,
261        write_opts: &WriteOptions,
262        metrics: &mut Metrics,
263    ) -> Result<SstInfoArray> {
264        let region_id = request.metadata.region_id;
265        let cache_manager = request.cache_manager.clone();
266
267        let sst_info = if let Some(write_cache) = cache_manager.write_cache() {
268            // Write to the write cache.
269            write_cache
270                .write_and_upload_sst(
271                    request,
272                    SstUploadRequest {
273                        dest_path_provider: RegionFilePathFactory::new(
274                            self.table_dir.clone(),
275                            self.path_type,
276                        ),
277                        remote_store: self.object_store.clone(),
278                    },
279                    write_opts,
280                    metrics,
281                )
282                .await?
283        } else {
284            // Write cache is disabled.
285            let store = self.object_store.clone();
286            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
287            let indexer_builder = IndexerBuilderImpl {
288                build_type: request.op_type.into(),
289                metadata: request.metadata.clone(),
290                row_group_size: write_opts.row_group_size,
291                puffin_manager: self
292                    .puffin_manager_factory
293                    .build(store, path_provider.clone()),
294                intermediate_manager: self.intermediate_manager.clone(),
295                index_options: request.index_options,
296                inverted_index_config: request.inverted_index_config,
297                fulltext_index_config: request.fulltext_index_config,
298                bloom_filter_index_config: request.bloom_filter_index_config,
299            };
300            // We disable write cache on file system but we still use atomic write.
301            // TODO(yingwen): If we support other non-fs stores without the write cache, then
302            // we may have find a way to check whether we need the cleaner.
303            let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
304            let mut writer = ParquetWriter::new_with_object_store(
305                self.object_store.clone(),
306                request.metadata,
307                request.index_config,
308                indexer_builder,
309                path_provider,
310                metrics,
311            )
312            .await
313            .with_file_cleaner(cleaner);
314            match request.source {
315                Either::Left(source) => {
316                    writer
317                        .write_all(source, request.max_sequence, write_opts)
318                        .await?
319                }
320                Either::Right(flat_source) => {
321                    writer.write_all_flat(flat_source, write_opts).await?
322                }
323            }
324        };
325
326        // Put parquet metadata to cache manager.
327        if !sst_info.is_empty() {
328            for sst in &sst_info {
329                if let Some(parquet_metadata) = &sst.file_metadata {
330                    cache_manager.put_parquet_meta_data(
331                        RegionFileId::new(region_id, sst.file_id),
332                        parquet_metadata.clone(),
333                    )
334                }
335            }
336        }
337
338        Ok(sst_info)
339    }
340
341    /// Puts encoded SST bytes to the write cache (if enabled) and uploads it to the object store.
342    pub(crate) async fn put_sst(
343        &self,
344        data: &bytes::Bytes,
345        region_id: RegionId,
346        sst_info: &SstInfo,
347        cache_manager: &CacheManagerRef,
348    ) -> Result<Metrics> {
349        if let Some(write_cache) = cache_manager.write_cache() {
350            // Write to cache and upload to remote store
351            let upload_request = SstUploadRequest {
352                dest_path_provider: RegionFilePathFactory::new(
353                    self.table_dir.clone(),
354                    self.path_type,
355                ),
356                remote_store: self.object_store.clone(),
357            };
358            write_cache
359                .put_and_upload_sst(data, region_id, sst_info, upload_request)
360                .await
361        } else {
362            let start = Instant::now();
363            let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
364            let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
365            let sst_file_path =
366                path_provider.build_sst_file_path(RegionFileId::new(region_id, sst_info.file_id));
367            let mut writer = self
368                .object_store
369                .writer_with(&sst_file_path)
370                .chunk(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
371                .concurrent(DEFAULT_WRITE_CONCURRENCY)
372                .await
373                .context(OpenDalSnafu)?;
374            if let Err(err) = writer.write(data.clone()).await.context(OpenDalSnafu) {
375                cleaner.clean_by_file_id(sst_info.file_id).await;
376                return Err(err);
377            }
378            if let Err(err) = writer.close().await.context(OpenDalSnafu) {
379                cleaner.clean_by_file_id(sst_info.file_id).await;
380                return Err(err);
381            }
382            let mut metrics = Metrics::new(WriteType::Flush);
383            metrics.write_batch = start.elapsed();
384            Ok(metrics)
385        }
386    }
387
388    /// Lists the SST entries from the storage layer in the table directory.
389    pub fn storage_sst_entries(&self) -> impl Stream<Item = Result<StorageSstEntry>> + use<> {
390        let object_store = self.object_store.clone();
391        let table_dir = self.table_dir.clone();
392
393        try_stream! {
394            let mut lister = object_store
395                .lister_with(table_dir.as_str())
396                .recursive(true)
397                .await
398                .context(OpenDalSnafu)?;
399
400            while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? {
401                let metadata = entry.metadata();
402                if metadata.is_dir() {
403                    continue;
404                }
405
406                let path = entry.path();
407                if !path.ends_with(".parquet") && !path.ends_with(".puffin") {
408                    continue;
409                }
410
411                let file_size = metadata.content_length();
412                let file_size = if file_size == 0 { None } else { Some(file_size) };
413                let last_modified_ms = metadata
414                    .last_modified()
415                    .map(|ts| Timestamp::new_millisecond(ts.timestamp_millis()));
416
417                let entry = StorageSstEntry {
418                    file_path: path.to_string(),
419                    file_size,
420                    last_modified_ms,
421                    node_id: None,
422                };
423
424                yield entry;
425            }
426        }
427    }
428}
429
430/// `OperationType` represents the origin of the `SstWriteRequest`.
431#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
432pub enum OperationType {
433    Flush,
434    Compact,
435}
436
437/// Contents to build a SST.
438pub struct SstWriteRequest {
439    pub op_type: OperationType,
440    pub metadata: RegionMetadataRef,
441    pub source: Either<Source, FlatSource>,
442    pub cache_manager: CacheManagerRef,
443    #[allow(dead_code)]
444    pub storage: Option<String>,
445    pub max_sequence: Option<SequenceNumber>,
446
447    /// Configs for index
448    pub index_options: IndexOptions,
449    pub index_config: IndexConfig,
450    pub inverted_index_config: InvertedIndexConfig,
451    pub fulltext_index_config: FulltextIndexConfig,
452    pub bloom_filter_index_config: BloomFilterConfig,
453}
454
455/// Cleaner to remove temp files on the atomic write dir.
456pub(crate) struct TempFileCleaner {
457    region_id: RegionId,
458    object_store: ObjectStore,
459}
460
461impl TempFileCleaner {
462    /// Constructs the cleaner for the region and store.
463    pub(crate) fn new(region_id: RegionId, object_store: ObjectStore) -> Self {
464        Self {
465            region_id,
466            object_store,
467        }
468    }
469
470    /// Removes the SST and index file from the local atomic dir by the file id.
471    pub(crate) async fn clean_by_file_id(&self, file_id: FileId) {
472        let sst_key = IndexKey::new(self.region_id, file_id, FileType::Parquet).to_string();
473        let index_key = IndexKey::new(self.region_id, file_id, FileType::Puffin).to_string();
474
475        Self::clean_atomic_dir_files(&self.object_store, &[&sst_key, &index_key]).await;
476    }
477
478    /// Removes the files from the local atomic dir by their names.
479    pub(crate) async fn clean_atomic_dir_files(
480        local_store: &ObjectStore,
481        names_to_remove: &[&str],
482    ) {
483        // We don't know the actual suffix of the file under atomic dir, so we have
484        // to list the dir. The cost should be acceptable as there won't be to many files.
485        let Ok(entries) = local_store.list(ATOMIC_WRITE_DIR).await.inspect_err(|e| {
486            if e.kind() != ErrorKind::NotFound {
487                common_telemetry::error!(e; "Failed to list tmp files for {:?}", names_to_remove)
488            }
489        }) else {
490            return;
491        };
492
493        // In our case, we can ensure the file id is unique so it is safe to remove all files
494        // with the same file id under the atomic write dir.
495        let actual_files: Vec<_> = entries
496            .into_iter()
497            .filter_map(|entry| {
498                if entry.metadata().is_dir() {
499                    return None;
500                }
501
502                // Remove name that matches files_to_remove.
503                let should_remove = names_to_remove
504                    .iter()
505                    .any(|file| entry.name().starts_with(file));
506                if should_remove {
507                    Some(entry.path().to_string())
508                } else {
509                    None
510                }
511            })
512            .collect();
513
514        common_telemetry::warn!(
515            "Clean files {:?} under atomic write dir for {:?}",
516            actual_files,
517            names_to_remove
518        );
519
520        if let Err(e) = local_store.delete_iter(actual_files).await {
521            common_telemetry::error!(e; "Failed to delete tmp file for {:?}", names_to_remove);
522        }
523    }
524}
525
526pub(crate) async fn new_fs_cache_store(root: &str) -> Result<ObjectStore> {
527    let atomic_write_dir = join_dir(root, ATOMIC_WRITE_DIR);
528    clean_dir(&atomic_write_dir).await?;
529
530    // Compatible code. Remove this after a major release.
531    let old_atomic_temp_dir = join_dir(root, OLD_ATOMIC_WRITE_DIR);
532    clean_dir(&old_atomic_temp_dir).await?;
533
534    let builder = Fs::default().root(root).atomic_write_dir(&atomic_write_dir);
535    let store = ObjectStore::new(builder).context(OpenDalSnafu)?.finish();
536
537    Ok(with_instrument_layers(store, false))
538}
539
540/// Clean the directory.
541async fn clean_dir(dir: &str) -> Result<()> {
542    if tokio::fs::try_exists(dir)
543        .await
544        .context(CleanDirSnafu { dir })?
545    {
546        tokio::fs::remove_dir_all(dir)
547            .await
548            .context(CleanDirSnafu { dir })?;
549    }
550
551    Ok(())
552}
553
554/// Path provider for SST file and index file.
555pub trait FilePathProvider: Send + Sync {
556    /// Creates index file path of given file id.
557    fn build_index_file_path(&self, file_id: RegionFileId) -> String;
558
559    /// Creates SST file path of given file id.
560    fn build_sst_file_path(&self, file_id: RegionFileId) -> String;
561}
562
563/// Path provider that builds paths in local write cache.
564#[derive(Clone)]
565pub(crate) struct WriteCachePathProvider {
566    file_cache: FileCacheRef,
567}
568
569impl WriteCachePathProvider {
570    /// Creates a new `WriteCachePathProvider` instance.
571    pub fn new(file_cache: FileCacheRef) -> Self {
572        Self { file_cache }
573    }
574}
575
576impl FilePathProvider for WriteCachePathProvider {
577    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
578        let puffin_key = IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Puffin);
579        self.file_cache.cache_file_path(puffin_key)
580    }
581
582    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
583        let parquet_file_key =
584            IndexKey::new(file_id.region_id(), file_id.file_id(), FileType::Parquet);
585        self.file_cache.cache_file_path(parquet_file_key)
586    }
587}
588
589/// Path provider that builds paths in region storage path.
590#[derive(Clone, Debug)]
591pub(crate) struct RegionFilePathFactory {
592    pub(crate) table_dir: String,
593    pub(crate) path_type: PathType,
594}
595
596impl RegionFilePathFactory {
597    /// Creates a new `RegionFilePathFactory` instance.
598    pub fn new(table_dir: String, path_type: PathType) -> Self {
599        Self {
600            table_dir,
601            path_type,
602        }
603    }
604}
605
606impl FilePathProvider for RegionFilePathFactory {
607    fn build_index_file_path(&self, file_id: RegionFileId) -> String {
608        location::index_file_path(&self.table_dir, file_id, self.path_type)
609    }
610
611    fn build_sst_file_path(&self, file_id: RegionFileId) -> String {
612        location::sst_file_path(&self.table_dir, file_id, self.path_type)
613    }
614}