builder.cc 13.7 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
//
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"

I
Igor Canadi 已提交
12
#include <algorithm>
13
#include <deque>
14
#include <vector>
15

16
#include "db/blob/blob_file_builder.h"
17
#include "db/compaction/compaction_iterator.h"
J
jorlow@chromium.org 已提交
18
#include "db/dbformat.h"
19
#include "db/event_helpers.h"
20
#include "db/internal_stats.h"
21
#include "db/merge_helper.h"
22
#include "db/range_del_aggregator.h"
J
jorlow@chromium.org 已提交
23 24
#include "db/table_cache.h"
#include "db/version_edit.h"
25
#include "file/filename.h"
26 27
#include "file/read_write_util.h"
#include "file/writable_file_writer.h"
28 29
#include "monitoring/iostats_context_imp.h"
#include "monitoring/thread_status_util.h"
30 31 32
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
S
Siying Dong 已提交
33
#include "rocksdb/options.h"
K
kailiu 已提交
34
#include "rocksdb/table.h"
35
#include "table/block_based/block_based_table_builder.h"
36
#include "table/format.h"
S
sdong 已提交
37
#include "table/internal_iterator.h"
38
#include "test_util/sync_point.h"
39
#include "util/stop_watch.h"
J
jorlow@chromium.org 已提交
40

