sst_file_writer.cc 12.3 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5 6 7 8

#include "rocksdb/sst_file_writer.h"

#include <vector>
9

10
#include "db/dbformat.h"
11
#include "file/writable_file_writer.h"
12
#include "rocksdb/file_system.h"
13
#include "rocksdb/table.h"
14
#include "table/block_based/block_based_table_builder.h"
15
#include "table/sst_file_writer_collectors.h"
16
#include "test_util/sync_point.h"
17

18
namespace ROCKSDB_NAMESPACE {
19 20 21

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
      Env::IOPriority _io_priority, const Comparator* _user_comparator,
32
      ColumnFamilyHandle* _cfh, bool _invalidate_page_cache, bool _skip_filters)
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
        cfh(_cfh),
        invalidate_page_cache(_invalidate_page_cache),
40 41
        last_fadvise_size(0),
        skip_filters(_skip_filters) {}
42 43 44 45 46

  std::unique_ptr<WritableFileWriter> file_writer;
  std::unique_ptr<TableBuilder> builder;
  EnvOptions env_options;
  ImmutableCFOptions ioptions;
A
Aaron Gao 已提交
47
  MutableCFOptions mutable_cf_options;
48
  Env::IOPriority io_priority;
49 50
  InternalKeyComparator internal_comparator;
  ExternalSstFileInfo file_info;
51
  InternalKey ikey;
52 53
  std::string column_family_name;
  ColumnFamilyHandle* cfh;
54
  // If true, We will give the OS a hint that this file pages is not needed
55
  // every time we write 1MB to the file.
56
  bool invalidate_page_cache;
57
  // The size of the file during the last time we called Fadvise to remove
58 59
  // cached pages from page cache.
  uint64_t last_fadvise_size;
60
  bool skip_filters;
61 62 63 64 65 66 67 68 69 70 71 72
  Status Add(const Slice& user_key, const Slice& value,
             const ValueType value_type) {
    if (!builder) {
      return Status::InvalidArgument("File is not opened");
    }

    if (file_info.num_entries == 0) {
      file_info.smallest_key.assign(user_key.data(), user_key.size());
    } else {
      if (internal_comparator.user_comparator()->Compare(
              user_key, file_info.largest_key) <= 0) {
        // Make sure that keys are added in order
73 74
        return Status::InvalidArgument(
            "Keys must be added in strict ascending order.");
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      }
    }

    // TODO(tec) : For external SST files we could omit the seqno and type.
    switch (value_type) {
      case ValueType::kTypeValue:
        ikey.Set(user_key, 0 /* Sequence Number */,
                 ValueType::kTypeValue /* Put */);
        break;
      case ValueType::kTypeMerge:
        ikey.Set(user_key, 0 /* Sequence Number */,
                 ValueType::kTypeMerge /* Merge */);
        break;
      case ValueType::kTypeDeletion:
        ikey.Set(user_key, 0 /* Sequence Number */,
                 ValueType::kTypeDeletion /* Delete */);
        break;
      default:
        return Status::InvalidArgument("Value type is not supported");
    }
    builder->Add(ikey.Encode(), value);

    // update file info
    file_info.num_entries++;
    file_info.largest_key.assign(user_key.data(), user_key.size());
    file_info.file_size = builder->FileSize();

102 103
    InvalidatePageCache(false /* closing */).PermitUncheckedError();
    return Status::OK();
104 105
  }

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  Status DeleteRange(const Slice& begin_key, const Slice& end_key) {
    if (!builder) {
      return Status::InvalidArgument("File is not opened");
    }

    RangeTombstone tombstone(begin_key, end_key, 0 /* Sequence Number */);
    if (file_info.num_range_del_entries == 0) {
      file_info.smallest_range_del_key.assign(tombstone.start_key_.data(),
                                              tombstone.start_key_.size());
      file_info.largest_range_del_key.assign(tombstone.end_key_.data(),
                                             tombstone.end_key_.size());
    } else {
      if (internal_comparator.user_comparator()->Compare(
              tombstone.start_key_, file_info.smallest_range_del_key) < 0) {
        file_info.smallest_range_del_key.assign(tombstone.start_key_.data(),
                                                tombstone.start_key_.size());
      }
      if (internal_comparator.user_comparator()->Compare(
              tombstone.end_key_, file_info.largest_range_del_key) > 0) {
        file_info.largest_range_del_key.assign(tombstone.end_key_.data(),
                                               tombstone.end_key_.size());
      }
    }

    auto ikey_and_end_key = tombstone.Serialize();
    builder->Add(ikey_and_end_key.first.Encode(), ikey_and_end_key.second);

    // update file info
    file_info.num_range_del_entries++;
    file_info.file_size = builder->FileSize();

137 138
    InvalidatePageCache(false /* closing */).PermitUncheckedError();
    return Status::OK();
139 140
  }

