sst_file_writer.cc 7.8 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 3 4
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
5 6
//  This source code is also licensed under the GPLv2 license found in the
//  COPYING file in the root directory of this source tree.
7 8 9 10 11 12 13

#include "rocksdb/sst_file_writer.h"

#include <vector>
#include "db/dbformat.h"
#include "rocksdb/table.h"
#include "table/block_based_table_builder.h"
14
#include "table/sst_file_writer_collectors.h"
15
#include "util/file_reader_writer.h"
16
#include "util/sync_point.h"
17 18 19 20 21

namespace rocksdb {

const std::string ExternalSstFilePropertyNames::kVersion =
    "rocksdb.external_sst_file.version";
22 23
const std::string ExternalSstFilePropertyNames::kGlobalSeqno =
    "rocksdb.external_sst_file.global_seqno";
24 25 26

#ifndef ROCKSDB_LITE

27
const size_t kFadviseTrigger = 1024 * 1024; // 1MB
28 29

struct SstFileWriter::Rep {
A
Aaron Gao 已提交
30
  Rep(const EnvOptions& _env_options, const Options& options,
31 32
      Env::IOPriority _io_priority, const Comparator* _user_comparator,
      ColumnFamilyHandle* _cfh, bool _invalidate_page_cache)
33
      : env_options(_env_options),
A
Aaron Gao 已提交
34
        ioptions(options),
Y
Yi Wu 已提交
35
        mutable_cf_options(options),
36
        io_priority(_io_priority),
37
        internal_comparator(_user_comparator),
38 39 40
        cfh(_cfh),
        invalidate_page_cache(_invalidate_page_cache),
        last_fadvise_size(0) {}
41 42 43 44 45

