options_helper.cc 56.4 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
#include "options/options_helper.h"
6 7

#include <cassert>
L
Lei Jin 已提交
8
#include <cctype>
S
sdong 已提交
9
#include <cstdlib>
10
#include <unordered_set>
11
#include <vector>
12

13
#include "options/options_type.h"
14
#include "rocksdb/cache.h"
15
#include "rocksdb/compaction_filter.h"
A
agiardullo 已提交
16
#include "rocksdb/convenience.h"
17
#include "rocksdb/filter_policy.h"
18 19
#include "rocksdb/memtablerep.h"
#include "rocksdb/merge_operator.h"
20
#include "rocksdb/options.h"
I
Igor Canadi 已提交
21
#include "rocksdb/rate_limiter.h"
22
#include "rocksdb/slice_transform.h"
23
#include "rocksdb/table.h"
24
#include "rocksdb/utilities/object_registry.h"
25
#include "table/block_based/block_based_table_factory.h"
26
#include "table/plain/plain_table_factory.h"
27
#include "util/string_util.h"
28

29
namespace ROCKSDB_NAMESPACE {
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44
DBOptions BuildDBOptions(const ImmutableDBOptions& immutable_db_options,
                         const MutableDBOptions& mutable_db_options) {
  DBOptions options;

  options.create_if_missing = immutable_db_options.create_if_missing;
  options.create_missing_column_families =
      immutable_db_options.create_missing_column_families;
  options.error_if_exists = immutable_db_options.error_if_exists;
  options.paranoid_checks = immutable_db_options.paranoid_checks;
  options.env = immutable_db_options.env;
  options.rate_limiter = immutable_db_options.rate_limiter;
  options.sst_file_manager = immutable_db_options.sst_file_manager;
  options.info_log = immutable_db_options.info_log;
  options.info_log_level = immutable_db_options.info_log_level;
L
Leonidas Galanis 已提交
45
  options.max_open_files = mutable_db_options.max_open_files;
46 47
  options.max_file_opening_threads =
      immutable_db_options.max_file_opening_threads;
48
  options.max_total_wal_size = mutable_db_options.max_total_wal_size;
49 50 51 52 53 54
  options.statistics = immutable_db_options.statistics;
  options.use_fsync = immutable_db_options.use_fsync;
  options.db_paths = immutable_db_options.db_paths;
  options.db_log_dir = immutable_db_options.db_log_dir;
  options.wal_dir = immutable_db_options.wal_dir;
  options.delete_obsolete_files_period_micros =
55
      mutable_db_options.delete_obsolete_files_period_micros;
56
  options.max_background_jobs = mutable_db_options.max_background_jobs;
57
  options.base_background_compactions =
58
      mutable_db_options.base_background_compactions;
59
  options.max_background_compactions =
60
      mutable_db_options.max_background_compactions;
61 62
  options.bytes_per_sync = mutable_db_options.bytes_per_sync;
  options.wal_bytes_per_sync = mutable_db_options.wal_bytes_per_sync;
63
  options.strict_bytes_per_sync = mutable_db_options.strict_bytes_per_sync;
64
  options.max_subcompactions = immutable_db_options.max_subcompactions;
65
  options.max_background_flushes = mutable_db_options.max_background_flushes;
66 67 68 69 70 71 72 73 74 75 76 77 78
  options.max_log_file_size = immutable_db_options.max_log_file_size;
  options.log_file_time_to_roll = immutable_db_options.log_file_time_to_roll;
  options.keep_log_file_num = immutable_db_options.keep_log_file_num;
  options.recycle_log_file_num = immutable_db_options.recycle_log_file_num;
  options.max_manifest_file_size = immutable_db_options.max_manifest_file_size;
  options.table_cache_numshardbits =
      immutable_db_options.table_cache_numshardbits;
  options.WAL_ttl_seconds = immutable_db_options.wal_ttl_seconds;
  options.WAL_size_limit_MB = immutable_db_options.wal_size_limit_mb;
  options.manifest_preallocation_size =
      immutable_db_options.manifest_preallocation_size;
  options.allow_mmap_reads = immutable_db_options.allow_mmap_reads;
  options.allow_mmap_writes = immutable_db_options.allow_mmap_writes;
79
  options.use_direct_reads = immutable_db_options.use_direct_reads;
80 81
  options.use_direct_io_for_flush_and_compaction =
      immutable_db_options.use_direct_io_for_flush_and_compaction;
82 83
  options.allow_fallocate = immutable_db_options.allow_fallocate;
  options.is_fd_close_on_exec = immutable_db_options.is_fd_close_on_exec;
84
  options.stats_dump_period_sec = mutable_db_options.stats_dump_period_sec;
85 86
  options.stats_persist_period_sec =
      mutable_db_options.stats_persist_period_sec;
87
  options.persist_stats_to_disk = immutable_db_options.persist_stats_to_disk;
88 89
  options.stats_history_buffer_size =
      mutable_db_options.stats_history_buffer_size;
90 91 92 93 94 95 96 97
  options.advise_random_on_open = immutable_db_options.advise_random_on_open;
  options.db_write_buffer_size = immutable_db_options.db_write_buffer_size;
  options.write_buffer_manager = immutable_db_options.write_buffer_manager;
  options.access_hint_on_compaction_start =
      immutable_db_options.access_hint_on_compaction_start;
  options.new_table_reader_for_compaction_inputs =
      immutable_db_options.new_table_reader_for_compaction_inputs;
  options.compaction_readahead_size =
98
      mutable_db_options.compaction_readahead_size;
99 100 101
  options.random_access_max_buffer_size =
      immutable_db_options.random_access_max_buffer_size;
  options.writable_file_max_buffer_size =
102
      mutable_db_options.writable_file_max_buffer_size;
103 104 105
  options.use_adaptive_mutex = immutable_db_options.use_adaptive_mutex;
  options.listeners = immutable_db_options.listeners;
  options.enable_thread_tracking = immutable_db_options.enable_thread_tracking;
106
  options.delayed_write_rate = mutable_db_options.delayed_write_rate;
107
  options.enable_pipelined_write = immutable_db_options.enable_pipelined_write;
M
Maysam Yabandeh 已提交
108
  options.unordered_write = immutable_db_options.unordered_write;
109 110 111 112
  options.allow_concurrent_memtable_write =
      immutable_db_options.allow_concurrent_memtable_write;
  options.enable_write_thread_adaptive_yield =
      immutable_db_options.enable_write_thread_adaptive_yield;
113 114
  options.max_write_batch_group_size_bytes =
      immutable_db_options.max_write_batch_group_size_bytes;
115 116 117 118 119 120
  options.write_thread_max_yield_usec =
      immutable_db_options.write_thread_max_yield_usec;
  options.write_thread_slow_yield_usec =
      immutable_db_options.write_thread_slow_yield_usec;
  options.skip_stats_update_on_db_open =
      immutable_db_options.skip_stats_update_on_db_open;
121 122
  options.skip_checking_sst_file_sizes_on_db_open =
      immutable_db_options.skip_checking_sst_file_sizes_on_db_open;
123 124 125 126 127 128 129 130 131 132 133
  options.wal_recovery_mode = immutable_db_options.wal_recovery_mode;
  options.allow_2pc = immutable_db_options.allow_2pc;
  options.row_cache = immutable_db_options.row_cache;
#ifndef ROCKSDB_LITE
  options.wal_filter = immutable_db_options.wal_filter;
#endif  // ROCKSDB_LITE
  options.fail_if_options_file_error =
      immutable_db_options.fail_if_options_file_error;
  options.dump_malloc_stats = immutable_db_options.dump_malloc_stats;
  options.avoid_flush_during_recovery =
      immutable_db_options.avoid_flush_during_recovery;
Y
Yi Wu 已提交
134 135
  options.avoid_flush_during_shutdown =
      mutable_db_options.avoid_flush_during_shutdown;
136 137
  options.allow_ingest_behind =
      immutable_db_options.allow_ingest_behind;
138 139
  options.preserve_deletes =
      immutable_db_options.preserve_deletes;
140 141
  options.two_write_queues = immutable_db_options.two_write_queues;
  options.manual_wal_flush = immutable_db_options.manual_wal_flush;
142
  options.atomic_flush = immutable_db_options.atomic_flush;
143 144
  options.avoid_unnecessary_blocking_io =
      immutable_db_options.avoid_unnecessary_blocking_io;
145
  options.log_readahead_size = immutable_db_options.log_readahead_size;
146 147
  options.file_checksum_gen_factory =
      immutable_db_options.file_checksum_gen_factory;
148
  options.best_efforts_recovery = immutable_db_options.best_efforts_recovery;
149 150 151
  return options;
}

152 153 154 155 156 157 158 159 160 161 162
ColumnFamilyOptions BuildColumnFamilyOptions(
    const ColumnFamilyOptions& options,
    const MutableCFOptions& mutable_cf_options) {
  ColumnFamilyOptions cf_opts(options);

  // Memtable related options
  cf_opts.write_buffer_size = mutable_cf_options.write_buffer_size;
  cf_opts.max_write_buffer_number = mutable_cf_options.max_write_buffer_number;
  cf_opts.arena_block_size = mutable_cf_options.arena_block_size;
  cf_opts.memtable_prefix_bloom_size_ratio =
      mutable_cf_options.memtable_prefix_bloom_size_ratio;
163 164
  cf_opts.memtable_whole_key_filtering =
      mutable_cf_options.memtable_whole_key_filtering;
165 166 167 168
  cf_opts.memtable_huge_page_size = mutable_cf_options.memtable_huge_page_size;
  cf_opts.max_successive_merges = mutable_cf_options.max_successive_merges;
  cf_opts.inplace_update_num_locks =
      mutable_cf_options.inplace_update_num_locks;
169
  cf_opts.prefix_extractor = mutable_cf_options.prefix_extractor;
170 171 172 173

  // Compaction related options
  cf_opts.disable_auto_compactions =
      mutable_cf_options.disable_auto_compactions;
174 175 176 177
  cf_opts.soft_pending_compaction_bytes_limit =
      mutable_cf_options.soft_pending_compaction_bytes_limit;
  cf_opts.hard_pending_compaction_bytes_limit =
      mutable_cf_options.hard_pending_compaction_bytes_limit;
178 179 180 181 182 183 184 185 186 187 188 189 190 191
  cf_opts.level0_file_num_compaction_trigger =
      mutable_cf_options.level0_file_num_compaction_trigger;
  cf_opts.level0_slowdown_writes_trigger =
      mutable_cf_options.level0_slowdown_writes_trigger;
  cf_opts.level0_stop_writes_trigger =
      mutable_cf_options.level0_stop_writes_trigger;
  cf_opts.max_compaction_bytes = mutable_cf_options.max_compaction_bytes;
  cf_opts.target_file_size_base = mutable_cf_options.target_file_size_base;
  cf_opts.target_file_size_multiplier =
      mutable_cf_options.target_file_size_multiplier;
  cf_opts.max_bytes_for_level_base =
      mutable_cf_options.max_bytes_for_level_base;
  cf_opts.max_bytes_for_level_multiplier =
      mutable_cf_options.max_bytes_for_level_multiplier;
192
  cf_opts.ttl = mutable_cf_options.ttl;
S
Sagar Vemuri 已提交
193 194
  cf_opts.periodic_compaction_seconds =
      mutable_cf_options.periodic_compaction_seconds;
195 196 197 198 199 200 201

  cf_opts.max_bytes_for_level_multiplier_additional.clear();
  for (auto value :
       mutable_cf_options.max_bytes_for_level_multiplier_additional) {
    cf_opts.max_bytes_for_level_multiplier_additional.emplace_back(value);
  }

202
  cf_opts.compaction_options_fifo = mutable_cf_options.compaction_options_fifo;
203 204
  cf_opts.compaction_options_universal =
      mutable_cf_options.compaction_options_universal;
205

206 207 208 209 210 211
  // Misc options
  cf_opts.max_sequential_skip_in_iterations =
      mutable_cf_options.max_sequential_skip_in_iterations;
  cf_opts.paranoid_file_checks = mutable_cf_options.paranoid_file_checks;
  cf_opts.report_bg_io_stats = mutable_cf_options.report_bg_io_stats;
  cf_opts.compression = mutable_cf_options.compression;
212 213 214 215
  cf_opts.compression_opts = mutable_cf_options.compression_opts;
  cf_opts.bottommost_compression = mutable_cf_options.bottommost_compression;
  cf_opts.bottommost_compression_opts =
      mutable_cf_options.bottommost_compression_opts;
216
  cf_opts.sample_for_compression = mutable_cf_options.sample_for_compression;
217 218 219 220 221 222 223 224

  cf_opts.table_factory = options.table_factory;
  // TODO(yhchiang): find some way to handle the following derived options
  // * max_file_size

  return cf_opts;
}

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
std::map<CompactionStyle, std::string>
    OptionsHelper::compaction_style_to_string = {
        {kCompactionStyleLevel, "kCompactionStyleLevel"},
        {kCompactionStyleUniversal, "kCompactionStyleUniversal"},
        {kCompactionStyleFIFO, "kCompactionStyleFIFO"},
        {kCompactionStyleNone, "kCompactionStyleNone"}};

std::map<CompactionPri, std::string> OptionsHelper::compaction_pri_to_string = {
    {kByCompensatedSize, "kByCompensatedSize"},
    {kOldestLargestSeqFirst, "kOldestLargestSeqFirst"},
    {kOldestSmallestSeqFirst, "kOldestSmallestSeqFirst"},
    {kMinOverlappingRatio, "kMinOverlappingRatio"}};

std::map<CompactionStopStyle, std::string>
    OptionsHelper::compaction_stop_style_to_string = {
        {kCompactionStopStyleSimilarSize, "kCompactionStopStyleSimilarSize"},
        {kCompactionStopStyleTotalSize, "kCompactionStopStyleTotalSize"}};

std::unordered_map<std::string, ChecksumType>
    OptionsHelper::checksum_type_string_map = {{"kNoChecksum", kNoChecksum},
                                               {"kCRC32c", kCRC32c},
B
Bo Hou 已提交
246 247
                                               {"kxxHash", kxxHash},
                                               {"kxxHash64", kxxHash64}};
248

249 250 251 252 253 254 255 256 257 258 259 260
std::unordered_map<std::string, CompressionType>
    OptionsHelper::compression_type_string_map = {
        {"kNoCompression", kNoCompression},
        {"kSnappyCompression", kSnappyCompression},
        {"kZlibCompression", kZlibCompression},
        {"kBZip2Compression", kBZip2Compression},
        {"kLZ4Compression", kLZ4Compression},
        {"kLZ4HCCompression", kLZ4HCCompression},
        {"kXpressCompression", kXpressCompression},
        {"kZSTD", kZSTD},
        {"kZSTDNotFinalCompression", kZSTDNotFinalCompression},
        {"kDisableCompressionOption", kDisableCompressionOption}};
C
Cheng Chang 已提交
261 262 263 264 265 266 267 268 269 270 271 272

std::vector<CompressionType> GetSupportedCompressions() {
  std::vector<CompressionType> supported_compressions;
  for (const auto& comp_to_name : OptionsHelper::compression_type_string_map) {
    CompressionType t = comp_to_name.second;
    if (t != kDisableCompressionOption && CompressionTypeSupported(t)) {
      supported_compressions.push_back(t);
    }
  }
  return supported_compressions;
}

273
#ifndef ROCKSDB_LITE
274

D
Dmitri Smirnov 已提交
275
namespace {
276 277 278 279 280 281 282 283 284
bool SerializeVectorCompressionType(const std::vector<CompressionType>& types,
                                    std::string* value) {
  std::stringstream ss;
  bool result;
  for (size_t i = 0; i < types.size(); ++i) {
    if (i > 0) {
      ss << ':';
    }
    std::string string_type;
S
SherlockNoMad 已提交
285
    result = SerializeEnum<CompressionType>(compression_type_string_map,
286
                                            types[i], &string_type);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    if (result == false) {
      return result;
    }
    ss << string_type;
  }
  *value = ss.str();
  return true;
}

bool ParseVectorCompressionType(
    const std::string& value,
    std::vector<CompressionType>* compression_per_level) {
  compression_per_level->clear();
  size_t start = 0;
  while (start < value.size()) {
    size_t end = value.find(':', start);
    bool is_ok;
    CompressionType type;
    if (end == std::string::npos) {
306 307
      is_ok = ParseEnum<CompressionType>(compression_type_string_map,
                                         value.substr(start), &type);
308 309 310 311 312 313
      if (!is_ok) {
        return false;
      }
      compression_per_level->emplace_back(type);
      break;
    } else {
314 315
      is_ok = ParseEnum<CompressionType>(
          compression_type_string_map, value.substr(start, end - start), &type);
316 317 318 319 320 321 322 323 324
      if (!is_ok) {
        return false;
      }
      compression_per_level->emplace_back(type);
      start = end + 1;
    }
  }
  return true;
}
325
}  // anonymouse namespace
326

327 328 329 330
bool ParseSliceTransformHelper(
    const std::string& kFixedPrefixName, const std::string& kCappedPrefixName,
    const std::string& value,
    std::shared_ptr<const SliceTransform>* slice_transform) {
331 332
  const char* no_op_name = "rocksdb.Noop";
  size_t no_op_length = strlen(no_op_name);
333 334 335 336 337 338 339 340 341 342 343
  auto& pe_value = value;
  if (pe_value.size() > kFixedPrefixName.size() &&
      pe_value.compare(0, kFixedPrefixName.size(), kFixedPrefixName) == 0) {
    int prefix_length = ParseInt(trim(value.substr(kFixedPrefixName.size())));
    slice_transform->reset(NewFixedPrefixTransform(prefix_length));
  } else if (pe_value.size() > kCappedPrefixName.size() &&
             pe_value.compare(0, kCappedPrefixName.size(), kCappedPrefixName) ==
                 0) {
    int prefix_length =
        ParseInt(trim(pe_value.substr(kCappedPrefixName.size())));
    slice_transform->reset(NewCappedPrefixTransform(prefix_length));
344 345 346 347
  } else if (pe_value.size() == no_op_length &&
             pe_value.compare(0, no_op_length, no_op_name) == 0) {
    const SliceTransform* no_op_transform = NewNoopTransform();
    slice_transform->reset(no_op_transform);
348
  } else if (value == kNullptrString) {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    slice_transform->reset();
  } else {
    return false;
  }

  return true;
}

bool ParseSliceTransform(
    const std::string& value,
    std::shared_ptr<const SliceTransform>* slice_transform) {
  // While we normally don't convert the string representation of a
  // pointer-typed option into its instance, here we do so for backward
  // compatibility as we allow this action in SetOption().

  // TODO(yhchiang): A possible better place for these serialization /
  // deserialization is inside the class definition of pointer-typed
  // option itself, but this requires a bigger change of public API.
  bool result =
      ParseSliceTransformHelper("fixed:", "capped:", value, slice_transform);
  if (result) {
    return result;
  }
  result = ParseSliceTransformHelper(
      "rocksdb.FixedPrefix.", "rocksdb.CappedPrefix.", value, slice_transform);
  if (result) {
    return result;
  }
  // TODO(yhchiang): we can further support other default
  //                 SliceTransforms here.
  return false;
}

382 383 384 385 386 387 388 389 390
bool ParseOptionHelper(char* opt_address, const OptionType& opt_type,
                       const std::string& value) {
  switch (opt_type) {
    case OptionType::kBoolean:
      *reinterpret_cast<bool*>(opt_address) = ParseBoolean("", value);
      break;
    case OptionType::kInt:
      *reinterpret_cast<int*>(opt_address) = ParseInt(value);
      break;
Z
Zhongyi Xie 已提交
391 392 393 394 395 396
    case OptionType::kInt32T:
      *reinterpret_cast<int32_t*>(opt_address) = ParseInt32(value);
      break;
    case OptionType::kInt64T:
      PutUnaligned(reinterpret_cast<int64_t*>(opt_address), ParseInt64(value));
      break;
Y
Yi Wu 已提交
397 398 399
    case OptionType::kVectorInt:
      *reinterpret_cast<std::vector<int>*>(opt_address) = ParseVectorInt(value);
      break;
400 401 402 403 404 405 406
    case OptionType::kUInt:
      *reinterpret_cast<unsigned int*>(opt_address) = ParseUint32(value);
      break;
    case OptionType::kUInt32T:
      *reinterpret_cast<uint32_t*>(opt_address) = ParseUint32(value);
      break;
    case OptionType::kUInt64T:
T
Tomas Kolda 已提交
407
      PutUnaligned(reinterpret_cast<uint64_t*>(opt_address), ParseUint64(value));
408 409
      break;
    case OptionType::kSizeT:
T
Tomas Kolda 已提交
410
      PutUnaligned(reinterpret_cast<size_t*>(opt_address), ParseSizeT(value));
411 412 413 414 415 416 417 418
      break;
    case OptionType::kString:
      *reinterpret_cast<std::string*>(opt_address) = value;
      break;
    case OptionType::kDouble:
      *reinterpret_cast<double*>(opt_address) = ParseDouble(value);
      break;
    case OptionType::kCompactionStyle:
419 420 421
      return ParseEnum<CompactionStyle>(
          compaction_style_string_map, value,
          reinterpret_cast<CompactionStyle*>(opt_address));
422 423 424 425
    case OptionType::kCompactionPri:
      return ParseEnum<CompactionPri>(
          compaction_pri_string_map, value,
          reinterpret_cast<CompactionPri*>(opt_address));
426
    case OptionType::kCompressionType:
427 428 429
      return ParseEnum<CompressionType>(
          compression_type_string_map, value,
          reinterpret_cast<CompressionType*>(opt_address));
430 431 432 433 434 435 436
    case OptionType::kVectorCompressionType:
      return ParseVectorCompressionType(
          value, reinterpret_cast<std::vector<CompressionType>*>(opt_address));
    case OptionType::kSliceTransform:
      return ParseSliceTransform(
          value, reinterpret_cast<std::shared_ptr<const SliceTransform>*>(
                     opt_address));
437
    case OptionType::kChecksumType:
438 439 440
      return ParseEnum<ChecksumType>(
          checksum_type_string_map, value,
          reinterpret_cast<ChecksumType*>(opt_address));
441
    case OptionType::kEncodingType:
442 443 444
      return ParseEnum<EncodingType>(
          encoding_type_string_map, value,
          reinterpret_cast<EncodingType*>(opt_address));
445 446 447 448
    case OptionType::kCompactionStopStyle:
      return ParseEnum<CompactionStopStyle>(
          compaction_stop_style_string_map, value,
          reinterpret_cast<CompactionStopStyle*>(opt_address));
449 450 451 452 453 454 455 456 457
    default:
      return false;
  }
  return true;
}

bool SerializeSingleOptionHelper(const char* opt_address,
                                 const OptionType opt_type,
                                 std::string* value) {
458

459 460 461 462 463 464 465 466
  assert(value);
  switch (opt_type) {
    case OptionType::kBoolean:
      *value = *(reinterpret_cast<const bool*>(opt_address)) ? "true" : "false";
      break;
    case OptionType::kInt:
      *value = ToString(*(reinterpret_cast<const int*>(opt_address)));
      break;
Z
Zhongyi Xie 已提交
467 468 469 470 471 472 473 474 475 476
    case OptionType::kInt32T:
      *value = ToString(*(reinterpret_cast<const int32_t*>(opt_address)));
      break;
    case OptionType::kInt64T:
      {
        int64_t v;
        GetUnaligned(reinterpret_cast<const int64_t*>(opt_address), &v);
        *value = ToString(v);
      }
      break;
Y
Yi Wu 已提交
477 478 479
    case OptionType::kVectorInt:
      return SerializeIntVector(
          *reinterpret_cast<const std::vector<int>*>(opt_address), value);
480 481 482 483 484 485 486
    case OptionType::kUInt:
      *value = ToString(*(reinterpret_cast<const unsigned int*>(opt_address)));
      break;
    case OptionType::kUInt32T:
      *value = ToString(*(reinterpret_cast<const uint32_t*>(opt_address)));
      break;
    case OptionType::kUInt64T:
T
Tomas Kolda 已提交
487 488 489 490 491
      {
        uint64_t v;
        GetUnaligned(reinterpret_cast<const uint64_t*>(opt_address), &v);
        *value = ToString(v);
      }
492 493
      break;
    case OptionType::kSizeT:
T
Tomas Kolda 已提交
494 495 496 497 498
      {
        size_t v;
        GetUnaligned(reinterpret_cast<const size_t*>(opt_address), &v);
        *value = ToString(v);
      }
499 500 501 502 503
      break;
    case OptionType::kDouble:
      *value = ToString(*(reinterpret_cast<const double*>(opt_address)));
      break;
    case OptionType::kString:
504 505
      *value = EscapeOptionString(
          *(reinterpret_cast<const std::string*>(opt_address)));
506 507
      break;
    case OptionType::kCompactionStyle:
508 509
      return SerializeEnum<CompactionStyle>(
          compaction_style_string_map,
S
SherlockNoMad 已提交
510
          *(reinterpret_cast<const CompactionStyle*>(opt_address)), value);
511 512 513 514
    case OptionType::kCompactionPri:
      return SerializeEnum<CompactionPri>(
          compaction_pri_string_map,
          *(reinterpret_cast<const CompactionPri*>(opt_address)), value);
515
    case OptionType::kCompressionType:
516 517
      return SerializeEnum<CompressionType>(
          compression_type_string_map,
518 519 520 521 522 523 524 525 526 527 528
          *(reinterpret_cast<const CompressionType*>(opt_address)), value);
    case OptionType::kVectorCompressionType:
      return SerializeVectorCompressionType(
          *(reinterpret_cast<const std::vector<CompressionType>*>(opt_address)),
          value);
      break;
    case OptionType::kSliceTransform: {
      const auto* slice_transform_ptr =
          reinterpret_cast<const std::shared_ptr<const SliceTransform>*>(
              opt_address);
      *value = slice_transform_ptr->get() ? slice_transform_ptr->get()->Name()
529
                                          : kNullptrString;
530 531 532 533 534 535 536
      break;
    }
    case OptionType::kTableFactory: {
      const auto* table_factory_ptr =
          reinterpret_cast<const std::shared_ptr<const TableFactory>*>(
              opt_address);
      *value = table_factory_ptr->get() ? table_factory_ptr->get()->Name()
537
                                        : kNullptrString;
538 539 540 541 542
      break;
    }
    case OptionType::kComparator: {
      // it's a const pointer of const Comparator*
      const auto* ptr = reinterpret_cast<const Comparator* const*>(opt_address);
543 544 545
      // Since the user-specified comparator will be wrapped by
      // InternalKeyComparator, we should persist the user-specified one
      // instead of InternalKeyComparator.
S
Siying Dong 已提交
546 547
      if (*ptr == nullptr) {
        *value = kNullptrString;
548
      } else {
S
Siying Dong 已提交
549 550 551 552 553
        const Comparator* root_comp = (*ptr)->GetRootComparator();
        if (root_comp == nullptr) {
          root_comp = (*ptr);
        }
        *value = root_comp->Name();
554
      }
555 556 557 558 559 560
      break;
    }
    case OptionType::kCompactionFilter: {
      // it's a const pointer of const CompactionFilter*
      const auto* ptr =
          reinterpret_cast<const CompactionFilter* const*>(opt_address);
561
      *value = *ptr ? (*ptr)->Name() : kNullptrString;
562 563 564 565 566 567
      break;
    }
    case OptionType::kCompactionFilterFactory: {
      const auto* ptr =
          reinterpret_cast<const std::shared_ptr<CompactionFilterFactory>*>(
              opt_address);
568
      *value = ptr->get() ? ptr->get()->Name() : kNullptrString;
569 570 571 572 573 574
      break;
    }
    case OptionType::kMemTableRepFactory: {
      const auto* ptr =
          reinterpret_cast<const std::shared_ptr<MemTableRepFactory>*>(
              opt_address);
575
      *value = ptr->get() ? ptr->get()->Name() : kNullptrString;
576 577 578 579 580
      break;
    }
    case OptionType::kMergeOperator: {
      const auto* ptr =
          reinterpret_cast<const std::shared_ptr<MergeOperator>*>(opt_address);
581 582 583 584 585 586 587 588 589 590
      *value = ptr->get() ? ptr->get()->Name() : kNullptrString;
      break;
    }
    case OptionType::kFilterPolicy: {
      const auto* ptr =
          reinterpret_cast<const std::shared_ptr<FilterPolicy>*>(opt_address);
      *value = ptr->get() ? ptr->get()->Name() : kNullptrString;
      break;
    }
    case OptionType::kChecksumType:
591 592
      return SerializeEnum<ChecksumType>(
          checksum_type_string_map,
593 594 595 596 597 598
          *reinterpret_cast<const ChecksumType*>(opt_address), value);
    case OptionType::kFlushBlockPolicyFactory: {
      const auto* ptr =
          reinterpret_cast<const std::shared_ptr<FlushBlockPolicyFactory>*>(
              opt_address);
      *value = ptr->get() ? ptr->get()->Name() : kNullptrString;
599 600
      break;
    }
601
    case OptionType::kEncodingType:
602 603
      return SerializeEnum<EncodingType>(
          encoding_type_string_map,
604
          *reinterpret_cast<const EncodingType*>(opt_address), value);
605 606 607 608
    case OptionType::kCompactionStopStyle:
      return SerializeEnum<CompactionStopStyle>(
          compaction_stop_style_string_map,
          *reinterpret_cast<const CompactionStopStyle*>(opt_address), value);
609 610 611 612 613 614
    default:
      return false;
  }
  return true;
}

615
Status GetMutableOptionsFromStrings(
616 617
    const MutableCFOptions& base_options,
    const std::unordered_map<std::string, std::string>& options_map,
618
    Logger* info_log, MutableCFOptions* new_options) {
619 620
  assert(new_options);
  *new_options = base_options;
621
  ConfigOptions config_options;
622
  for (const auto& o : options_map) {
623 624 625 626
    std::string elem;
    const auto opt_info =
        OptionTypeInfo::Find(o.first, cf_options_type_info, &elem);
    if (opt_info == nullptr) {
627
      return Status::InvalidArgument("Unrecognized option: " + o.first);
628
    } else if (!opt_info->IsMutable()) {
629
      return Status::InvalidArgument("Option not changeable: " + o.first);
630
    } else if (opt_info->IsDeprecated()) {
631 632 633 634
      // log warning when user tries to set a deprecated option but don't fail
      // the call for compatibility.
      ROCKS_LOG_WARN(info_log, "%s is a deprecated option and cannot be set",
                     o.first.c_str());
635 636 637 638 639 640 641
    } else {
      Status s = opt_info->Parse(
          config_options, elem, o.second,
          reinterpret_cast<char*>(new_options) + opt_info->mutable_offset_);
      if (!s.ok()) {
        return s;
      }
642 643
    }
  }
644
  return Status::OK();
645 646
}

647 648 649 650 651 652
Status GetMutableDBOptionsFromStrings(
    const MutableDBOptions& base_options,
    const std::unordered_map<std::string, std::string>& options_map,
    MutableDBOptions* new_options) {
  assert(new_options);
  *new_options = base_options;
653 654
  ConfigOptions config_options;

655 656
  for (const auto& o : options_map) {
    try {
657 658 659 660
      std::string elem;
      const auto opt_info =
          OptionTypeInfo::Find(o.first, db_options_type_info, &elem);
      if (opt_info == nullptr) {
661
        return Status::InvalidArgument("Unrecognized option: " + o.first);
662
      } else if (!opt_info->IsMutable()) {
663
        return Status::InvalidArgument("Option not changeable: " + o.first);
664 665 666 667 668 669 670
      } else {
        Status s = opt_info->Parse(
            config_options, elem, o.second,
            reinterpret_cast<char*>(new_options) + opt_info->mutable_offset_);
        if (!s.ok()) {
          return s;
        }
671 672 673 674 675 676 677 678 679
      }
    } catch (std::exception& e) {
      return Status::InvalidArgument("Error parsing " + o.first + ":" +
                                     std::string(e.what()));
    }
  }
  return Status::OK();
}

680 681
Status StringToMap(const std::string& opts_str,
                   std::unordered_map<std::string, std::string>* opts_map) {
L
Lei Jin 已提交
682 683
  assert(opts_map);
  // Example:
684 685
  //   opts_str = "write_buffer_size=1024;max_write_buffer_number=2;"
  //              "nested_opt={opt1=1;opt2=2};max_bytes_for_level_base=100"
L
Lei Jin 已提交
686 687
  size_t pos = 0;
  std::string opts = trim(opts_str);
688 689 690 691 692
  // If the input string starts and ends with "{...}", strip off the brackets
  while (opts.size() > 2 && opts[0] == '{' && opts[opts.size() - 1] == '}') {
    opts = trim(opts.substr(1, opts.size() - 2));
  }

L
Lei Jin 已提交
693 694 695
  while (pos < opts.size()) {
    size_t eq_pos = opts.find('=', pos);
    if (eq_pos == std::string::npos) {
696
      return Status::InvalidArgument("Mismatched key value pair, '=' expected");
L
Lei Jin 已提交
697 698
    }
    std::string key = trim(opts.substr(pos, eq_pos - pos));
699 700 701
    if (key.empty()) {
      return Status::InvalidArgument("Empty key found");
    }
L
Lei Jin 已提交
702

703 704 705 706 707 708 709 710
    // skip space after '=' and look for '{' for possible nested options
    pos = eq_pos + 1;
    while (pos < opts.size() && isspace(opts[pos])) {
      ++pos;
    }
    // Empty value at the end
    if (pos >= opts.size()) {
      (*opts_map)[key] = "";
L
Lei Jin 已提交
711
      break;
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    }
    if (opts[pos] == '{') {
      int count = 1;
      size_t brace_pos = pos + 1;
      while (brace_pos < opts.size()) {
        if (opts[brace_pos] == '{') {
          ++count;
        } else if (opts[brace_pos] == '}') {
          --count;
          if (count == 0) {
            break;
          }
        }
        ++brace_pos;
      }
      // found the matching closing brace
      if (count == 0) {
        (*opts_map)[key] = trim(opts.substr(pos + 1, brace_pos - pos - 1));
        // skip all whitespace and move to the next ';'
        // brace_pos points to the next position after the matching '}'
        pos = brace_pos + 1;
        while (pos < opts.size() && isspace(opts[pos])) {
          ++pos;
        }
        if (pos < opts.size() && opts[pos] != ';') {
          return Status::InvalidArgument(
              "Unexpected chars after nested options");
        }
        ++pos;
      } else {
        return Status::InvalidArgument(
            "Mismatched curly braces for nested options");
      }
L
Lei Jin 已提交
745
    } else {
746 747 748 749 750 751 752 753 754
      size_t sc_pos = opts.find(';', pos);
      if (sc_pos == std::string::npos) {
        (*opts_map)[key] = trim(opts.substr(pos));
        // It either ends with a trailing semi-colon or the last key-value pair
        break;
      } else {
        (*opts_map)[key] = trim(opts.substr(pos, sc_pos - pos));
      }
      pos = sc_pos + 1;
L
Lei Jin 已提交
755 756 757
    }
  }

758
  return Status::OK();
L
Lei Jin 已提交
759 760
}

761
Status GetStringFromStruct(
762
    const ConfigOptions& config_options, const void* const opt_ptr,
763
    const std::unordered_map<std::string, OptionTypeInfo>& type_info,
764
    std::string* opt_string) {
765 766
  assert(opt_string);
  opt_string->clear();
767 768
  for (const auto iter : type_info) {
    const auto& opt_info = iter.second;
769 770 771 772
    // If the option is no longer used in rocksdb and marked as deprecated,
    // we skip it in the serialization.
    if (opt_info.ShouldSerialize()) {
      const char* opt_addr =
773
          reinterpret_cast<const char*>(opt_ptr) + opt_info.offset_;
774
      std::string value;
775 776
      Status s =
          opt_info.Serialize(config_options, iter.first, opt_addr, &value);
777 778 779 780 781
      if (s.ok()) {
        opt_string->append(iter.first + "=" + value + config_options.delimiter);
      } else {
        return s;
      }
782 783 784 785 786
    }
  }
  return Status::OK();
}

787 788 789
Status GetStringFromDBOptions(std::string* opt_string,
                              const DBOptions& db_options,
                              const std::string& delimiter) {
790 791 792 793 794 795 796 797 798 799
  ConfigOptions config_options;
  config_options.delimiter = delimiter;
  return GetStringFromDBOptions(config_options, db_options, opt_string);
}

Status GetStringFromDBOptions(const ConfigOptions& cfg_options,
                              const DBOptions& db_options,
                              std::string* opt_string) {
  return GetStringFromStruct(cfg_options, &db_options, db_options_type_info,
                             opt_string);
800 801
}

802 803 804
Status GetStringFromColumnFamilyOptions(std::string* opt_string,
                                        const ColumnFamilyOptions& cf_options,
                                        const std::string& delimiter) {
805 806 807 808 809 810 811 812 813 814 815
  ConfigOptions config_options;
  config_options.delimiter = delimiter;
  return GetStringFromColumnFamilyOptions(config_options, cf_options,
                                          opt_string);
}

Status GetStringFromColumnFamilyOptions(const ConfigOptions& config_options,
                                        const ColumnFamilyOptions& cf_options,
                                        std::string* opt_string) {
  return GetStringFromStruct(config_options, &cf_options, cf_options_type_info,
                             opt_string);
816 817
}

818 819 820 821 822 823 824 825 826 827 828
Status GetStringFromCompressionType(std::string* compression_str,
                                    CompressionType compression_type) {
  bool ok = SerializeEnum<CompressionType>(compression_type_string_map,
                                           compression_type, compression_str);
  if (ok) {
    return Status::OK();
  } else {
    return Status::InvalidArgument("Invalid compression types");
  }
}

829 830 831 832 833 834 835
static Status ParseDBOption(const ConfigOptions& config_options,
                            const std::string& name,
                            const std::string& org_value,
                            DBOptions* new_options) {
  const std::string& value = config_options.input_strings_escaped
                                 ? UnescapeOptionString(org_value)
                                 : org_value;
836 837 838
  std::string elem;
  const auto opt_info = OptionTypeInfo::Find(name, db_options_type_info, &elem);
  if (opt_info == nullptr) {
839 840
    return Status::InvalidArgument("Unrecognized option DBOptions:", name);
  } else {
841 842 843
    return opt_info->Parse(
        config_options, elem, value,
        reinterpret_cast<char*>(new_options) + opt_info->offset_);
844 845
  }
}
L
Lei Jin 已提交
846

847
Status GetColumnFamilyOptionsFromMap(
L
Lei Jin 已提交
848 849
    const ColumnFamilyOptions& base_options,
    const std::unordered_map<std::string, std::string>& opts_map,
850 851
    ColumnFamilyOptions* new_options, bool input_strings_escaped,
    bool ignore_unknown_options) {
852 853 854 855 856
  ConfigOptions config_options;
  config_options.ignore_unknown_options = ignore_unknown_options;
  config_options.input_strings_escaped = input_strings_escaped;
  return GetColumnFamilyOptionsFromMap(config_options, base_options, opts_map,
                                       new_options);
857 858
}

859 860
Status GetColumnFamilyOptionsFromMap(
    const ConfigOptions& config_options,
861 862
    const ColumnFamilyOptions& base_options,
    const std::unordered_map<std::string, std::string>& opts_map,
863
    ColumnFamilyOptions* new_options) {
864 865
  assert(new_options);
  *new_options = base_options;
L
Lei Jin 已提交
866
  for (const auto& o : opts_map) {
867 868
    auto s =
        ParseColumnFamilyOption(config_options, o.first, o.second, new_options);
869 870
    if (!s.ok()) {
      if (s.IsNotSupported()) {
871 872 873
        continue;
      } else if (s.IsInvalidArgument() &&
                 config_options.ignore_unknown_options) {
874
        continue;
875
      } else {
876 877
        // Restore "new_options" to the default "base_options".
        *new_options = base_options;
878
        return s;
879
      }
L
Lei Jin 已提交
880 881
    }
  }
882
  return Status::OK();
L
Lei Jin 已提交
883 884
}

885
Status GetColumnFamilyOptionsFromString(
L
Lei Jin 已提交
886 887 888
    const ColumnFamilyOptions& base_options,
    const std::string& opts_str,
    ColumnFamilyOptions* new_options) {
889 890 891 892 893 894 895 896 897 898 899
  ConfigOptions config_options;
  config_options.input_strings_escaped = false;
  config_options.ignore_unknown_options = false;
  return GetColumnFamilyOptionsFromString(config_options, base_options,
                                          opts_str, new_options);
}

Status GetColumnFamilyOptionsFromString(const ConfigOptions& config_options,
                                        const ColumnFamilyOptions& base_options,
                                        const std::string& opts_str,
                                        ColumnFamilyOptions* new_options) {
L
Lei Jin 已提交
900
  std::unordered_map<std::string, std::string> opts_map;
901 902
  Status s = StringToMap(opts_str, &opts_map);
  if (!s.ok()) {
903
    *new_options = base_options;
904
    return s;
L
Lei Jin 已提交
905
  }
906 907
  return GetColumnFamilyOptionsFromMap(config_options, base_options, opts_map,
                                       new_options);
L
Lei Jin 已提交
908 909
}

910
Status GetDBOptionsFromMap(
L
Lei Jin 已提交
911 912
    const DBOptions& base_options,
    const std::unordered_map<std::string, std::string>& opts_map,
913 914
    DBOptions* new_options, bool input_strings_escaped,
    bool ignore_unknown_options) {
915 916 917 918 919 920 921 922 923 924 925 926 927
  ConfigOptions config_options;
  config_options.input_strings_escaped = input_strings_escaped;
  config_options.ignore_unknown_options = ignore_unknown_options;
  return GetDBOptionsFromMap(config_options, base_options, opts_map,
                             new_options);
}

Status GetDBOptionsFromMap(
    const ConfigOptions& config_options, const DBOptions& base_options,
    const std::unordered_map<std::string, std::string>& opts_map,
    DBOptions* new_options) {
  return GetDBOptionsFromMapInternal(config_options, base_options, opts_map,
                                     new_options, nullptr);
928 929 930
}

Status GetDBOptionsFromMapInternal(
931
    const ConfigOptions& config_options, const DBOptions& base_options,
932
    const std::unordered_map<std::string, std::string>& opts_map,
933 934
    DBOptions* new_options,
    std::vector<std::string>* unsupported_options_names) {
L
Lei Jin 已提交
935 936
  assert(new_options);
  *new_options = base_options;
937 938 939
  if (unsupported_options_names) {
    unsupported_options_names->clear();
  }
L
Lei Jin 已提交
940
  for (const auto& o : opts_map) {
941
    auto s = ParseDBOption(config_options, o.first, o.second, new_options);
942 943 944 945 946 947 948 949 950 951 952
    if (!s.ok()) {
      if (s.IsNotSupported()) {
        // If the deserialization of the specified option is not supported
        // and an output vector of unsupported_options is provided, then
        // we log the name of the unsupported option and proceed.
        if (unsupported_options_names != nullptr) {
          unsupported_options_names->push_back(o.first);
        }
        // Note that we still return Status::OK in such case to maintain
        // the backward compatibility in the old public API defined in
        // rocksdb/convenience.h
953 954
      } else if (s.IsInvalidArgument() &&
                 config_options.ignore_unknown_options) {
955
        continue;
956
      } else {
957 958
        // Restore "new_options" to the default "base_options".
        *new_options = base_options;
959 960
        return s;
      }
961 962
    }
  }
963
  return Status::OK();
964 965
}

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
Status GetDBOptionsFromString(const DBOptions& base_options,
                              const std::string& opts_str,
                              DBOptions* new_options) {
  ConfigOptions config_options;
  config_options.input_strings_escaped = false;
  config_options.ignore_unknown_options = false;

  return GetDBOptionsFromString(config_options, base_options, opts_str,
                                new_options);
}

Status GetDBOptionsFromString(const ConfigOptions& config_options,
                              const DBOptions& base_options,
                              const std::string& opts_str,
                              DBOptions* new_options) {
L
Lei Jin 已提交
981
  std::unordered_map<std::string, std::string> opts_map;
982 983
  Status s = StringToMap(opts_str, &opts_map);
  if (!s.ok()) {
984
    *new_options = base_options;
985
    return s;
L
Lei Jin 已提交
986
  }
987 988
  return GetDBOptionsFromMap(config_options, base_options, opts_map,
                             new_options);
L
Lei Jin 已提交
989 990
}

991 992
Status GetOptionsFromString(const Options& base_options,
                            const std::string& opts_str, Options* new_options) {
993 994 995 996 997 998 999 1000 1001 1002 1003
  ConfigOptions config_options;
  config_options.input_strings_escaped = false;
  config_options.ignore_unknown_options = false;

  return GetOptionsFromString(config_options, base_options, opts_str,
                              new_options);
}

Status GetOptionsFromString(const ConfigOptions& config_options,
                            const Options& base_options,
                            const std::string& opts_str, Options* new_options) {
1004 1005 1006 1007 1008 1009 1010 1011
  std::unordered_map<std::string, std::string> opts_map;
  Status s = StringToMap(opts_str, &opts_map);
  if (!s.ok()) {
    return s;
  }
  DBOptions new_db_options(base_options);
  ColumnFamilyOptions new_cf_options(base_options);
  for (const auto& o : opts_map) {
1012 1013 1014 1015 1016
    if (ParseDBOption(config_options, o.first, o.second, &new_db_options)
            .ok()) {
    } else if (ParseColumnFamilyOption(config_options, o.first, o.second,
                                       &new_cf_options)
                   .ok()) {
1017 1018 1019 1020 1021 1022 1023 1024
    } else {
      return Status::InvalidArgument("Can't parse option " + o.first);
    }
  }
  *new_options = Options(new_db_options, new_cf_options);
  return Status::OK();
}

1025 1026 1027
Status GetTableFactoryFromMap(
    const std::string& factory_name,
    const std::unordered_map<std::string, std::string>& opt_map,
1028
    std::shared_ptr<TableFactory>* table_factory, bool ignore_unknown_options) {
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
  ConfigOptions
      config_options;  // Use default for escaped(true) and check (exact)
  config_options.ignore_unknown_options = ignore_unknown_options;
  return GetTableFactoryFromMap(config_options, factory_name, opt_map,
                                table_factory);
}

Status GetTableFactoryFromMap(
    const ConfigOptions& config_options, const std::string& factory_name,
    const std::unordered_map<std::string, std::string>& opt_map,
    std::shared_ptr<TableFactory>* table_factory) {
1040 1041 1042
  Status s;
  if (factory_name == BlockBasedTableFactory().Name()) {
    BlockBasedTableOptions bbt_opt;
1043 1044
    s = GetBlockBasedTableOptionsFromMap(
        config_options, BlockBasedTableOptions(), opt_map, &bbt_opt);
1045 1046 1047 1048
    if (!s.ok()) {
      return s;
    }
    table_factory->reset(new BlockBasedTableFactory(bbt_opt));
1049
    return s;
1050 1051
  } else if (factory_name == PlainTableFactory().Name()) {
    PlainTableOptions pt_opt;
1052 1053
    s = GetPlainTableOptionsFromMap(config_options, PlainTableOptions(),
                                    opt_map, &pt_opt);
1054 1055 1056 1057
    if (!s.ok()) {
      return s;
    }
    table_factory->reset(new PlainTableFactory(pt_opt));
1058
    return s;
1059 1060 1061 1062
  }
  // Return OK for not supported table factories as TableFactory
  // Deserialization is optional.
  table_factory->reset();
1063
  return s;
1064 1065
}

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
std::unordered_map<std::string, EncodingType>
    OptionsHelper::encoding_type_string_map = {{"kPlain", kPlain},
                                               {"kPrefix", kPrefix}};

std::unordered_map<std::string, CompactionStyle>
    OptionsHelper::compaction_style_string_map = {
        {"kCompactionStyleLevel", kCompactionStyleLevel},
        {"kCompactionStyleUniversal", kCompactionStyleUniversal},
        {"kCompactionStyleFIFO", kCompactionStyleFIFO},
        {"kCompactionStyleNone", kCompactionStyleNone}};

std::unordered_map<std::string, CompactionPri>
    OptionsHelper::compaction_pri_string_map = {
        {"kByCompensatedSize", kByCompensatedSize},
        {"kOldestLargestSeqFirst", kOldestLargestSeqFirst},
        {"kOldestSmallestSeqFirst", kOldestSmallestSeqFirst},
        {"kMinOverlappingRatio", kMinOverlappingRatio}};

1084 1085 1086 1087 1088
std::unordered_map<std::string, CompactionStopStyle>
    OptionsHelper::compaction_stop_style_string_map = {
        {"kCompactionStopStyleSimilarSize", kCompactionStopStyleSimilarSize},
        {"kCompactionStopStyleTotalSize", kCompactionStopStyleTotalSize}};

1089 1090 1091 1092
Status OptionTypeInfo::Parse(const ConfigOptions& config_options,
                             const std::string& opt_name,
                             const std::string& opt_value,
                             char* opt_addr) const {
1093 1094 1095 1096 1097 1098
  if (IsDeprecated()) {
    return Status::OK();
  }
  try {
    if (opt_addr == nullptr) {
      return Status::NotFound("Could not find option: ", opt_name);
1099 1100 1101
    } else if (parse_func_ != nullptr) {
      return parse_func_(config_options, opt_name, opt_value, opt_addr);
    } else if (ParseOptionHelper(opt_addr, type_, opt_value)) {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
      return Status::OK();
    } else if (IsByName()) {
      return Status::NotSupported("Deserializing the option " + opt_name +
                                  " is not supported");
    } else {
      return Status::InvalidArgument("Error parsing:", opt_name);
    }
  } catch (std::exception& e) {
    return Status::InvalidArgument("Error parsing " + opt_name + ":" +
                                   std::string(e.what()));
  }
}

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
Status OptionTypeInfo::ParseStruct(
    const ConfigOptions& config_options, const std::string& struct_name,
    const std::unordered_map<std::string, OptionTypeInfo>* struct_map,
    const std::string& opt_name, const std::string& opt_value, char* opt_addr) {
  assert(struct_map);
  Status status;
  if (opt_name == struct_name || EndsWith(opt_name, "." + struct_name)) {
    // This option represents the entire struct
    std::unordered_map<std::string, std::string> opt_map;
    status = StringToMap(opt_value, &opt_map);
    if (status.ok()) {
      for (const auto& map_iter : opt_map) {
        const auto iter = struct_map->find(map_iter.first);
        if (iter != struct_map->end()) {
          status = iter->second.Parse(config_options, map_iter.first,
                                      map_iter.second,
                                      opt_addr + iter->second.offset_);
        } else {
          return Status::InvalidArgument("Unrecognized option: ",
                                         struct_name + "." + map_iter.first);
        }
      }
    }
  } else if (StartsWith(opt_name, struct_name + ".")) {
    // This option represents a nested field in the struct (e.g, struct.field)
    std::string elem_name;
    const auto opt_info =
        Find(opt_name.substr(struct_name.size() + 1), *struct_map, &elem_name);
    if (opt_info != nullptr) {
      status = opt_info->Parse(config_options, elem_name, opt_value,
                               opt_addr + opt_info->offset_);
    } else {
      status = Status::InvalidArgument("Unrecognized option: ", opt_name);
    }
  } else {
    // This option represents a field in the struct (e.g. field)
    std::string elem_name;
    const auto opt_info = Find(opt_name, *struct_map, &elem_name);
    if (opt_info != nullptr) {
      status = opt_info->Parse(config_options, elem_name, opt_value,
                               opt_addr + opt_info->offset_);
    } else {
      status = Status::InvalidArgument("Unrecognized option: ",
                                       struct_name + "." + opt_name);
    }
  }
  return status;
}

Status OptionTypeInfo::Serialize(const ConfigOptions& config_options,
                                 const std::string& opt_name,
                                 const char* opt_addr,
                                 std::string* opt_value) const {
1168 1169
  // If the option is no longer used in rocksdb and marked as deprecated,
  // we skip it in the serialization.
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
  if (opt_addr != nullptr && ShouldSerialize()) {
    if (serialize_func_ != nullptr) {
      return serialize_func_(config_options, opt_name, opt_addr, opt_value);
    } else if (!SerializeSingleOptionHelper(opt_addr, type_, opt_value)) {
      return Status::InvalidArgument("Cannot serialize option: ", opt_name);
    }
  }
  return Status::OK();
}

Status OptionTypeInfo::SerializeStruct(
    const ConfigOptions& config_options, const std::string& struct_name,
    const std::unordered_map<std::string, OptionTypeInfo>* struct_map,
    const std::string& opt_name, const char* opt_addr, std::string* value) {
  assert(struct_map);
  Status status;
  if (EndsWith(opt_name, struct_name)) {
    // We are going to write the struct as "{ prop1=value1; prop2=value2;}.
    // Set the delimiter to ";" so that the everything will be on one line.
    ConfigOptions embedded = config_options;
    embedded.delimiter = ";";

    // This option represents the entire struct
    std::string result;
    for (const auto& iter : *struct_map) {
      std::string single;
      const auto& opt_info = iter.second;
      if (opt_info.ShouldSerialize()) {
        status = opt_info.Serialize(embedded, iter.first,
                                    opt_addr + opt_info.offset_, &single);
        if (!status.ok()) {
          return status;
        } else {
          result.append(iter.first + "=" + single + embedded.delimiter);
        }
      }
    }
    *value = "{" + result + "}";
  } else if (StartsWith(opt_name, struct_name + ".")) {
    // This option represents a nested field in the struct (e.g, struct.field)
    std::string elem_name;
    const auto opt_info =
        Find(opt_name.substr(struct_name.size() + 1), *struct_map, &elem_name);
    if (opt_info != nullptr) {
      status = opt_info->Serialize(config_options, elem_name,
                                   opt_addr + opt_info->offset_, value);
    } else {
      status = Status::InvalidArgument("Unrecognized option: ", opt_name);
    }
1219
  } else {
1220 1221 1222 1223
    // This option represents a field in the struct (e.g. field)
    std::string elem_name;
    const auto opt_info = Find(opt_name, *struct_map, &elem_name);
    if (opt_info == nullptr) {
1224
      status = Status::InvalidArgument("Unrecognized option: ", opt_name);
1225
    } else if (opt_info->ShouldSerialize()) {
1226 1227
      status = opt_info->Serialize(config_options, opt_name + "." + elem_name,
                                   opt_addr + opt_info->offset_, value);
1228
    }
1229
  }
1230
  return status;
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
}

template <typename T>
bool IsOptionEqual(const char* offset1, const char* offset2) {
  return (*reinterpret_cast<const T*>(offset1) ==
          *reinterpret_cast<const T*>(offset2));
}

static bool AreEqualDoubles(const double a, const double b) {
  return (fabs(a - b) < 0.00001);
}

static bool AreOptionsEqual(OptionType type, const char* this_offset,
                            const char* that_offset) {
  switch (type) {
    case OptionType::kBoolean:
      return IsOptionEqual<bool>(this_offset, that_offset);
    case OptionType::kInt:
      return IsOptionEqual<int>(this_offset, that_offset);
    case OptionType::kUInt:
      return IsOptionEqual<unsigned int>(this_offset, that_offset);
    case OptionType::kInt32T:
      return IsOptionEqual<int32_t>(this_offset, that_offset);
    case OptionType::kInt64T: {
      int64_t v1, v2;
      GetUnaligned(reinterpret_cast<const int64_t*>(this_offset), &v1);
      GetUnaligned(reinterpret_cast<const int64_t*>(that_offset), &v2);
      return (v1 == v2);
    }
    case OptionType::kVectorInt:
      return IsOptionEqual<std::vector<int> >(this_offset, that_offset);
    case OptionType::kUInt32T:
      return IsOptionEqual<uint32_t>(this_offset, that_offset);
    case OptionType::kUInt64T: {
      uint64_t v1, v2;
      GetUnaligned(reinterpret_cast<const uint64_t*>(this_offset), &v1);
      GetUnaligned(reinterpret_cast<const uint64_t*>(that_offset), &v2);
      return (v1 == v2);
    }
    case OptionType::kSizeT: {
      size_t v1, v2;
      GetUnaligned(reinterpret_cast<const size_t*>(this_offset), &v1);
      GetUnaligned(reinterpret_cast<const size_t*>(that_offset), &v2);
      return (v1 == v2);
    }
    case OptionType::kString:
      return IsOptionEqual<std::string>(this_offset, that_offset);
    case OptionType::kDouble:
      return AreEqualDoubles(*reinterpret_cast<const double*>(this_offset),
                             *reinterpret_cast<const double*>(that_offset));
    case OptionType::kVectorCompressionType:
      return IsOptionEqual<std::vector<CompressionType> >(this_offset,
                                                          that_offset);
    case OptionType::kCompactionStyle:
      return IsOptionEqual<CompactionStyle>(this_offset, that_offset);
    case OptionType::kCompactionStopStyle:
      return IsOptionEqual<CompactionStopStyle>(this_offset, that_offset);
    case OptionType::kCompactionPri:
      return IsOptionEqual<CompactionPri>(this_offset, that_offset);
    case OptionType::kCompressionType:
      return IsOptionEqual<CompressionType>(this_offset, that_offset);
    case OptionType::kChecksumType:
      return IsOptionEqual<ChecksumType>(this_offset, that_offset);
    case OptionType::kEncodingType:
      return IsOptionEqual<EncodingType>(this_offset, that_offset);
    default:
      return false;
  }  // End switch
}

1301 1302 1303 1304
bool OptionTypeInfo::AreEqual(const ConfigOptions& config_options,
                              const std::string& opt_name,
                              const char* this_addr, const char* that_addr,
                              std::string* mismatch) const {
1305 1306 1307 1308 1309 1310 1311
  if (!config_options.IsCheckEnabled(GetSanityLevel())) {
    return true;  // If the sanity level is not being checked, skip it
  }
  if (this_addr == nullptr || that_addr == nullptr) {
    if (this_addr == that_addr) {
      return true;
    }
1312 1313 1314
  } else if (equals_func_ != nullptr) {
    if (equals_func_(config_options, opt_name, this_addr, that_addr,
                     mismatch)) {
1315 1316
      return true;
    }
1317
  } else if (AreOptionsEqual(type_, this_addr, that_addr)) {
1318 1319 1320 1321 1322 1323 1324 1325
    return true;
  }
  if (mismatch->empty()) {
    *mismatch = opt_name;
  }
  return false;
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
bool OptionTypeInfo::StructsAreEqual(
    const ConfigOptions& config_options, const std::string& struct_name,
    const std::unordered_map<std::string, OptionTypeInfo>* struct_map,
    const std::string& opt_name, const char* this_addr, const char* that_addr,
    std::string* mismatch) {
  assert(struct_map);
  bool matches = true;
  std::string result;
  if (EndsWith(opt_name, struct_name)) {
    // This option represents the entire struct
    for (const auto& iter : *struct_map) {
      const auto& opt_info = iter.second;

      matches = opt_info.AreEqual(config_options, iter.first,
                                  this_addr + opt_info.offset_,
                                  that_addr + opt_info.offset_, &result);
      if (!matches) {
        *mismatch = struct_name + "." + result;
        return false;
      }
    }
  } else if (StartsWith(opt_name, struct_name + ".")) {
    // This option represents a nested field in the struct (e.g, struct.field)
    std::string elem_name;
    const auto opt_info =
        Find(opt_name.substr(struct_name.size() + 1), *struct_map, &elem_name);
    assert(opt_info);
    if (opt_info == nullptr) {
      *mismatch = opt_name;
      matches = false;
    } else if (!opt_info->AreEqual(config_options, elem_name,
                                   this_addr + opt_info->offset_,
                                   that_addr + opt_info->offset_, &result)) {
      matches = false;
      *mismatch = struct_name + "." + result;
    }
  } else {
    // This option represents a field in the struct (e.g. field)
    std::string elem_name;
    const auto opt_info = Find(opt_name, *struct_map, &elem_name);
    assert(opt_info);
    if (opt_info == nullptr) {
      *mismatch = struct_name + "." + opt_name;
      matches = false;
    } else if (!opt_info->AreEqual(config_options, elem_name,
                                   this_addr + opt_info->offset_,
                                   that_addr + opt_info->offset_, &result)) {
      matches = false;
      *mismatch = struct_name + "." + result;
    }
  }
  return matches;
}

bool OptionTypeInfo::AreEqualByName(const ConfigOptions& config_options,
                                    const std::string& opt_name,
                                    const char* this_addr,
                                    const char* that_addr) const {
1384 1385
  if (IsByName()) {
    std::string that_value;
1386 1387
    if (Serialize(config_options, opt_name, that_addr, &that_value).ok()) {
      return AreEqualByName(config_options, opt_name, this_addr, that_value);
1388 1389 1390 1391 1392
    }
  }
  return false;
}

1393 1394 1395 1396
bool OptionTypeInfo::AreEqualByName(const ConfigOptions& config_options,
                                    const std::string& opt_name,
                                    const char* opt_addr,
                                    const std::string& that_value) const {
1397 1398 1399
  std::string this_value;
  if (!IsByName()) {
    return false;
1400
  } else if (!Serialize(config_options, opt_name, opt_addr, &this_value).ok()) {
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    return false;
  } else if (IsEnabled(OptionVerificationType::kByNameAllowFromNull)) {
    if (that_value == kNullptrString) {
      return true;
    }
  } else if (IsEnabled(OptionVerificationType::kByNameAllowNull)) {
    if (that_value == kNullptrString) {
      return true;
    }
  }
  return (this_value == that_value);
}
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

const OptionTypeInfo* OptionTypeInfo::Find(
    const std::string& opt_name,
    const std::unordered_map<std::string, OptionTypeInfo>& opt_map,
    std::string* elem_name) {
  const auto iter = opt_map.find(opt_name);  // Look up the value in the map
  if (iter != opt_map.end()) {               // Found the option in the map
    *elem_name = opt_name;                   // Return the name
    return &(iter->second);  // Return the contents of the iterator
  } else {
    auto idx = opt_name.find(".");              // Look for a separator
    if (idx > 0 && idx != std::string::npos) {  // We found a separator
      auto siter =
          opt_map.find(opt_name.substr(0, idx));  // Look for the short name
      if (siter != opt_map.end()) {               // We found the short name
        if (siter->second.IsStruct()) {           // If the object is a struct
          *elem_name = opt_name.substr(idx + 1);  // Return the rest
          return &(siter->second);  // Return the contents of the iterator
        }
      }
    }
  }
  return nullptr;
}
1437
#endif  // !ROCKSDB_LITE
1438

1439
}  // namespace ROCKSDB_NAMESPACE