builder.cc 14.0 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/output_validator.h"
23
#include "db/range_del_aggregator.h"
J
jorlow@chromium.org 已提交
24 25
#include "db/table_cache.h"
#include "db/version_edit.h"
26
#include "file/filename.h"
27 28
#include "file/read_write_util.h"
#include "file/writable_file_writer.h"
29 30
#include "monitoring/iostats_context_imp.h"
#include "monitoring/thread_status_util.h"
31 32 33
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
S
Siying Dong 已提交
34
#include "rocksdb/options.h"
K
kailiu 已提交
35
#include "rocksdb/table.h"
36
#include "table/block_based/block_based_table_builder.h"
37
#include "table/format.h"
S
sdong 已提交
38
#include "table/internal_iterator.h"
39
#include "test_util/sync_point.h"
40
#include "util/stop_watch.h"
J
jorlow@chromium.org 已提交
41

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

S
Siying Dong 已提交
44 45
class TableFactory;

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

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

114
  std::string fname = TableFileName(ioptions.cf_paths, meta->fd.GetNumber(),
115
                                    meta->fd.GetPathId());
116
  std::vector<std::string> blob_file_paths;
117 118
  std::string file_checksum = kUnknownFileChecksum;
  std::string file_checksum_func_name = kUnknownFileChecksumFuncName;
119 120 121 122 123
#ifndef ROCKSDB_LITE
  EventHelpers::NotifyTableFileCreationStarted(
      ioptions.listeners, dbname, column_family_name, fname, job_id, reason);
#endif  // !ROCKSDB_LITE
  TableProperties tp;
124
  if (iter->Valid() || !range_del_agg->IsEmpty()) {
125
    TableBuilder* builder;
126
    std::unique_ptr<WritableFileWriter> file_writer;
127 128 129 130 131
    // 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;
132
    {
133
      std::unique_ptr<FSWritableFile> file;
134
#ifndef NDEBUG
135
      bool use_direct_writes = file_options.use_direct_writes;
136 137
      TEST_SYNC_POINT_CALLBACK("BuildTable:create_file", &use_direct_writes);
#endif  // !NDEBUG
138
      IOStatus io_s = NewWritableFile(fs, fname, &file, file_options);
139
      assert(s.ok());
140 141 142 143
      s = io_s;
      if (io_status->ok()) {
        *io_status = io_s;
      }
144
      if (!s.ok()) {
145 146
        EventHelpers::LogAndNotifyTableFileCreationFinished(
            event_logger, ioptions.listeners, dbname, column_family_name, fname,
147 148
            job_id, meta->fd, kInvalidBlobFileNumber, tp, reason, s,
            file_checksum, file_checksum_func_name);
149 150 151
        return s;
      }
      file->SetIOPriority(io_priority);
S
Stream  
Shaohua Li 已提交
152
      file->SetWriteLifeTimeHint(write_hint);
S
Siying Dong 已提交
153

154
      file_writer.reset(new WritableFileWriter(
155 156 157
          std::move(file), fname, file_options, env, io_tracer,
          ioptions.statistics, ioptions.listeners,
          ioptions.file_checksum_gen_factory));
158

159
      builder = NewTableBuilder(
160 161
          ioptions, mutable_cf_options, internal_comparator,
          int_tbl_prop_collector_factories, column_family_id,
162
          column_family_name, file_writer.get(), compression,
163
          sample_for_compression, compression_opts_for_flush, level,
S
Sagar Vemuri 已提交
164
          false /* skip_filters */, creation_time, oldest_key_time,
165
          0 /*target_file_size*/, file_creation_time, db_id, db_session_id);
166
    }
167

I
Igor Canadi 已提交
168 169 170
    MergeHelper merge(env, internal_comparator.user_comparator(),
                      ioptions.merge_operator, nullptr, ioptions.info_log,
                      true /* internal key corruption is not ok */,
171 172
                      snapshots.empty() ? 0 : snapshots.back(),
                      snapshot_checker);
173

174 175 176 177 178 179 180 181 182
    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);

183 184
    CompactionIterator c_iter(
        iter, internal_comparator.user_comparator(), &merge, kMaxSequenceNumber,
Y
Yi Wu 已提交
185
        &snapshots, earliest_write_conflict_snapshot, snapshot_checker, env,
186
        ShouldReportDetailedTime(env, ioptions.statistics),
187
        true /* internal key corruption is not ok */, range_del_agg.get(),
188
        blob_file_builder.get(), ioptions.allow_data_in_errors);
189

190 191 192 193
    c_iter.SeekToFirst();
    for (; c_iter.Valid(); c_iter.Next()) {
      const Slice& key = c_iter.key();
      const Slice& value = c_iter.value();
194
      const ParsedInternalKey& ikey = c_iter.ikey();
195 196 197 198
      // Generate a rolling 64-bit hash of the key and values
      s = output_validator.Add(key, value);
      if (!s.ok()) {
        break;
199
      }
200
      builder->Add(key, value);
201
      meta->UpdateBoundaries(key, value, ikey.sequence, ikey.type);
202 203

      // TODO(noetzli): Update stats after flush, too.
I
Igor Canadi 已提交
204 205
      if (io_priority == Env::IO_HIGH &&
          IOSTATS(bytes_written) >= kReportFlushIOStatsEvery) {
206
        ThreadStatusUtil::SetThreadOperationProperty(
I
Igor Canadi 已提交
207
            ThreadStatus::FLUSH_BYTES_WRITTEN, IOSTATS(bytes_written));
208
      }
J
jorlow@chromium.org 已提交
209
    }
