sst_file_writer.cc 10.9 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 11
#include "db/dbformat.h"
#include "rocksdb/table.h"
12
#include "table/block_based/block_based_table_builder.h"
13
#include "table/sst_file_writer_collectors.h"
14
#include "test_util/sync_point.h"
15
#include "util/file_reader_writer.h"
16 17 18 19 20

namespace rocksdb {

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

#ifndef ROCKSDB_LITE

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

struct SstFileWriter::Rep {
A
Aaron Gao 已提交
29
  Rep(const EnvOptions& _env_options, const Options& options,
30
      Env::IOPriority _io_priority, const Comparator* _user_comparator,
31
      ColumnFamilyHandle* _cfh, bool _invalidate_page_cache, bool _skip_filters)
32
      : env_options(_env_options),
A
Aaron Gao 已提交
33
        ioptions(options),
Y
Yi Wu 已提交
34
        mutable_cf_options(options),
35
        io_priority(_io_priority),
36
        internal_comparator(_user_comparator),
37 38
        cfh(_cfh),
        invalidate_page_cache(_invalidate_page_cache),
39 40
        last_fadvise_size(0),
        skip_filters(_skip_filters) {}
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
  // every time 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
  bool skip_filters;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 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 102 103 104
  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
        return Status::InvalidArgument("Keys must be added in order");
      }
    }

    // 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();

    InvalidatePageCache(false /* closing */);

    return Status::OK();
  }

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 137 138 139 140
  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();

    InvalidatePageCache(false /* closing */);

    return Status::OK();
  }

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  void InvalidatePageCache(bool closing) {
    if (invalidate_page_cache == false) {
      // Fadvise disabled
      return;
    }
    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));
      // Tell the OS that we dont need this file in page cache
      file_writer->InvalidateCache(0, 0);
      last_fadvise_size = builder->FileSize();
    }
  }

157 158 159
};

SstFileWriter::SstFileWriter(const EnvOptions& env_options,
A
Aaron Gao 已提交
160
                             const Options& options,
161
                             const Comparator* user_comparator,
162
                             ColumnFamilyHandle* column_family,
163
                             bool invalidate_page_cache,
164
                             Env::IOPriority io_priority, bool skip_filters)
165
    : rep_(new Rep(env_options, options, io_priority, user_comparator,
166
                   column_family, invalidate_page_cache, skip_filters)) {
167 168
  rep_->file_info.file_size = 0;
}
169

I
Islam AbdelRahman 已提交
170 171 172 173 174 175 176
SstFileWriter::~SstFileWriter() {
  if (rep_->builder) {
    // User did not call Finish() or Finish() failed, we need to
    // abandon the builder.
    rep_->builder->Abandon();
  }
}
177 178

Status SstFileWriter::Open(const std::string& file_path) {
179
  Rep* r = rep_.get();
180 181 182 183 184 185 186
  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;
  }

187 188
  sst_file->SetIOPriority(r->io_priority);

189
  CompressionType compression_type;
190
  CompressionOptions compression_opts;
191 192
  if (r->ioptions.bottommost_compression != kDisableCompressionOption) {
    compression_type = r->ioptions.bottommost_compression;
193 194 195 196 197
    if (r->ioptions.bottommost_compression_opts.enabled) {
      compression_opts = r->ioptions.bottommost_compression_opts;
    } else {
      compression_opts = r->ioptions.compression_opts;
    }
198
  } else if (!r->ioptions.compression_per_level.empty()) {
199 200
    // Use the compression of the last level if we have per level compression
    compression_type = *(r->ioptions.compression_per_level.rbegin());
201
    compression_opts = r->ioptions.compression_opts;
202 203
  } else {
    compression_type = r->mutable_cf_options.compression;
204
    compression_opts = r->ioptions.compression_opts;
205
  }
206 207
  uint64_t sample_for_compression =
      r->mutable_cf_options.sample_for_compression;
208 209 210

  std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
      int_tbl_prop_collector_factories;
211 212

  // SstFileWriter properties collector to add SstFileWriter version.
213
  int_tbl_prop_collector_factories.emplace_back(
214 215
      new SstFileWriterPropertiesCollectorFactory(2 /* version */,
                                                  0 /* global_seqno*/));
216

217 218 219 220 221 222 223 224
  // 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]));
  }
225
  int unknown_level = -1;
226 227 228 229 230 231 232 233 234 235 236 237
  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;
  }

238
  TableBuilderOptions table_builder_options(
239
      r->ioptions, r->mutable_cf_options, r->internal_comparator,
240 241 242
      &int_tbl_prop_collector_factories, compression_type,
      sample_for_compression, compression_opts, r->skip_filters,
      r->column_family_name, unknown_level);
243 244 245
  r->file_writer.reset(new WritableFileWriter(
      std::move(sst_file), file_path, r->env_options, r->ioptions.env,
      nullptr /* stats */, r->ioptions.listeners));
246 247 248

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

252
  r->file_info = ExternalSstFileInfo();
253
  r->file_info.file_path = file_path;
254
  r->file_info.version = 2;
255 256 257 258
  return s;
}

Status SstFileWriter::Add(const Slice& user_key, const Slice& value) {
259 260
  return rep_->Add(user_key, value, ValueType::kTypeValue);
}
261

262 263 264
Status SstFileWriter::Put(const Slice& user_key, const Slice& value) {
  return rep_->Add(user_key, value, ValueType::kTypeValue);
}
265

266 267 268
Status SstFileWriter::Merge(const Slice& user_key, const Slice& value) {
  return rep_->Add(user_key, value, ValueType::kTypeMerge);
}
269

270 271
Status SstFileWriter::Delete(const Slice& user_key) {
  return rep_->Add(user_key, Slice(), ValueType::kTypeDeletion);
272 273
}

274 275 276 277 278
Status SstFileWriter::DeleteRange(const Slice& begin_key,
                                  const Slice& end_key) {
  return rep_->DeleteRange(begin_key, end_key);
}

279
Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) {
280
  Rep* r = rep_.get();
281 282 283
  if (!r->builder) {
    return Status::InvalidArgument("File is not opened");
  }
284 285
  if (r->file_info.num_entries == 0 &&
      r->file_info.num_range_del_entries == 0) {
286 287
    return Status::InvalidArgument("Cannot create sst file with no entries");
  }
288 289

  Status s = r->builder->Finish();
290 291
  r->file_info.file_size = r->builder->FileSize();

292
  if (s.ok()) {
S
Sagar Vemuri 已提交
293
    s = r->file_writer->Sync(r->ioptions.use_fsync);
294
    r->InvalidatePageCache(true /* closing */);
295 296 297 298 299 300 301 302
    if (s.ok()) {
      s = r->file_writer->Close();
    }
  }
  if (!s.ok()) {
    r->ioptions.env->DeleteFile(r->file_info.file_path);
  }

303
  if (file_info != nullptr) {
304 305 306 307 308 309
    *file_info = r->file_info;
  }

  r->builder.reset();
  return s;
}
D
Ding Ma 已提交
310 311 312 313

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

316
}  // namespace rocksdb