41
namespace ROCKSDB_NAMESPACE {
J
jorlow@chromium.org 已提交
42

S
Siying Dong 已提交
43 44
class TableFactory;

45
TableBuilder* NewTableBuilder(
46
    const ImmutableCFOptions& ioptions, const MutableCFOptions& moptions,
47 48 49
    const InternalKeyComparator& internal_comparator,
    const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
        int_tbl_prop_collector_factories,
50 51
    uint32_t column_family_id, const std::string& column_family_name,
    WritableFileWriter* file, const CompressionType compression_type,
52 53
    uint64_t sample_for_compression, const CompressionOptions& compression_opts,
    int level, const bool skip_filters, const uint64_t creation_time,
S
Sagar Vemuri 已提交
54
    const uint64_t oldest_key_time, const uint64_t target_file_size,
55 56
    const uint64_t file_creation_time, const std::string& db_id,
    const std::string& db_session_id) {
57 58 59
  assert((column_family_id ==
          TablePropertiesCollectorFactory::Context::kUnknownColumnFamily) ==
         column_family_name.empty());
60
  return ioptions.table_factory->NewTableBuilder(
61 62
      TableBuilderOptions(ioptions, moptions, internal_comparator,
                          int_tbl_prop_collector_factories, compression_type,
63 64
                          sample_for_compression, compression_opts,
                          skip_filters, column_family_name, level,
S
Sagar Vemuri 已提交
65
                          creation_time, oldest_key_time, target_file_size,
66
                          file_creation_time, db_id, db_session_id),
67
      column_family_id, file);
S
Siying Dong 已提交
68 69
}

70
Status BuildTable(
71
    const std::string& dbname, VersionSet* versions, Env* env, FileSystem* fs,
72 73
    const ImmutableCFOptions& ioptions,
    const MutableCFOptions& mutable_cf_options, const FileOptions& file_options,
74
    TableCache* table_cache, InternalIterator* iter,
75 76
    std::vector<std::unique_ptr<FragmentedRangeTombstoneIterator>>
        range_del_iters,
77 78
    FileMetaData* meta, std::vector<BlobFileAddition>* blob_file_additions,
    const InternalKeyComparator& internal_comparator,
79 80
    const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
        int_tbl_prop_collector_factories,
81 82
    uint32_t column_family_id, const std::string& column_family_name,
    std::vector<SequenceNumber> snapshots,
83
    SequenceNumber earliest_write_conflict_snapshot,
Y
Yi Wu 已提交
84
    SnapshotChecker* snapshot_checker, const CompressionType compression,
85 86
    uint64_t sample_for_compression, const CompressionOptions& compression_opts,
    bool paranoid_file_checks, InternalStats* internal_stats,
87
    TableFileCreationReason reason, IOStatus* io_status,
88 89
    const std::shared_ptr<IOTracer>& io_tracer, EventLogger* event_logger,
    int job_id, const Env::IOPriority io_priority,
90 91
    TableProperties* table_properties, int level, const uint64_t creation_time,
    const uint64_t oldest_key_time, Env::WriteLifeTimeHint write_hint,
92 93
    const uint64_t file_creation_time, const std::string& db_id,
    const std::string& db_session_id) {
94 95 96
  assert((column_family_id ==
          TablePropertiesCollectorFactory::Context::kUnknownColumnFamily) ==
         column_family_name.empty());
97 98
  // Reports the IOStats for flush for every following bytes.
  const size_t kReportFlushIOStatsEvery = 1048576;
99
  uint64_t paranoid_hash = 0;
J
jorlow@chromium.org 已提交
100
  Status s;
101
  meta->fd.file_size = 0;
J
jorlow@chromium.org 已提交
102
  iter->SeekToFirst();
103 104
  std::unique_ptr<CompactionRangeDelAggregator> range_del_agg(
      new CompactionRangeDelAggregator(&internal_comparator, snapshots));
105 106
  for (auto& range_del_iter : range_del_iters) {
    range_del_agg->AddTombstones(std::move(range_del_iter));
A
Andrew Kryczka 已提交
107
  }
J
jorlow@chromium.org 已提交
108

109
  std::string fname = TableFileName(ioptions.cf_paths, meta->fd.GetNumber(),
110
                                    meta->fd.GetPathId());
111
  std::vector<std::string> blob_file_paths;
112 113
  std::string file_checksum = kUnknownFileChecksum;
  std::string file_checksum_func_name = kUnknownFileChecksumFuncName;
114 115 116 117 118
#ifndef ROCKSDB_LITE
  EventHelpers::NotifyTableFileCreationStarted(
      ioptions.listeners, dbname, column_family_name, fname, job_id, reason);
#endif  // !ROCKSDB_LITE
  TableProperties tp;
119
  if (iter->Valid() || !range_del_agg->IsEmpty()) {
120
    TableBuilder* builder;
121
    std::unique_ptr<WritableFileWriter> file_writer;
122 123 124 125 126
    // Currently we only enable dictionary compression during compaction to the
    // bottommost level.
    CompressionOptions compression_opts_for_flush(compression_opts);
    compression_opts_for_flush.max_dict_bytes = 0;
    compression_opts_for_flush.zstd_max_train_bytes = 0;
127
    {
128
      std::unique_ptr<FSWritableFile> file;
129
#ifndef NDEBUG
130
      bool use_direct_writes = file_options.use_direct_writes;
131 132
      TEST_SYNC_POINT_CALLBACK("BuildTable:create_file", &use_direct_writes);
#endif  // !NDEBUG
133
      IOStatus io_s = NewWritableFile(fs, fname, &file, file_options);
134 135 136 137
      s = io_s;
      if (io_status->ok()) {
        *io_status = io_s;
      }
138
      if (!s.ok()) {
139 140
        EventHelpers::LogAndNotifyTableFileCreationFinished(
            event_logger, ioptions.listeners, dbname, column_family_name, fname,
141 142
            job_id, meta->fd, kInvalidBlobFileNumber, tp, reason, s,
            file_checksum, file_checksum_func_name);
143 144 145
        return s;
      }
      file->SetIOPriority(io_priority);
S
Stream  
Shaohua Li 已提交
146
      file->SetWriteLifeTimeHint(write_hint);
S
Siying Dong 已提交
147

148
      file_writer.reset(new WritableFileWriter(
149 150 151
          std::move(file), fname, file_options, env, io_tracer,
          ioptions.statistics, ioptions.listeners,
          ioptions.file_checksum_gen_factory));
152

153
      builder = NewTableBuilder(
154 155
          ioptions, mutable_cf_options, internal_comparator,
          int_tbl_prop_collector_factories, column_family_id,
156
          column_family_name, file_writer.get(), compression,
157
          sample_for_compression, compression_opts_for_flush, level,
S
Sagar Vemuri 已提交
158
          false /* skip_filters */, creation_time, oldest_key_time,
159
          0 /*target_file_size*/, file_creation_time, db_id, db_session_id);
160
    }
161

I
Igor Canadi 已提交
162 163 164
    MergeHelper merge(env, internal_comparator.user_comparator(),
                      ioptions.merge_operator, nullptr, ioptions.info_log,
                      true /* internal key corruption is not ok */,
165 166
                      snapshots.empty() ? 0 : snapshots.back(),
                      snapshot_checker);
167

168 169 170 171 172 173 174 175 176
    std::unique_ptr<BlobFileBuilder> blob_file_builder(
        (mutable_cf_options.enable_blob_files && blob_file_additions)
            ? new BlobFileBuilder(versions, env, fs, &ioptions,
                                  &mutable_cf_options, &file_options, job_id,
                                  column_family_id, column_family_name,
                                  io_priority, write_hint, &blob_file_paths,
                                  blob_file_additions)
            : nullptr);

177 178
    CompactionIterator c_iter(
        iter, internal_comparator.user_comparator(), &merge, kMaxSequenceNumber,
Y
Yi Wu 已提交
179
        &snapshots, earliest_write_conflict_snapshot, snapshot_checker, env,
180
        ShouldReportDetailedTime(env, ioptions.statistics),
181 182 183
        true /* internal key corruption is not ok */, range_del_agg.get(),
        blob_file_builder.get());

184 185 186 187
    c_iter.SeekToFirst();
    for (; c_iter.Valid(); c_iter.Next()) {
      const Slice& key = c_iter.key();
      const Slice& value = c_iter.value();
188
      const ParsedInternalKey& ikey = c_iter.ikey();
189 190 191 192 193
      if (paranoid_file_checks) {
        // Generate a rolling 64-bit hash of the key and values
        paranoid_hash = Hash64(key.data(), key.size(), paranoid_hash);
        paranoid_hash = Hash64(value.data(), value.size(), paranoid_hash);
      }
194
      builder->Add(key, value);
195
      meta->UpdateBoundaries(key, value, ikey.sequence, ikey.type);
196 197

      // TODO(noetzli): Update stats after flush, too.
I
Igor Canadi 已提交
198 199
      if (io_priority == Env::IO_HIGH &&
          IOSTATS(bytes_written) >= kReportFlushIOStatsEvery) {
200
        ThreadStatusUtil::SetThreadOperationProperty(
I
Igor Canadi 已提交
201
            ThreadStatus::FLUSH_BYTES_WRITTEN, IOSTATS(bytes_written));
202
      }
J
jorlow@chromium.org 已提交
203
    }
204

205 206 207 208
    auto range_del_it = range_del_agg->NewIterator();
    for (range_del_it->SeekToFirst(); range_del_it->Valid();
         range_del_it->Next()) {
      auto tombstone = range_del_it->Tombstone();
209 210 211 212 213
      auto kv = tombstone.Serialize();
      builder->Add(kv.first.Encode(), kv.second);
      meta->UpdateBoundariesForRange(kv.first, tombstone.SerializeEndKey(),
                                     tombstone.seq_, internal_comparator);
    }
J
jorlow@chromium.org 已提交
214 215

    // Finish and check for builder errors
216
    s = c_iter.status();
217 218 219 220 221 222 223

    if (blob_file_builder) {
      if (s.ok()) {
        s = blob_file_builder->Finish();
      }
    }

224
    TEST_SYNC_POINT("BuildTable:BeforeFinishBuildTable");
225
    const bool empty = builder->IsEmpty();
A
Andres Noetzli 已提交
226
    if (!s.ok() || empty) {
J
jorlow@chromium.org 已提交
227
      builder->Abandon();
A
Andres Noetzli 已提交
228 229
    } else {
      s = builder->Finish();
J
jorlow@chromium.org 已提交
230
    }
231
    if (io_status->ok()) {
232
      *io_status = builder->io_status();
233
    }
A
Andres Noetzli 已提交
234 235

    if (s.ok() && !empty) {
236 237
      uint64_t file_size = builder->FileSize();
      meta->fd.file_size = file_size;
238
      meta->marked_for_compaction = builder->NeedCompact();
239
      assert(meta->fd.GetFileSize() > 0);
240
      tp = builder->GetTableProperties(); // refresh now that builder is finished
241
      if (table_properties) {
242
        *table_properties = tp;
243 244
      }
    }
J
jorlow@chromium.org 已提交
245 246 247
    delete builder;

    // Finish and check for file errors
Z
Zhichao Cao 已提交
248
    TEST_SYNC_POINT("BuildTable:BeforeSyncTable");
S
Sagar Vemuri 已提交
249
    if (s.ok() && !empty) {
250
      StopWatch sw(env, ioptions.statistics, TABLE_SYNC_MICROS);
251
      *io_status = file_writer->Sync(ioptions.use_fsync);
J
jorlow@chromium.org 已提交
252
    }
Z
Zhichao Cao 已提交
253
    TEST_SYNC_POINT("BuildTable:BeforeCloseTableFile");
254
    if (s.ok() && io_status->ok() && !empty) {
255
      *io_status = file_writer->Close();
J
jorlow@chromium.org 已提交
256
    }
257
    if (s.ok() && io_status->ok() && !empty) {
258 259 260
      // Add the checksum information to file metadata.
      meta->file_checksum = file_writer->GetFileChecksum();
      meta->file_checksum_func_name = file_writer->GetFileChecksumFuncName();
261 262
      file_checksum = meta->file_checksum;
      file_checksum_func_name = meta->file_checksum_func_name;
263 264
    }

265
    if (s.ok()) {
266 267 268 269
      s = *io_status;
    }

    // TODO Also check the IO status when create the Iterator.
J
jorlow@chromium.org 已提交
270

A
Andres Noetzli 已提交
271
    if (s.ok() && !empty) {
J
jorlow@chromium.org 已提交
272
      // Verify that the table is usable
273 274 275 276 277
      // We set for_compaction to false and don't OptimizeForCompactionTableRead
      // here because this is a special case after we finish the table building
      // No matter whether use_direct_io_for_flush_and_compaction is true,
      // we will regrad this verification as user reads since the goal is
      // to cache it here for further user reads
278
      ReadOptions read_options;
S
sdong 已提交
279
      std::unique_ptr<InternalIterator> it(table_cache->NewIterator(
280
          read_options, file_options, internal_comparator, *meta,
281 282
          nullptr /* range_del_agg */,
          mutable_cf_options.prefix_extractor.get(), nullptr,
283 284
          (internal_stats == nullptr) ? nullptr
                                      : internal_stats->GetFileReadHist(0),
285
          TableReaderCaller::kFlush, /*arena=*/nullptr,
286 287 288
          /*skip_filter=*/false, level,
          MaxFileSizeForL0MetaPin(mutable_cf_options),
          /*smallest_compaction_key=*/nullptr,
289 290
          /*largest_compaction_key*/ nullptr,
          /*allow_unprepared_value*/ false));
J
jorlow@chromium.org 已提交
291
      s = it->status();
292
      if (s.ok() && paranoid_file_checks) {
293
        uint64_t check_hash = 0;
A
Andres Noetzli 已提交
294
        for (it->SeekToFirst(); it->Valid(); it->Next()) {
295 296 297 298
          // Generate a rolling 64-bit hash of the key and values
          check_hash = Hash64(it->key().data(), it->key().size(), check_hash);
          check_hash =
              Hash64(it->value().data(), it->value().size(), check_hash);
A
Andres Noetzli 已提交
299
        }
300
        s = it->status();
301
        if (s.ok() && check_hash != paranoid_hash) {
302
          s = Status::Corruption("Paranoid checksums do not match");
303
        }
304
      }
J
jorlow@chromium.org 已提交
305 306 307 308 309 310 311 312
    }
  }

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

A
Andres Noetzli 已提交
313
  if (!s.ok() || meta->fd.GetFileSize() == 0) {
314 315
    constexpr IODebugContext* dbg = nullptr;

316
    Status ignored = fs->DeleteFile(fname, IOOptions(), dbg);
317 318 319 320 321

    assert(blob_file_additions || blob_file_paths.empty());

    if (blob_file_additions) {
      for (const std::string& blob_file_path : blob_file_paths) {
322
        ignored = fs->DeleteFile(blob_file_path, IOOptions(), dbg);
323 324 325 326
      }

      blob_file_additions->clear();
    }
327
    ignored.PermitUncheckedError();
J
jorlow@chromium.org 已提交
328
  }
329

330 331 332
  if (meta->fd.GetFileSize() == 0) {
    fname = "(nil)";
  }
333
  // Output to event logger and fire events.
334 335
  EventHelpers::LogAndNotifyTableFileCreationFinished(
      event_logger, ioptions.listeners, dbname, column_family_name, fname,
336 337
      job_id, meta->fd, meta->oldest_blob_file_number, tp, reason, s,
      file_checksum, file_checksum_func_name);
338

J
jorlow@chromium.org 已提交
339 340 341
  return s;
}

342
}  // namespace ROCKSDB_NAMESPACE