210 211 212 213 214
    if (!s.ok()) {
      c_iter.status().PermitUncheckedError();
    } else if (!c_iter.status().ok()) {
      s = c_iter.status();
    }
215 216 217 218 219 220 221 222 223 224
    if (s.ok()) {
      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();
        auto kv = tombstone.Serialize();
        builder->Add(kv.first.Encode(), kv.second);
        meta->UpdateBoundariesForRange(kv.first, tombstone.SerializeEndKey(),
                                       tombstone.seq_, internal_comparator);
      }
225

226
      if (blob_file_builder) {
227
        s = blob_file_builder->Finish();
228 229 230
      }
    }

231
    TEST_SYNC_POINT("BuildTable:BeforeFinishBuildTable");
232
    const bool empty = builder->IsEmpty();
A
Andres Noetzli 已提交
233
    if (!s.ok() || empty) {
J
jorlow@chromium.org 已提交
234
      builder->Abandon();
A
Andres Noetzli 已提交
235 236
    } else {
      s = builder->Finish();
J
jorlow@chromium.org 已提交
237
    }
238
    if (io_status->ok()) {
239
      *io_status = builder->io_status();
240
    }
A
Andres Noetzli 已提交
241 242

    if (s.ok() && !empty) {
243 244
      uint64_t file_size = builder->FileSize();
      meta->fd.file_size = file_size;
245
      meta->marked_for_compaction = builder->NeedCompact();
246
      assert(meta->fd.GetFileSize() > 0);
247
      tp = builder->GetTableProperties(); // refresh now that builder is finished
248
      if (table_properties) {
249
        *table_properties = tp;
250 251
      }
    }
J
jorlow@chromium.org 已提交
252 253 254
    delete builder;

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

272
    if (s.ok()) {
273 274 275 276
      s = *io_status;
    }

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

A
Andres Noetzli 已提交
278
    if (s.ok() && !empty) {
J
jorlow@chromium.org 已提交
279
      // Verify that the table is usable
280 281 282 283 284
      // 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
285
      ReadOptions read_options;
S
sdong 已提交
286
      std::unique_ptr<InternalIterator> it(table_cache->NewIterator(
287
          read_options, file_options, internal_comparator, *meta,
288 289
          nullptr /* range_del_agg */,
          mutable_cf_options.prefix_extractor.get(), nullptr,
290 291
          (internal_stats == nullptr) ? nullptr
                                      : internal_stats->GetFileReadHist(0),
292
          TableReaderCaller::kFlush, /*arena=*/nullptr,
293 294 295
          /*skip_filter=*/false, level,
          MaxFileSizeForL0MetaPin(mutable_cf_options),
          /*smallest_compaction_key=*/nullptr,
296 297
          /*largest_compaction_key*/ nullptr,
          /*allow_unprepared_value*/ false));
J
jorlow@chromium.org 已提交
298
      s = it->status();
299
      if (s.ok() && paranoid_file_checks) {
300 301 302
        OutputValidator file_validator(internal_comparator,
                                       /*enable_order_check=*/true,
                                       /*enable_hash=*/true);
A
Andres Noetzli 已提交
303
        for (it->SeekToFirst(); it->Valid(); it->Next()) {
304
          // Generate a rolling 64-bit hash of the key and values
305
          file_validator.Add(it->key(), it->value()).PermitUncheckedError();
A
Andres Noetzli 已提交
306
        }
307
        s = it->status();
308
        if (s.ok() && !output_validator.CompareValidator(file_validator)) {
309
          s = Status::Corruption("Paranoid checksums do not match");
310
        }
311
      }
J
jorlow@chromium.org 已提交
312 313 314 315 316 317 318 319
    }
  }

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

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

323
    Status ignored = fs->DeleteFile(fname, IOOptions(), dbg);
324
    ignored.PermitUncheckedError();
325 326 327 328 329

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

    if (blob_file_additions) {
      for (const std::string& blob_file_path : blob_file_paths) {
330
        ignored = fs->DeleteFile(blob_file_path, IOOptions(), dbg);
331
        ignored.PermitUncheckedError();
332 333 334 335
      }

      blob_file_additions->clear();
    }
J
jorlow@chromium.org 已提交
336
  }
337

338 339 340
  if (meta->fd.GetFileSize() == 0) {
    fname = "(nil)";
  }
341
  // Output to event logger and fire events.
342 343
  EventHelpers::LogAndNotifyTableFileCreationFinished(
      event_logger, ioptions.listeners, dbname, column_family_name, fname,
344 345
      job_id, meta->fd, meta->oldest_blob_file_number, tp, reason, s,
      file_checksum, file_checksum_func_name);
346

J
jorlow@chromium.org 已提交
347 348 349
  return s;
}

350
}  // namespace ROCKSDB_NAMESPACE