  std::unique_ptr<WritableFileWriter> file_writer;
  std::unique_ptr<TableBuilder> builder;
  EnvOptions env_options;
  ImmutableCFOptions ioptions;
A
Aaron Gao 已提交
46
  MutableCFOptions mutable_cf_options;
47
  Env::IOPriority io_priority;
48 49
  InternalKeyComparator internal_comparator;
  ExternalSstFileInfo file_info;
50
  InternalKey ikey;
51 52
  std::string column_family_name;
  ColumnFamilyHandle* cfh;
53
  // If true, We will give the OS a hint that this file pages is not needed
54
  // everytime we write 1MB to the file.
55
  bool invalidate_page_cache;
56
  // The size of the file during the last time we called Fadvise to remove
57 58
  // cached pages from page cache.
  uint64_t last_fadvise_size;
59 60 61
};

SstFileWriter::SstFileWriter(const EnvOptions& env_options,
A
Aaron Gao 已提交
62
                             const Options& options,
63
                             const Comparator* user_comparator,
64
                             ColumnFamilyHandle* column_family,
65 66 67 68
                             bool invalidate_page_cache,
                             Env::IOPriority io_priority)
    : rep_(new Rep(env_options, options, io_priority, user_comparator,
                   column_family, invalidate_page_cache)) {
69 70
  rep_->file_info.file_size = 0;
}
71

I
Islam AbdelRahman 已提交
72 73 74 75 76 77 78
SstFileWriter::~SstFileWriter() {
  if (rep_->builder) {
    // User did not call Finish() or Finish() failed, we need to
    // abandon the builder.
    rep_->builder->Abandon();
  }
}
79 80

Status SstFileWriter::Open(const std::string& file_path) {
81
  Rep* r = rep_.get();
82 83 84 85 86 87 88
  Status s;
  std::unique_ptr<WritableFile> sst_file;
  s = r->ioptions.env->NewWritableFile(file_path, &sst_file, r->env_options);
  if (!s.ok()) {
    return s;
  }

89 90
  sst_file->SetIOPriority(r->io_priority);

91 92 93 94
  CompressionType compression_type;
  if (r->ioptions.bottommost_compression != kDisableCompressionOption) {
    compression_type = r->ioptions.bottommost_compression;
  } else if (!r->ioptions.compression_per_level.empty()) {
95 96
    // Use the compression of the last level if we have per level compression
    compression_type = *(r->ioptions.compression_per_level.rbegin());
97 98
  } else {
    compression_type = r->mutable_cf_options.compression;
99 100 101 102
  }

  std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
      int_tbl_prop_collector_factories;
103 104

  // SstFileWriter properties collector to add SstFileWriter version.
105
  int_tbl_prop_collector_factories.emplace_back(
106 107
      new SstFileWriterPropertiesCollectorFactory(2 /* version */,
                                                  0 /* global_seqno*/));
108

109 110 111 112 113 114 115 116
  // User collector factories
  auto user_collector_factories =
      r->ioptions.table_properties_collector_factories;
  for (size_t i = 0; i < user_collector_factories.size(); i++) {
    int_tbl_prop_collector_factories.emplace_back(
        new UserKeyTablePropertiesCollectorFactory(
            user_collector_factories[i]));
  }
117
  int unknown_level = -1;
118 119 120 121 122 123 124 125 126 127 128 129
  uint32_t cf_id;

  if (r->cfh != nullptr) {
    // user explicitly specified that this file will be ingested into cfh,
    // we can persist this information in the file.
    cf_id = r->cfh->GetID();
    r->column_family_name = r->cfh->GetName();
  } else {
    r->column_family_name = "";
    cf_id = TablePropertiesCollectorFactory::Context::kUnknownColumnFamily;
  }

130 131
  TableBuilderOptions table_builder_options(
      r->ioptions, r->internal_comparator, &int_tbl_prop_collector_factories,
132 133
      compression_type, r->ioptions.compression_opts,
      nullptr /* compression_dict */, false /* skip_filters */,
134
      r->column_family_name, unknown_level);
135 136
  r->file_writer.reset(
      new WritableFileWriter(std::move(sst_file), r->env_options));
137 138 139

  // TODO(tec) : If table_factory is using compressed block cache, we will
  // be adding the external sst file blocks into it, which is wasteful.
140
  r->builder.reset(r->ioptions.table_factory->NewTableBuilder(
141
      table_builder_options, cf_id, r->file_writer.get()));
142 143 144 145 146

  r->file_info.file_path = file_path;
  r->file_info.file_size = 0;
  r->file_info.num_entries = 0;
  r->file_info.sequence_number = 0;
147
  r->file_info.version = 2;
148 149 150 151
  return s;
}

Status SstFileWriter::Add(const Slice& user_key, const Slice& value) {
152
  Rep* r = rep_.get();
153 154 155 156 157
  if (!r->builder) {
    return Status::InvalidArgument("File is not opened");
  }

  if (r->file_info.num_entries == 0) {
158
    r->file_info.smallest_key.assign(user_key.data(), user_key.size());
159 160 161 162 163 164 165 166
  } else {
    if (r->internal_comparator.user_comparator()->Compare(
            user_key, r->file_info.largest_key) <= 0) {
      // Make sure that keys are added in order
      return Status::InvalidArgument("Keys must be added in order");
    }
  }

167 168 169 170 171
  // TODO(tec) : For external SST files we could omit the seqno and type.
  r->ikey.Set(user_key, 0 /* Sequence Number */,
              ValueType::kTypeValue /* Put */);
  r->builder->Add(r->ikey.Encode(), value);

172
  // Update file info
173
  r->file_info.num_entries++;
174
  r->file_info.largest_key.assign(user_key.data(), user_key.size());
175 176
  r->file_info.file_size = r->builder->FileSize();

177
  InvalidatePageCache(false /* closing */);
178 179 180 181 182

  return Status::OK();
}

Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) {
183
  Rep* r = rep_.get();
184 185 186
  if (!r->builder) {
    return Status::InvalidArgument("File is not opened");
  }
187 188 189
  if (r->file_info.num_entries == 0) {
    return Status::InvalidArgument("Cannot create sst file with no entries");
  }
190 191

  Status s = r->builder->Finish();
192 193
  r->file_info.file_size = r->builder->FileSize();

194
  if (s.ok()) {
S
Sagar Vemuri 已提交
195
    s = r->file_writer->Sync(r->ioptions.use_fsync);
196
    InvalidatePageCache(true /* closing */);
197 198 199 200 201 202 203 204
    if (s.ok()) {
      s = r->file_writer->Close();
    }
  }
  if (!s.ok()) {
    r->ioptions.env->DeleteFile(r->file_info.file_path);
  }

205
  if (file_info != nullptr) {
206 207 208 209 210 211
    *file_info = r->file_info;
  }

  r->builder.reset();
  return s;
}
D
Ding Ma 已提交
212

213
void SstFileWriter::InvalidatePageCache(bool closing) {
214
  Rep* r = rep_.get();
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
  if (r->invalidate_page_cache == false) {
    // Fadvise disabled
    return;
  }

  uint64_t bytes_since_last_fadvise =
      r->builder->FileSize() - r->last_fadvise_size;
  if (bytes_since_last_fadvise > kFadviseTrigger || closing) {
    TEST_SYNC_POINT_CALLBACK("SstFileWriter::InvalidatePageCache",
                             &(bytes_since_last_fadvise));
    // Tell the OS that we dont need this file in page cache
    r->file_writer->InvalidateCache(0, 0);
    r->last_fadvise_size = r->builder->FileSize();
  }
}

D
Ding Ma 已提交
231 232 233
uint64_t SstFileWriter::FileSize() {
  return rep_->file_info.file_size;
}
234 235
#endif  // !ROCKSDB_LITE

236
}  // namespace rocksdb