builder.cc 10.3 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  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.
//
J
jorlow@chromium.org 已提交
6 7 8 9 10 11
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/builder.h"

12
#include <vector>
J
jorlow@chromium.org 已提交
13
#include "db/dbformat.h"
K
kailiu 已提交
14
#include "db/filename.h"
15
#include "db/merge_helper.h"
J
jorlow@chromium.org 已提交
16 17
#include "db/table_cache.h"
#include "db/version_edit.h"
18 19 20
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
S
Siying Dong 已提交
21
#include "rocksdb/options.h"
K
kailiu 已提交
22
#include "rocksdb/table.h"
S
Siying Dong 已提交
23
#include "table/block_based_table_builder.h"
24
#include "util/file_reader_writer.h"
25 26
#include "util/iostats_context_imp.h"
#include "util/thread_status_util.h"
27
#include "util/stop_watch.h"
J
jorlow@chromium.org 已提交
28

29
namespace rocksdb {
J
jorlow@chromium.org 已提交
30

S
Siying Dong 已提交
31 32
class TableFactory;

33 34 35 36 37
TableBuilder* NewTableBuilder(
    const ImmutableCFOptions& ioptions,
    const InternalKeyComparator& internal_comparator,
    const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
        int_tbl_prop_collector_factories,
38
    WritableFileWriter* file, const CompressionType compression_type,
39 40 41 42 43 44
    const CompressionOptions& compression_opts, const bool skip_filters) {
  return ioptions.table_factory->NewTableBuilder(
      TableBuilderOptions(ioptions, internal_comparator,
                          int_tbl_prop_collector_factories, compression_type,
                          compression_opts, skip_filters),
      file);
S
Siying Dong 已提交
45 46
}

47 48 49 50 51 52 53 54 55
Status BuildTable(
    const std::string& dbname, Env* env, const ImmutableCFOptions& ioptions,
    const EnvOptions& env_options, TableCache* table_cache, Iterator* iter,
    FileMetaData* meta, const InternalKeyComparator& internal_comparator,
    const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
        int_tbl_prop_collector_factories,
    const SequenceNumber newest_snapshot,
    const SequenceNumber earliest_seqno_in_memtable,
    const CompressionType compression,
56
    const CompressionOptions& compression_opts, bool paranoid_file_checks,
57
    const Env::IOPriority io_priority, TableProperties* table_properties) {
58 59
  // Reports the IOStats for flush for every following bytes.
  const size_t kReportFlushIOStatsEvery = 1048576;
J
jorlow@chromium.org 已提交
60
  Status s;
61
  meta->fd.file_size = 0;
62
  meta->smallest_seqno = meta->largest_seqno = 0;
J
jorlow@chromium.org 已提交
63 64
  iter->SeekToFirst();

65 66 67
  // If the sequence number of the smallest entry in the memtable is
  // smaller than the most recent snapshot, then we do not trigger
  // removal of duplicate/deleted keys as part of this builder.
68
  bool purge = true;
69 70 71 72
  if (earliest_seqno_in_memtable <= newest_snapshot) {
    purge = false;
  }

L
Lei Jin 已提交
73
  std::string fname = TableFileName(ioptions.db_paths, meta->fd.GetNumber(),
74
                                    meta->fd.GetPathId());
J
jorlow@chromium.org 已提交
75
  if (iter->Valid()) {
76 77 78 79 80 81 82 83 84
    TableBuilder* builder;
    unique_ptr<WritableFileWriter> file_writer;
    {
      unique_ptr<WritableFile> file;
      s = env->NewWritableFile(fname, &file, env_options);
      if (!s.ok()) {
        return s;
      }
      file->SetIOPriority(io_priority);
S
Siying Dong 已提交
85

86 87 88 89 90 91
      file_writer.reset(new WritableFileWriter(std::move(file), env_options));

      builder = NewTableBuilder(
          ioptions, internal_comparator, int_tbl_prop_collector_factories,
          file_writer.get(), compression, compression_opts);
    }
92

I
Igor Canadi 已提交
93 94 95 96 97 98 99
    {
      // the first key is the smallest key
      Slice key = iter->key();
      meta->smallest.DecodeFrom(key);
      meta->smallest_seqno = GetInternalKeySeqno(key);
      meta->largest_seqno = meta->smallest_seqno;
    }
100

101
    MergeHelper merge(internal_comparator.user_comparator(),
L
Lei Jin 已提交
102 103
                      ioptions.merge_operator, ioptions.info_log,
                      ioptions.min_partial_merge_operands,
104 105
                      true /* internal key corruption is not ok */);

106
    if (purge) {
107
      // Ugly walkaround to avoid compiler error for release build
108 109 110
      bool ok __attribute__((unused)) = true;

      // Will write to builder if current key != prev key
111 112
      ParsedInternalKey prev_ikey;
      std::string prev_key;
113
      bool is_first_key = true;    // Also write if this is the very first key
114

115 116
      while (iter->Valid()) {
        bool iterator_at_next = false;
117 118

        // Get current key
119 120
        ParsedInternalKey this_ikey;
        Slice key = iter->key();
121 122 123 124
        Slice value = iter->value();

        // In-memory key corruption is not ok;
        // TODO: find a clean way to treat in memory key corruption
125 126
        ok = ParseInternalKey(key, &this_ikey);
        assert(ok);
127 128
        assert(this_ikey.sequence >= earliest_seqno_in_memtable);

129 130 131
        // If the key is the same as the previous key (and it is not the
        // first key), then we skip it, since it is an older version.
        // Otherwise we output the key and mark it as the "new" previous key.
132 133
        if (!is_first_key && !internal_comparator.user_comparator()->Compare(
                                  prev_ikey.user_key, this_ikey.user_key)) {
134 135 136 137 138
          // seqno within the same key are in decreasing order
          assert(this_ikey.sequence < prev_ikey.sequence);
        } else {
          is_first_key = false;

139
          if (this_ikey.type == kTypeMerge) {
140 141 142 143 144 145 146
            // TODO(tbd): Add a check here to prevent RocksDB from crash when
            // reopening a DB w/o properly specifying the merge operator.  But
            // currently we observed a memory leak on failing in RocksDB
            // recovery, so we decide to let it crash instead of causing
            // memory leak for now before we have identified the real cause
            // of the memory leak.

147
            // Handle merge-type keys using the MergeHelper
148
            // TODO: pass statistics to MergeUntil
149 150
            merge.MergeUntil(iter, 0 /* don't worry about snapshot */);
            iterator_at_next = true;
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            if (merge.IsSuccess()) {
              // Merge completed correctly.
              // Add the resulting merge key/value and continue to next
              builder->Add(merge.key(), merge.value());
              prev_key.assign(merge.key().data(), merge.key().size());
              ok = ParseInternalKey(Slice(prev_key), &prev_ikey);
              assert(ok);
            } else {
              // Merge did not find a Put/Delete.
              // Can not compact these merges into a kValueType.
              // Write them out one-by-one. (Proceed back() to front())
              const std::deque<std::string>& keys = merge.keys();
              const std::deque<std::string>& values = merge.values();
              assert(keys.size() == values.size() && keys.size() >= 1);
              std::deque<std::string>::const_reverse_iterator key_iter;
              std::deque<std::string>::const_reverse_iterator value_iter;
              for (key_iter=keys.rbegin(), value_iter = values.rbegin();
                   key_iter != keys.rend() && value_iter != values.rend();
                   ++key_iter, ++value_iter) {

                builder->Add(Slice(*key_iter), Slice(*value_iter));
              }

              // Sanity check. Both iterators should end at the same time
              assert(key_iter == keys.rend() && value_iter == values.rend());

              prev_key.assign(keys.front());
              ok = ParseInternalKey(Slice(prev_key), &prev_ikey);
              assert(ok);
            }
181
          } else {
182 183
            // Handle Put/Delete-type keys by simply writing them
            builder->Add(key, value);
184 185 186 187
            prev_key.assign(key.data(), key.size());
            ok = ParseInternalKey(Slice(prev_key), &prev_ikey);
            assert(ok);
          }
188
        }
189

190 191 192 193 194 195 196
        if (io_priority == Env::IO_HIGH &&
            IOSTATS(bytes_written) >= kReportFlushIOStatsEvery) {
          ThreadStatusUtil::IncreaseThreadOperationProperty(
              ThreadStatus::FLUSH_BYTES_WRITTEN,
              IOSTATS(bytes_written));
          IOSTATS_RESET(bytes_written);
        }
197
        if (!iterator_at_next) iter->Next();
198
      }
199 200

      // The last key is the largest key
201
      meta->largest.DecodeFrom(Slice(prev_key));
202 203 204
      SequenceNumber seqno = GetInternalKeySeqno(Slice(prev_key));
      meta->smallest_seqno = std::min(meta->smallest_seqno, seqno);
      meta->largest_seqno = std::max(meta->largest_seqno, seqno);
205 206 207 208 209 210

    } else {
      for (; iter->Valid(); iter->Next()) {
        Slice key = iter->key();
        meta->largest.DecodeFrom(key);
        builder->Add(key, iter->value());
211 212 213
        SequenceNumber seqno = GetInternalKeySeqno(key);
        meta->smallest_seqno = std::min(meta->smallest_seqno, seqno);
        meta->largest_seqno = std::max(meta->largest_seqno, seqno);
214 215 216 217 218 219 220
        if (io_priority == Env::IO_HIGH &&
            IOSTATS(bytes_written) >= kReportFlushIOStatsEvery) {
          ThreadStatusUtil::IncreaseThreadOperationProperty(
              ThreadStatus::FLUSH_BYTES_WRITTEN,
              IOSTATS(bytes_written));
          IOSTATS_RESET(bytes_written);
        }
221
      }
J
jorlow@chromium.org 已提交
222 223 224 225 226 227 228 229
    }

    // Finish and check for builder errors
    if (s.ok()) {
      s = builder->Finish();
    } else {
      builder->Abandon();
    }
230 231
    if (s.ok()) {
      meta->fd.file_size = builder->FileSize();
232
      meta->marked_for_compaction = builder->NeedCompact();
233 234 235 236 237
      assert(meta->fd.GetFileSize() > 0);
      if (table_properties) {
        *table_properties = builder->GetTableProperties();
      }
    }
J
jorlow@chromium.org 已提交
238 239 240
    delete builder;

    // Finish and check for file errors
L
Lei Jin 已提交
241
    if (s.ok() && !ioptions.disable_data_sync) {
242 243
      StopWatch sw(env, ioptions.statistics, TABLE_SYNC_MICROS);
      file_writer->Sync(ioptions.use_fsync);
J
jorlow@chromium.org 已提交
244 245
    }
    if (s.ok()) {
246
      s = file_writer->Close();
J
jorlow@chromium.org 已提交
247 248 249 250
    }

    if (s.ok()) {
      // Verify that the table is usable
L
Lei Jin 已提交
251
      Iterator* it = table_cache->NewIterator(ReadOptions(), env_options,
252
                                              internal_comparator, meta->fd);
J
jorlow@chromium.org 已提交
253
      s = it->status();
254 255 256 257 258
      if (s.ok() && paranoid_file_checks) {
        for (it->SeekToFirst(); it->Valid(); it->Next()) {}
        s = it->status();
      }

J
jorlow@chromium.org 已提交
259 260 261 262 263 264 265 266 267
      delete it;
    }
  }

  // Check for input iterator errors
  if (!iter->status().ok()) {
    s = iter->status();
  }

268
  if (s.ok() && meta->fd.GetFileSize() > 0) {
269
    // Keep it
J
jorlow@chromium.org 已提交
270 271 272 273 274 275
  } else {
    env->DeleteFile(fname);
  }
  return s;
}

276
}  // namespace rocksdb