141 142
  Status InvalidatePageCache(bool closing) {
    Status s = Status::OK();
143 144
    if (invalidate_page_cache == false) {
      // Fadvise disabled
145
      return s;
146 147 148 149 150 151
    }
    uint64_t bytes_since_last_fadvise =
      builder->FileSize() - last_fadvise_size;
    if (bytes_since_last_fadvise > kFadviseTrigger || closing) {
      TEST_SYNC_POINT_CALLBACK("SstFileWriter::Rep::InvalidatePageCache",
                               &(bytes_since_last_fadvise));
152
      // Tell the OS that we don't need this file in page cache
153 154 155 156 157 158
      s = file_writer->InvalidateCache(0, 0);
      if (s.IsNotSupported()) {
        // NotSupported is fine as it could be a file type that doesn't use page
        // cache.
        s = Status::OK();
      }
159 160
      last_fadvise_size = builder->FileSize();
    }
161
    return s;
162
  }
163 164 165
};

SstFileWriter::SstFileWriter(const EnvOptions& env_options,
A
Aaron Gao 已提交
166
                             const Options& options,
167
                             const Comparator* user_comparator,
168
                             ColumnFamilyHandle* column_family,
169
                             bool invalidate_page_cache,
170
                             Env::IOPriority io_priority, bool skip_filters)
171
    : rep_(new Rep(env_options, options, io_priority, user_comparator,
172
                   column_family, invalidate_page_cache, skip_filters)) {
173 174
  rep_->file_info.file_size = 0;
}
175

I
Islam AbdelRahman 已提交
176 177 178 179 180 181 182
SstFileWriter::~SstFileWriter() {
  if (rep_->builder) {
    // User did not call Finish() or Finish() failed, we need to
    // abandon the builder.
    rep_->builder->Abandon();
  }
}
183 184

Status SstFileWriter::Open(const std::string& file_path) {
185
  Rep* r = rep_.get();
186
  Status s;
187
  std::unique_ptr<FSWritableFile> sst_file;
188
  FileOptions cur_file_opts(r->env_options);
189
  s = r->ioptions.env->GetFileSystem()->NewWritableFile(
190
      file_path, cur_file_opts, &sst_file, nullptr);
191 192 193 194
  if (!s.ok()) {
    return s;
  }

195 196
  sst_file->SetIOPriority(r->io_priority);

197
  CompressionType compression_type;
198
  CompressionOptions compression_opts;
199 200 201 202 203
  if (r->mutable_cf_options.bottommost_compression !=
      kDisableCompressionOption) {
    compression_type = r->mutable_cf_options.bottommost_compression;
    if (r->mutable_cf_options.bottommost_compression_opts.enabled) {
      compression_opts = r->mutable_cf_options.bottommost_compression_opts;
204
    } else {
205
      compression_opts = r->mutable_cf_options.compression_opts;
206
    }
207
  } else if (!r->ioptions.compression_per_level.empty()) {
208 209
    // Use the compression of the last level if we have per level compression
    compression_type = *(r->ioptions.compression_per_level.rbegin());
210
    compression_opts = r->mutable_cf_options.compression_opts;
211 212
  } else {
    compression_type = r->mutable_cf_options.compression;
213
    compression_opts = r->mutable_cf_options.compression_opts;
214 215 216 217
  }

  std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
      int_tbl_prop_collector_factories;
218 219

  // SstFileWriter properties collector to add SstFileWriter version.
220
  int_tbl_prop_collector_factories.emplace_back(
221 222
      new SstFileWriterPropertiesCollectorFactory(2 /* version */,
                                                  0 /* global_seqno*/));
223

224 225 226 227 228 229 230 231
  // 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]));
  }
