builder.cc 8.7 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 3 4
//  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.
5 6
//  This source code is also licensed under the GPLv2 license found in the
//  COPYING file in the root directory of this source tree.
7
//
J
jorlow@chromium.org 已提交
8 9 10 11 12 13
// 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 已提交
14
#include <algorithm>
15
#include <deque>
16
#include <vector>
17

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

39
namespace rocksdb {
J
jorlow@chromium.org 已提交
40

S
Siying Dong 已提交
41 42
class TableFactory;

43 44 45 46 47
TableBuilder* NewTableBuilder(
    const ImmutableCFOptions& ioptions,
    const InternalKeyComparator& internal_comparator,
    const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
        int_tbl_prop_collector_factories,
48 49
    uint32_t column_family_id, const std::string& column_family_name,
    WritableFileWriter* file, const CompressionType compression_type,
50
    const CompressionOptions& compression_opts,
51
    int level,
52
    const std::string* compression_dict, const bool skip_filters) {
53 54 55
  assert((column_family_id ==
          TablePropertiesCollectorFactory::Context::kUnknownColumnFamily) ==
         column_family_name.empty());
56 57 58
  return ioptions.table_factory->NewTableBuilder(
      TableBuilderOptions(ioptions, internal_comparator,
                          int_tbl_prop_collector_factories, compression_type,
59
                          compression_opts, compression_dict, skip_filters,
60
                          column_family_name, level),
61
      column_family_id, file);
S
Siying Dong 已提交
62 63
}

64 65
Status BuildTable(
    const std::string& dbname, Env* env, const ImmutableCFOptions& ioptions,
A
Aaron Gao 已提交
66
    const MutableCFOptions& mutable_cf_options, const EnvOptions& env_options,
A
Andrew Kryczka 已提交
67
    TableCache* table_cache, InternalIterator* iter,
68
    std::unique_ptr<InternalIterator> range_del_iter, FileMetaData* meta,
S
sdong 已提交
69
    const InternalKeyComparator& internal_comparator,
70 71
    const std::vector<std::unique_ptr<IntTblPropCollectorFactory>>*
        int_tbl_prop_collector_factories,
72 73
    uint32_t column_family_id, const std::string& column_family_name,
    std::vector<SequenceNumber> snapshots,
74
    SequenceNumber earliest_write_conflict_snapshot,
75
    const CompressionType compression,
76
    const CompressionOptions& compression_opts, bool paranoid_file_checks,
77 78
    InternalStats* internal_stats, TableFileCreationReason reason,
    EventLogger* event_logger, int job_id, const Env::IOPriority io_priority,
79
    TableProperties* table_properties, int level) {
80 81 82
  assert((column_family_id ==
          TablePropertiesCollectorFactory::Context::kUnknownColumnFamily) ==
         column_family_name.empty());
83 84
  // Reports the IOStats for flush for every following bytes.
  const size_t kReportFlushIOStatsEvery = 1048576;
J
jorlow@chromium.org 已提交
85
  Status s;
86
  meta->fd.file_size = 0;
J
jorlow@chromium.org 已提交
87
  iter->SeekToFirst();
A
Andrew Kryczka 已提交
88 89 90 91 92 93 94
  std::unique_ptr<RangeDelAggregator> range_del_agg(
      new RangeDelAggregator(internal_comparator, snapshots));
  s = range_del_agg->AddTombstones(std::move(range_del_iter));
  if (!s.ok()) {
    // may be non-ok if a range tombstone key is unparsable
    return s;
  }
J
jorlow@chromium.org 已提交
95

L
Lei Jin 已提交
96
  std::string fname = TableFileName(ioptions.db_paths, meta->fd.GetNumber(),
97
                                    meta->fd.GetPathId());
98 99 100 101 102 103
#ifndef ROCKSDB_LITE
  EventHelpers::NotifyTableFileCreationStarted(
      ioptions.listeners, dbname, column_family_name, fname, job_id, reason);
#endif  // !ROCKSDB_LITE
  TableProperties tp;

A
Andrew Kryczka 已提交
104
  if (iter->Valid() || range_del_agg->ShouldAddTombstones()) {
105 106 107 108
    TableBuilder* builder;
    unique_ptr<WritableFileWriter> file_writer;
    {
      unique_ptr<WritableFile> file;
109 110 111 112
#ifndef NDEBUG
      bool use_direct_writes = env_options.use_direct_writes;
      TEST_SYNC_POINT_CALLBACK("BuildTable:create_file", &use_direct_writes);
#endif  // !NDEBUG
S
sdong 已提交
113
      s = NewWritableFile(env, fname, &file, env_options);
114
      if (!s.ok()) {
115 116 117
        EventHelpers::LogAndNotifyTableFileCreationFinished(
            event_logger, ioptions.listeners, dbname, column_family_name, fname,
            job_id, meta->fd, tp, reason, s);
118 119 120
        return s;
      }
      file->SetIOPriority(io_priority);
S
Siying Dong 已提交
121

122 123
      file_writer.reset(new WritableFileWriter(std::move(file), env_options,
                                               ioptions.statistics));
124 125 126

      builder = NewTableBuilder(
          ioptions, internal_comparator, int_tbl_prop_collector_factories,
127
          column_family_id, column_family_name, file_writer.get(), compression,
128
          compression_opts, level);
129
    }
130

I
Igor Canadi 已提交
131 132 133 134
    MergeHelper merge(env, internal_comparator.user_comparator(),
                      ioptions.merge_operator, nullptr, ioptions.info_log,
                      true /* internal key corruption is not ok */,
                      snapshots.empty() ? 0 : snapshots.back());
135

136 137 138 139
    CompactionIterator c_iter(
        iter, internal_comparator.user_comparator(), &merge, kMaxSequenceNumber,
        &snapshots, earliest_write_conflict_snapshot, env,
        true /* internal key corruption is not ok */, range_del_agg.get());
140 141 142 143 144 145 146 147
    c_iter.SeekToFirst();
    for (; c_iter.Valid(); c_iter.Next()) {
      const Slice& key = c_iter.key();
      const Slice& value = c_iter.value();
      builder->Add(key, value);
      meta->UpdateBoundaries(key, c_iter.ikey().sequence);

      // TODO(noetzli): Update stats after flush, too.
I
Igor Canadi 已提交
148 149
      if (io_priority == Env::IO_HIGH &&
          IOSTATS(bytes_written) >= kReportFlushIOStatsEvery) {
150
        ThreadStatusUtil::SetThreadOperationProperty(
I
Igor Canadi 已提交
151
            ThreadStatus::FLUSH_BYTES_WRITTEN, IOSTATS(bytes_written));
152
      }
J
jorlow@chromium.org 已提交
153
    }
A
Andrew Kryczka 已提交
154
    // nullptr for table_{min,max} so all range tombstones will be flushed
155 156
    range_del_agg->AddToBuilder(builder, nullptr /* lower_bound */,
                                nullptr /* upper_bound */, meta);
J
jorlow@chromium.org 已提交
157 158

    // Finish and check for builder errors
A
Andres Noetzli 已提交
159
    bool empty = builder->NumEntries() == 0;
160
    s = c_iter.status();
A
Andres Noetzli 已提交
161
    if (!s.ok() || empty) {
J
jorlow@chromium.org 已提交
162
      builder->Abandon();
A
Andres Noetzli 已提交
163 164
    } else {
      s = builder->Finish();
J
jorlow@chromium.org 已提交
165
    }
A
Andres Noetzli 已提交
166 167

    if (s.ok() && !empty) {
168 169
      uint64_t file_size = builder->FileSize();
      meta->fd.file_size = file_size;
170
      meta->marked_for_compaction = builder->NeedCompact();
171
      assert(meta->fd.GetFileSize() > 0);
172
      tp = builder->GetTableProperties();
173
      if (table_properties) {
174
        *table_properties = tp;
175 176
      }
    }
J
jorlow@chromium.org 已提交
177 178 179
    delete builder;

    // Finish and check for file errors
S
Sagar Vemuri 已提交
180
    if (s.ok() && !empty) {
181
      StopWatch sw(env, ioptions.statistics, TABLE_SYNC_MICROS);
182
      s = file_writer->Sync(ioptions.use_fsync);
J
jorlow@chromium.org 已提交
183
    }
A
Andres Noetzli 已提交
184
    if (s.ok() && !empty) {
185
      s = file_writer->Close();
J
jorlow@chromium.org 已提交
186 187
    }

A
Andres Noetzli 已提交
188
    if (s.ok() && !empty) {
J
jorlow@chromium.org 已提交
189
      // Verify that the table is usable
190 191 192 193 194
      // 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
S
sdong 已提交
195
      std::unique_ptr<InternalIterator> it(table_cache->NewIterator(
196 197
          ReadOptions(), env_options, internal_comparator, meta->fd,
          nullptr /* range_del_agg */, nullptr,
198 199
          (internal_stats == nullptr) ? nullptr
                                      : internal_stats->GetFileReadHist(0),
200 201
          false /* for_compaction */, nullptr /* arena */,
          false /* skip_filter */, level));
J
jorlow@chromium.org 已提交
202
      s = it->status();
203
      if (s.ok() && paranoid_file_checks) {
A
Andres Noetzli 已提交
204 205
        for (it->SeekToFirst(); it->Valid(); it->Next()) {
        }
206 207
        s = it->status();
      }
J
jorlow@chromium.org 已提交
208 209 210 211 212 213 214 215
    }
  }

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

A
Andres Noetzli 已提交
216
  if (!s.ok() || meta->fd.GetFileSize() == 0) {
J
jorlow@chromium.org 已提交
217 218
    env->DeleteFile(fname);
  }
219 220 221 222 223 224

  // Output to event logger and fire events.
  EventHelpers::LogAndNotifyTableFileCreationFinished(
      event_logger, ioptions.listeners, dbname, column_family_name, fname,
      job_id, meta->fd, tp, reason, s);

J
jorlow@chromium.org 已提交
225 226 227
  return s;
}

228
}  // namespace rocksdb