232
  int unknown_level = -1;
233 234 235 236 237 238 239 240 241 242 243
  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;
  }
244 245 246 247 248 249 250 251 252
  // SstFileWriter is used to create sst files that can be added to database
  // later. Therefore, no real db_id and db_session_id are associated with it.
  // Here we mimic the way db_session_id behaves by resetting the db_session_id
  // every time SstFileWriter is used, and in this case db_id is set to be "SST
  // Writer".
  std::string db_session_id = r->ioptions.env->GenerateUniqueId();
  if (!db_session_id.empty() && db_session_id.back() == '\n') {
    db_session_id.pop_back();
  }
253
  TableBuilderOptions table_builder_options(
254
      r->ioptions, r->mutable_cf_options, r->internal_comparator,
255 256 257
      &int_tbl_prop_collector_factories, compression_type, compression_opts,
      r->skip_filters, r->column_family_name, unknown_level,
      0 /* creation_time */, 0 /* oldest_key_time */, 0 /* target_file_size */,
258
      0 /* file_creation_time */, "SST Writer" /* db_id */, db_session_id);
259
  FileTypeSet tmp_set = r->ioptions.checksum_handoff_file_types;
260
  r->file_writer.reset(new WritableFileWriter(
261 262
      std::move(sst_file), file_path, r->env_options, r->ioptions.clock,
      nullptr /* io_tracer */, nullptr /* stats */, r->ioptions.listeners,
263 264
      r->ioptions.file_checksum_gen_factory,
      tmp_set.Contains(FileType::kTableFile)));
265 266 267

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

271
  r->file_info = ExternalSstFileInfo();
272
  r->file_info.file_path = file_path;
273
  r->file_info.version = 2;
274 275 276 277
  return s;
}

Status SstFileWriter::Add(const Slice& user_key, const Slice& value) {
278 279
  return rep_->Add(user_key, value, ValueType::kTypeValue);
}
280

281 282 283
Status SstFileWriter::Put(const Slice& user_key, const Slice& value) {
  return rep_->Add(user_key, value, ValueType::kTypeValue);
}
284

285 286 287
Status SstFileWriter::Merge(const Slice& user_key, const Slice& value) {
  return rep_->Add(user_key, value, ValueType::kTypeMerge);
}
288

289 290
Status SstFileWriter::Delete(const Slice& user_key) {
  return rep_->Add(user_key, Slice(), ValueType::kTypeDeletion);
291 292
}

293 294 295 296 297
Status SstFileWriter::DeleteRange(const Slice& begin_key,
                                  const Slice& end_key) {
  return rep_->DeleteRange(begin_key, end_key);
}

298
Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) {
299
  Rep* r = rep_.get();
300 301 302
  if (!r->builder) {
    return Status::InvalidArgument("File is not opened");
  }
303 304
  if (r->file_info.num_entries == 0 &&
      r->file_info.num_range_del_entries == 0) {
305 306
    return Status::InvalidArgument("Cannot create sst file with no entries");
  }
307 308

  Status s = r->builder->Finish();
309 310
  r->file_info.file_size = r->builder->FileSize();

311
  if (s.ok()) {
S
Sagar Vemuri 已提交
312
    s = r->file_writer->Sync(r->ioptions.use_fsync);
313
    r->InvalidatePageCache(true /* closing */).PermitUncheckedError();
314 315 316 317
    if (s.ok()) {
      s = r->file_writer->Close();
    }
  }
318 319 320 321 322
  if (s.ok()) {
    r->file_info.file_checksum = r->file_writer->GetFileChecksum();
    r->file_info.file_checksum_func_name =
        r->file_writer->GetFileChecksumFuncName();
  }
323 324 325 326
  if (!s.ok()) {
    r->ioptions.env->DeleteFile(r->file_info.file_path);
  }

327
  if (file_info != nullptr) {
328 329 330 331 332 333
    *file_info = r->file_info;
  }

  r->builder.reset();
  return s;
}
D
Ding Ma 已提交
334 335 336 337

uint64_t SstFileWriter::FileSize() {
  return rep_->file_info.file_size;
}
338 339
#endif  // !ROCKSDB_LITE

340
}  // namespace ROCKSDB_NAMESPACE