options_test.cc 77.3 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 6 7 8 9
//
// 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.

L
liuhuahang 已提交
10
#ifndef __STDC_FORMAT_MACROS
11
#define __STDC_FORMAT_MACROS
L
liuhuahang 已提交
12 13
#endif

14
#include <cctype>
15
#include <cstring>
16
#include <unordered_map>
17 18
#include <inttypes.h>

19 20
#include "cache/lru_cache.h"
#include "cache/sharded_cache.h"
21 22 23
#include "options/options_helper.h"
#include "options/options_parser.h"
#include "options/options_sanity_check.h"
Z
Zhongyi Xie 已提交
24
#include "port/port.h"
25
#include "rocksdb/cache.h"
A
agiardullo 已提交
26
#include "rocksdb/convenience.h"
27
#include "rocksdb/memtablerep.h"
28
#include "rocksdb/utilities/leveldb_options.h"
29
#include "rocksdb/utilities/object_registry.h"
30
#include "util/random.h"
A
Andrew Kryczka 已提交
31
#include "util/stderr_logger.h"
32
#include "util/string_util.h"
33
#include "util/testharness.h"
34
#include "util/testutil.h"
35
#include "utilities/merge_operators/bytesxor.h"
36

I
Igor Canadi 已提交
37 38 39
#ifndef GFLAGS
bool FLAGS_enable_print = false;
#else
A
Andrew Kryczka 已提交
40 41
#include "util/gflags_compat.h"
using GFLAGS_NAMESPACE::ParseCommandLineFlags;
42
DEFINE_bool(enable_print, false, "Print options generated to console.");
I
Igor Canadi 已提交
43
#endif  // GFLAGS
44 45 46

namespace rocksdb {

47 48
class OptionsTest : public testing::Test {};

49
#ifndef ROCKSDB_LITE  // GetOptionsFromMap is not supported in ROCKSDB_LITE
I
Igor Sugak 已提交
50
TEST_F(OptionsTest, GetOptionsFromMapTest) {
L
Lei Jin 已提交
51
  std::unordered_map<std::string, std::string> cf_options_map = {
52 53 54
      {"write_buffer_size", "1"},
      {"max_write_buffer_number", "2"},
      {"min_write_buffer_number_to_merge", "3"},
55
      {"max_write_buffer_number_to_maintain", "99"},
56 57 58 59 60 61 62
      {"compression", "kSnappyCompression"},
      {"compression_per_level",
       "kNoCompression:"
       "kSnappyCompression:"
       "kZlibCompression:"
       "kBZip2Compression:"
       "kLZ4Compression:"
63
       "kLZ4HCCompression:"
64
       "kXpressCompression:"
S
sdong 已提交
65
       "kZSTD:"
66
       "kZSTDNotFinalCompression"},
67
      {"bottommost_compression", "kLZ4Compression"},
68 69
      {"bottommost_compression_opts", "5:6:7:8:9:true"},
      {"compression_opts", "4:5:6:7:8:true"},
70
      {"num_levels", "8"},
71 72 73 74 75 76 77
      {"level0_file_num_compaction_trigger", "8"},
      {"level0_slowdown_writes_trigger", "9"},
      {"level0_stop_writes_trigger", "10"},
      {"target_file_size_base", "12"},
      {"target_file_size_multiplier", "13"},
      {"max_bytes_for_level_base", "14"},
      {"level_compaction_dynamic_level_bytes", "true"},
78
      {"max_bytes_for_level_multiplier", "15.0"},
79
      {"max_bytes_for_level_multiplier_additional", "16:17:18"},
80
      {"max_compaction_bytes", "21"},
81 82
      {"soft_rate_limit", "1.1"},
      {"hard_rate_limit", "2.1"},
83
      {"hard_pending_compaction_bytes_limit", "211"},
84 85 86
      {"arena_block_size", "22"},
      {"disable_auto_compactions", "true"},
      {"compaction_style", "kCompactionStyleLevel"},
87
      {"compaction_pri", "kOldestSmallestSeqFirst"},
88 89 90 91
      {"verify_checksums_in_compaction", "false"},
      {"compaction_options_fifo", "23"},
      {"max_sequential_skip_in_iterations", "24"},
      {"inplace_update_support", "true"},
92 93
      {"report_bg_io_stats", "true"},
      {"compaction_measure_io_stats", "false"},
94
      {"inplace_update_num_locks", "25"},
95
      {"memtable_prefix_bloom_size_ratio", "0.26"},
96
      {"memtable_whole_key_filtering", "true"},
97
      {"memtable_huge_page_size", "28"},
98 99 100 101 102
      {"bloom_locality", "29"},
      {"max_successive_merges", "30"},
      {"min_partial_merge_operands", "31"},
      {"prefix_extractor", "fixed:31"},
      {"optimize_filters_for_hits", "true"},
L
Lei Jin 已提交
103 104 105
  };

  std::unordered_map<std::string, std::string> db_options_map = {
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
      {"create_if_missing", "false"},
      {"create_missing_column_families", "true"},
      {"error_if_exists", "false"},
      {"paranoid_checks", "true"},
      {"max_open_files", "32"},
      {"max_total_wal_size", "33"},
      {"use_fsync", "true"},
      {"db_log_dir", "/db_log_dir"},
      {"wal_dir", "/wal_dir"},
      {"delete_obsolete_files_period_micros", "34"},
      {"max_background_compactions", "35"},
      {"max_background_flushes", "36"},
      {"max_log_file_size", "37"},
      {"log_file_time_to_roll", "38"},
      {"keep_log_file_num", "39"},
121
      {"recycle_log_file_num", "5"},
122 123 124 125 126 127 128
      {"max_manifest_file_size", "40"},
      {"table_cache_numshardbits", "41"},
      {"WAL_ttl_seconds", "43"},
      {"WAL_size_limit_MB", "44"},
      {"manifest_preallocation_size", "45"},
      {"allow_mmap_reads", "true"},
      {"allow_mmap_writes", "false"},
A
Aaron Gao 已提交
129
      {"use_direct_reads", "false"},
130
      {"use_direct_io_for_flush_and_compaction", "false"},
131 132 133
      {"is_fd_close_on_exec", "true"},
      {"skip_log_error_on_recovery", "false"},
      {"stats_dump_period_sec", "46"},
134 135
      {"stats_persist_period_sec", "57"},
      {"stats_history_buffer_size", "69"},
136 137 138
      {"advise_random_on_open", "true"},
      {"use_adaptive_mutex", "false"},
      {"new_table_reader_for_compaction_inputs", "true"},
139
      {"compaction_readahead_size", "100"},
S
sdong 已提交
140
      {"random_access_max_buffer_size", "3145728"},
141
      {"writable_file_max_buffer_size", "314159"},
142
      {"bytes_per_sync", "47"},
143
      {"wal_bytes_per_sync", "48"},
144
      {"strict_bytes_per_sync", "true"},
145
  };
146

L
Lei Jin 已提交
147 148
  ColumnFamilyOptions base_cf_opt;
  ColumnFamilyOptions new_cf_opt;
149 150
  ASSERT_OK(GetColumnFamilyOptionsFromMap(
            base_cf_opt, cf_options_map, &new_cf_opt));
L
Lei Jin 已提交
151 152 153
  ASSERT_EQ(new_cf_opt.write_buffer_size, 1U);
  ASSERT_EQ(new_cf_opt.max_write_buffer_number, 2);
  ASSERT_EQ(new_cf_opt.min_write_buffer_number_to_merge, 3);
154
  ASSERT_EQ(new_cf_opt.max_write_buffer_number_to_maintain, 99);
L
Lei Jin 已提交
155
  ASSERT_EQ(new_cf_opt.compression, kSnappyCompression);
S
sdong 已提交
156
  ASSERT_EQ(new_cf_opt.compression_per_level.size(), 9U);
L
Lei Jin 已提交
157 158 159 160 161 162
  ASSERT_EQ(new_cf_opt.compression_per_level[0], kNoCompression);
  ASSERT_EQ(new_cf_opt.compression_per_level[1], kSnappyCompression);
  ASSERT_EQ(new_cf_opt.compression_per_level[2], kZlibCompression);
  ASSERT_EQ(new_cf_opt.compression_per_level[3], kBZip2Compression);
  ASSERT_EQ(new_cf_opt.compression_per_level[4], kLZ4Compression);
  ASSERT_EQ(new_cf_opt.compression_per_level[5], kLZ4HCCompression);
163
  ASSERT_EQ(new_cf_opt.compression_per_level[6], kXpressCompression);
S
sdong 已提交
164 165
  ASSERT_EQ(new_cf_opt.compression_per_level[7], kZSTD);
  ASSERT_EQ(new_cf_opt.compression_per_level[8], kZSTDNotFinalCompression);
L
Lei Jin 已提交
166 167 168
  ASSERT_EQ(new_cf_opt.compression_opts.window_bits, 4);
  ASSERT_EQ(new_cf_opt.compression_opts.level, 5);
  ASSERT_EQ(new_cf_opt.compression_opts.strategy, 6);
169
  ASSERT_EQ(new_cf_opt.compression_opts.max_dict_bytes, 7);
170 171
  ASSERT_EQ(new_cf_opt.compression_opts.zstd_max_train_bytes, 8);
  ASSERT_EQ(new_cf_opt.compression_opts.enabled, true);
172
  ASSERT_EQ(new_cf_opt.bottommost_compression, kLZ4Compression);
173 174 175 176 177 178
  ASSERT_EQ(new_cf_opt.bottommost_compression_opts.window_bits, 5);
  ASSERT_EQ(new_cf_opt.bottommost_compression_opts.level, 6);
  ASSERT_EQ(new_cf_opt.bottommost_compression_opts.strategy, 7);
  ASSERT_EQ(new_cf_opt.bottommost_compression_opts.max_dict_bytes, 8);
  ASSERT_EQ(new_cf_opt.bottommost_compression_opts.zstd_max_train_bytes, 9);
  ASSERT_EQ(new_cf_opt.bottommost_compression_opts.enabled, true);
179
  ASSERT_EQ(new_cf_opt.num_levels, 8);
L
Lei Jin 已提交
180 181 182 183 184 185
  ASSERT_EQ(new_cf_opt.level0_file_num_compaction_trigger, 8);
  ASSERT_EQ(new_cf_opt.level0_slowdown_writes_trigger, 9);
  ASSERT_EQ(new_cf_opt.level0_stop_writes_trigger, 10);
  ASSERT_EQ(new_cf_opt.target_file_size_base, static_cast<uint64_t>(12));
  ASSERT_EQ(new_cf_opt.target_file_size_multiplier, 13);
  ASSERT_EQ(new_cf_opt.max_bytes_for_level_base, 14U);
186
  ASSERT_EQ(new_cf_opt.level_compaction_dynamic_level_bytes, true);
187
  ASSERT_EQ(new_cf_opt.max_bytes_for_level_multiplier, 15.0);
L
Lei Jin 已提交
188 189 190 191
  ASSERT_EQ(new_cf_opt.max_bytes_for_level_multiplier_additional.size(), 3U);
  ASSERT_EQ(new_cf_opt.max_bytes_for_level_multiplier_additional[0], 16);
  ASSERT_EQ(new_cf_opt.max_bytes_for_level_multiplier_additional[1], 17);
  ASSERT_EQ(new_cf_opt.max_bytes_for_level_multiplier_additional[2], 18);
192
  ASSERT_EQ(new_cf_opt.max_compaction_bytes, 21);
193
  ASSERT_EQ(new_cf_opt.hard_pending_compaction_bytes_limit, 211);
L
Lei Jin 已提交
194 195 196
  ASSERT_EQ(new_cf_opt.arena_block_size, 22U);
  ASSERT_EQ(new_cf_opt.disable_auto_compactions, true);
  ASSERT_EQ(new_cf_opt.compaction_style, kCompactionStyleLevel);
197
  ASSERT_EQ(new_cf_opt.compaction_pri, kOldestSmallestSeqFirst);
L
Lei Jin 已提交
198
  ASSERT_EQ(new_cf_opt.compaction_options_fifo.max_table_files_size,
I
Igor Canadi 已提交
199
            static_cast<uint64_t>(23));
L
Lei Jin 已提交
200
  ASSERT_EQ(new_cf_opt.max_sequential_skip_in_iterations,
I
Igor Canadi 已提交
201
            static_cast<uint64_t>(24));
L
Lei Jin 已提交
202 203
  ASSERT_EQ(new_cf_opt.inplace_update_support, true);
  ASSERT_EQ(new_cf_opt.inplace_update_num_locks, 25U);
204
  ASSERT_EQ(new_cf_opt.memtable_prefix_bloom_size_ratio, 0.26);
205
  ASSERT_EQ(new_cf_opt.memtable_whole_key_filtering, true);
206
  ASSERT_EQ(new_cf_opt.memtable_huge_page_size, 28U);
L
Lei Jin 已提交
207 208
  ASSERT_EQ(new_cf_opt.bloom_locality, 29U);
  ASSERT_EQ(new_cf_opt.max_successive_merges, 30U);
209
  ASSERT_TRUE(new_cf_opt.prefix_extractor != nullptr);
210
  ASSERT_EQ(new_cf_opt.optimize_filters_for_hits, true);
211 212
  ASSERT_EQ(std::string(new_cf_opt.prefix_extractor->Name()),
            "rocksdb.FixedPrefix.31");
L
Lei Jin 已提交
213 214

  cf_options_map["write_buffer_size"] = "hello";
215 216
  ASSERT_NOK(GetColumnFamilyOptionsFromMap(
             base_cf_opt, cf_options_map, &new_cf_opt));
217 218
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

L
Lei Jin 已提交
219
  cf_options_map["write_buffer_size"] = "1";
220 221
  ASSERT_OK(GetColumnFamilyOptionsFromMap(
            base_cf_opt, cf_options_map, &new_cf_opt));
222

223
  cf_options_map["unknown_option"] = "1";
224 225
  ASSERT_NOK(GetColumnFamilyOptionsFromMap(
             base_cf_opt, cf_options_map, &new_cf_opt));
226
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));
L
Lei Jin 已提交
227

228 229 230 231 232 233 234 235 236 237 238
  ASSERT_OK(GetColumnFamilyOptionsFromMap(base_cf_opt, cf_options_map,
                                          &new_cf_opt,
                                          false, /* input_strings_escaped  */
                                          true /* ignore_unknown_options */));
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(
      base_cf_opt, new_cf_opt, nullptr, /* new_opt_map */
      kSanityLevelLooselyCompatible /* from CheckOptionsCompatibility*/));
  ASSERT_NOK(RocksDBOptionsParser::VerifyCFOptions(
      base_cf_opt, new_cf_opt, nullptr, /* new_opt_map */
      kSanityLevelExactMatch /* default for VerifyCFOptions */));

L
Lei Jin 已提交
239 240
  DBOptions base_db_opt;
  DBOptions new_db_opt;
241
  ASSERT_OK(GetDBOptionsFromMap(base_db_opt, db_options_map, &new_db_opt));
L
Lei Jin 已提交
242 243 244 245 246 247 248 249 250 251
  ASSERT_EQ(new_db_opt.create_if_missing, false);
  ASSERT_EQ(new_db_opt.create_missing_column_families, true);
  ASSERT_EQ(new_db_opt.error_if_exists, false);
  ASSERT_EQ(new_db_opt.paranoid_checks, true);
  ASSERT_EQ(new_db_opt.max_open_files, 32);
  ASSERT_EQ(new_db_opt.max_total_wal_size, static_cast<uint64_t>(33));
  ASSERT_EQ(new_db_opt.use_fsync, true);
  ASSERT_EQ(new_db_opt.db_log_dir, "/db_log_dir");
  ASSERT_EQ(new_db_opt.wal_dir, "/wal_dir");
  ASSERT_EQ(new_db_opt.delete_obsolete_files_period_micros,
I
Igor Canadi 已提交
252
            static_cast<uint64_t>(34));
L
Lei Jin 已提交
253 254 255 256 257
  ASSERT_EQ(new_db_opt.max_background_compactions, 35);
  ASSERT_EQ(new_db_opt.max_background_flushes, 36);
  ASSERT_EQ(new_db_opt.max_log_file_size, 37U);
  ASSERT_EQ(new_db_opt.log_file_time_to_roll, 38U);
  ASSERT_EQ(new_db_opt.keep_log_file_num, 39U);
258
  ASSERT_EQ(new_db_opt.recycle_log_file_num, 5U);
L
Lei Jin 已提交
259 260 261 262 263 264 265
  ASSERT_EQ(new_db_opt.max_manifest_file_size, static_cast<uint64_t>(40));
  ASSERT_EQ(new_db_opt.table_cache_numshardbits, 41);
  ASSERT_EQ(new_db_opt.WAL_ttl_seconds, static_cast<uint64_t>(43));
  ASSERT_EQ(new_db_opt.WAL_size_limit_MB, static_cast<uint64_t>(44));
  ASSERT_EQ(new_db_opt.manifest_preallocation_size, 45U);
  ASSERT_EQ(new_db_opt.allow_mmap_reads, true);
  ASSERT_EQ(new_db_opt.allow_mmap_writes, false);
A
Aaron Gao 已提交
266
  ASSERT_EQ(new_db_opt.use_direct_reads, false);
267
  ASSERT_EQ(new_db_opt.use_direct_io_for_flush_and_compaction, false);
L
Lei Jin 已提交
268 269 270
  ASSERT_EQ(new_db_opt.is_fd_close_on_exec, true);
  ASSERT_EQ(new_db_opt.skip_log_error_on_recovery, false);
  ASSERT_EQ(new_db_opt.stats_dump_period_sec, 46U);
271 272
  ASSERT_EQ(new_db_opt.stats_persist_period_sec, 57U);
  ASSERT_EQ(new_db_opt.stats_history_buffer_size, 69U);
L
Lei Jin 已提交
273 274
  ASSERT_EQ(new_db_opt.advise_random_on_open, true);
  ASSERT_EQ(new_db_opt.use_adaptive_mutex, false);
275
  ASSERT_EQ(new_db_opt.new_table_reader_for_compaction_inputs, true);
276
  ASSERT_EQ(new_db_opt.compaction_readahead_size, 100);
277
  ASSERT_EQ(new_db_opt.random_access_max_buffer_size, 3145728);
278
  ASSERT_EQ(new_db_opt.writable_file_max_buffer_size, 314159);
L
Lei Jin 已提交
279
  ASSERT_EQ(new_db_opt.bytes_per_sync, static_cast<uint64_t>(47));
280
  ASSERT_EQ(new_db_opt.wal_bytes_per_sync, static_cast<uint64_t>(48));
281
  ASSERT_EQ(new_db_opt.strict_bytes_per_sync, true);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

  db_options_map["max_open_files"] = "hello";
  ASSERT_NOK(GetDBOptionsFromMap(base_db_opt, db_options_map, &new_db_opt));
  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(base_db_opt, new_db_opt));
  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(
      base_db_opt, new_db_opt, nullptr, /* new_opt_map */
      kSanityLevelLooselyCompatible /* from CheckOptionsCompatibility */));

  // unknow options should fail parsing without ignore_unknown_options = true
  db_options_map["unknown_db_option"] = "1";
  ASSERT_NOK(GetDBOptionsFromMap(base_db_opt, db_options_map, &new_db_opt));
  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(base_db_opt, new_db_opt));

  ASSERT_OK(GetDBOptionsFromMap(base_db_opt, db_options_map, &new_db_opt,
                                false, /* input_strings_escaped  */
                                true /* ignore_unknown_options */));
  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(
      base_db_opt, new_db_opt, nullptr, /* new_opt_map */
      kSanityLevelLooselyCompatible /* from CheckOptionsCompatibility */));
  ASSERT_NOK(RocksDBOptionsParser::VerifyDBOptions(
      base_db_opt, new_db_opt, nullptr, /* new_opt_mat */
      kSanityLevelExactMatch /* default for VerifyDBOptions */));
L
Lei Jin 已提交
304
}
305
#endif  // !ROCKSDB_LITE
306

307 308
#ifndef ROCKSDB_LITE  // GetColumnFamilyOptionsFromString is not supported in
                      // ROCKSDB_LITE
I
Igor Sugak 已提交
309
TEST_F(OptionsTest, GetColumnFamilyOptionsFromStringTest) {
L
Lei Jin 已提交
310 311
  ColumnFamilyOptions base_cf_opt;
  ColumnFamilyOptions new_cf_opt;
312 313 314 315
  base_cf_opt.table_factory.reset();
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt, "", &new_cf_opt));
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=5", &new_cf_opt));
316
  ASSERT_EQ(new_cf_opt.write_buffer_size, 5U);
317 318 319
  ASSERT_TRUE(new_cf_opt.table_factory == nullptr);
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=6;", &new_cf_opt));
320
  ASSERT_EQ(new_cf_opt.write_buffer_size, 6U);
321 322
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "  write_buffer_size =  7  ", &new_cf_opt));
323
  ASSERT_EQ(new_cf_opt.write_buffer_size, 7U);
324 325
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "  write_buffer_size =  8 ; ", &new_cf_opt));
326
  ASSERT_EQ(new_cf_opt.write_buffer_size, 8U);
327 328
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=9;max_write_buffer_number=10", &new_cf_opt));
329
  ASSERT_EQ(new_cf_opt.write_buffer_size, 9U);
L
Lei Jin 已提交
330
  ASSERT_EQ(new_cf_opt.max_write_buffer_number, 10);
331 332 333
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=11; max_write_buffer_number  =  12 ;",
            &new_cf_opt));
334
  ASSERT_EQ(new_cf_opt.write_buffer_size, 11U);
L
Lei Jin 已提交
335 336
  ASSERT_EQ(new_cf_opt.max_write_buffer_number, 12);
  // Wrong name "max_write_buffer_number_"
337 338
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=13;max_write_buffer_number_=14;",
L
Lei Jin 已提交
339
              &new_cf_opt));
340 341
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

342 343 344 345 346 347 348 349 350 351 352 353
  // Comparator from object registry
  std::string kCompName = "reverse_comp";
  static Registrar<const Comparator> test_reg_a(
      kCompName, [](const std::string& /*name*/,
                    std::unique_ptr<const Comparator>* /*comparator_guard*/) {
        return ReverseBytewiseComparator();
      });

  ASSERT_OK(GetColumnFamilyOptionsFromString(
      base_cf_opt, "comparator=" + kCompName + ";", &new_cf_opt));
  ASSERT_EQ(new_cf_opt.comparator, ReverseBytewiseComparator());

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
  // MergeOperator from object registry
  std::unique_ptr<BytesXOROperator> bxo(new BytesXOROperator());
  std::string kMoName = bxo->Name();
  static Registrar<std::shared_ptr<MergeOperator>> test_reg_b(
      kMoName, [](const std::string& /*name*/,
                  std::unique_ptr<std::shared_ptr<MergeOperator>>*
                      merge_operator_guard) {
        merge_operator_guard->reset(
            new std::shared_ptr<MergeOperator>(new BytesXOROperator()));
        return merge_operator_guard->get();
      });

  ASSERT_OK(GetColumnFamilyOptionsFromString(
      base_cf_opt, "merge_operator=" + kMoName + ";", &new_cf_opt));
  ASSERT_EQ(kMoName, std::string(new_cf_opt.merge_operator->Name()));

L
Lei Jin 已提交
370
  // Wrong key/value pair
371 372
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=13;max_write_buffer_number;", &new_cf_opt));
373 374
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

L
Lei Jin 已提交
375
  // Error Paring value
376 377
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=13;max_write_buffer_number=;", &new_cf_opt));
378 379
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

L
Lei Jin 已提交
380
  // Missing option name
381 382
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=13; =100;", &new_cf_opt));
383
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));
D
Dmitri Smirnov 已提交
384 385 386 387 388 389

  const int64_t kilo = 1024UL;
  const int64_t mega = 1024 * kilo;
  const int64_t giga = 1024 * mega;
  const int64_t tera = 1024 * giga;

390
  // Units (k)
391
  ASSERT_OK(GetColumnFamilyOptionsFromString(
I
Islam AbdelRahman 已提交
392 393
      base_cf_opt, "max_write_buffer_number=15K", &new_cf_opt));
  ASSERT_EQ(new_cf_opt.max_write_buffer_number, 15 * kilo);
394
  // Units (m)
395 396 397
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "max_write_buffer_number=16m;inplace_update_num_locks=17M",
            &new_cf_opt));
S
sdong 已提交
398 399
  ASSERT_EQ(new_cf_opt.max_write_buffer_number, 16 * mega);
  ASSERT_EQ(new_cf_opt.inplace_update_num_locks, 17 * mega);
400
  // Units (g)
401 402 403 404 405
  ASSERT_OK(GetColumnFamilyOptionsFromString(
      base_cf_opt,
      "write_buffer_size=18g;prefix_extractor=capped:8;"
      "arena_block_size=19G",
      &new_cf_opt));
D
Dmitri Smirnov 已提交
406

S
sdong 已提交
407 408
  ASSERT_EQ(new_cf_opt.write_buffer_size, 18 * giga);
  ASSERT_EQ(new_cf_opt.arena_block_size, 19 * giga);
409 410 411 412
  ASSERT_TRUE(new_cf_opt.prefix_extractor.get() != nullptr);
  std::string prefix_name(new_cf_opt.prefix_extractor->Name());
  ASSERT_EQ(prefix_name, "rocksdb.CappedPrefix.8");

413
  // Units (t)
414 415
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=20t;arena_block_size=21T", &new_cf_opt));
S
sdong 已提交
416 417
  ASSERT_EQ(new_cf_opt.write_buffer_size, 20 * tera);
  ASSERT_EQ(new_cf_opt.arena_block_size, 21 * tera);
418 419

  // Nested block based table options
H
hyunwoo 已提交
420
  // Empty
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=10;max_write_buffer_number=16;"
            "block_based_table_factory={};arena_block_size=1024",
            &new_cf_opt));
  ASSERT_TRUE(new_cf_opt.table_factory != nullptr);
  // Non-empty
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=10;max_write_buffer_number=16;"
            "block_based_table_factory={block_cache=1M;block_size=4;};"
            "arena_block_size=1024",
            &new_cf_opt));
  ASSERT_TRUE(new_cf_opt.table_factory != nullptr);
  // Last one
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=10;max_write_buffer_number=16;"
            "block_based_table_factory={block_cache=1M;block_size=4;}",
            &new_cf_opt));
  ASSERT_TRUE(new_cf_opt.table_factory != nullptr);
  // Mismatch curly braces
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=10;max_write_buffer_number=16;"
             "block_based_table_factory={{{block_size=4;};"
             "arena_block_size=1024",
             &new_cf_opt));
445 446
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

447 448 449 450 451 452
  // Unexpected chars after closing curly brace
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=10;max_write_buffer_number=16;"
             "block_based_table_factory={block_size=4;}};"
             "arena_block_size=1024",
             &new_cf_opt));
453 454
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

455 456 457 458 459
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=10;max_write_buffer_number=16;"
             "block_based_table_factory={block_size=4;}xdfa;"
             "arena_block_size=1024",
             &new_cf_opt));
460 461
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

462 463 464 465
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=10;max_write_buffer_number=16;"
             "block_based_table_factory={block_size=4;}xdfa",
             &new_cf_opt));
466 467
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

468 469 470 471 472
  // Invalid block based table option
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
             "write_buffer_size=10;max_write_buffer_number=16;"
             "block_based_table_factory={xx_block_size=4;}",
             &new_cf_opt));
473 474
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));

475 476 477 478 479 480
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
           "optimize_filters_for_hits=true",
           &new_cf_opt));
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "optimize_filters_for_hits=false",
            &new_cf_opt));
481

482 483 484
  ASSERT_NOK(GetColumnFamilyOptionsFromString(base_cf_opt,
              "optimize_filters_for_hits=junk",
              &new_cf_opt));
485
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opt, new_cf_opt));
486 487

  // Nested plain table options
H
hyunwoo 已提交
488
  // Empty
489 490 491 492 493
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=10;max_write_buffer_number=16;"
            "plain_table_factory={};arena_block_size=1024",
            &new_cf_opt));
  ASSERT_TRUE(new_cf_opt.table_factory != nullptr);
S
sdong 已提交
494
  ASSERT_EQ(std::string(new_cf_opt.table_factory->Name()), "PlainTable");
495 496 497 498 499 500 501
  // Non-empty
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=10;max_write_buffer_number=16;"
            "plain_table_factory={user_key_len=66;bloom_bits_per_key=20;};"
            "arena_block_size=1024",
            &new_cf_opt));
  ASSERT_TRUE(new_cf_opt.table_factory != nullptr);
S
sdong 已提交
502
  ASSERT_EQ(std::string(new_cf_opt.table_factory->Name()), "PlainTable");
503 504 505 506 507 508 509 510

  // memtable factory
  ASSERT_OK(GetColumnFamilyOptionsFromString(base_cf_opt,
            "write_buffer_size=10;max_write_buffer_number=16;"
            "memtable=skip_list:10;arena_block_size=1024",
            &new_cf_opt));
  ASSERT_TRUE(new_cf_opt.memtable_factory != nullptr);
  ASSERT_EQ(std::string(new_cf_opt.memtable_factory->Name()), "SkipListFactory");
511
}
512
#endif  // !ROCKSDB_LITE
513

514
#ifndef ROCKSDB_LITE  // GetBlockBasedTableOptionsFromString is not supported
I
Igor Sugak 已提交
515
TEST_F(OptionsTest, GetBlockBasedTableOptionsFromString) {
516 517 518 519 520 521 522 523
  BlockBasedTableOptions table_opt;
  BlockBasedTableOptions new_opt;
  // make sure default values are overwritten by something else
  ASSERT_OK(GetBlockBasedTableOptionsFromString(table_opt,
            "cache_index_and_filter_blocks=1;index_type=kHashSearch;"
            "checksum=kxxHash;hash_index_allow_collision=1;no_block_cache=1;"
            "block_cache=1M;block_cache_compressed=1k;block_size=1024;"
            "block_size_deviation=8;block_restart_interval=4;"
524
            "filter_policy=bloomfilter:4:true;whole_key_filtering=1;",
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
            &new_opt));
  ASSERT_TRUE(new_opt.cache_index_and_filter_blocks);
  ASSERT_EQ(new_opt.index_type, BlockBasedTableOptions::kHashSearch);
  ASSERT_EQ(new_opt.checksum, ChecksumType::kxxHash);
  ASSERT_TRUE(new_opt.hash_index_allow_collision);
  ASSERT_TRUE(new_opt.no_block_cache);
  ASSERT_TRUE(new_opt.block_cache != nullptr);
  ASSERT_EQ(new_opt.block_cache->GetCapacity(), 1024UL*1024UL);
  ASSERT_TRUE(new_opt.block_cache_compressed != nullptr);
  ASSERT_EQ(new_opt.block_cache_compressed->GetCapacity(), 1024UL);
  ASSERT_EQ(new_opt.block_size, 1024UL);
  ASSERT_EQ(new_opt.block_size_deviation, 8);
  ASSERT_EQ(new_opt.block_restart_interval, 4);
  ASSERT_TRUE(new_opt.filter_policy != nullptr);

  // unknown option
  ASSERT_NOK(GetBlockBasedTableOptionsFromString(table_opt,
             "cache_index_and_filter_blocks=1;index_type=kBinarySearch;"
             "bad_option=1",
             &new_opt));
545 546 547
  ASSERT_EQ(table_opt.cache_index_and_filter_blocks,
            new_opt.cache_index_and_filter_blocks);
  ASSERT_EQ(table_opt.index_type, new_opt.index_type);
548 549 550 551 552

  // unrecognized index type
  ASSERT_NOK(GetBlockBasedTableOptionsFromString(table_opt,
             "cache_index_and_filter_blocks=1;index_type=kBinarySearchXX",
             &new_opt));
553 554 555
  ASSERT_EQ(table_opt.cache_index_and_filter_blocks,
            new_opt.cache_index_and_filter_blocks);
  ASSERT_EQ(table_opt.index_type, new_opt.index_type);
556 557 558 559 560

  // unrecognized checksum type
  ASSERT_NOK(GetBlockBasedTableOptionsFromString(table_opt,
             "cache_index_and_filter_blocks=1;checksum=kxxHashXX",
             &new_opt));
561 562 563
  ASSERT_EQ(table_opt.cache_index_and_filter_blocks,
            new_opt.cache_index_and_filter_blocks);
  ASSERT_EQ(table_opt.index_type, new_opt.index_type);
564 565 566 567 568 569

  // unrecognized filter policy name
  ASSERT_NOK(GetBlockBasedTableOptionsFromString(table_opt,
             "cache_index_and_filter_blocks=1;"
             "filter_policy=bloomfilterxx:4:true",
             &new_opt));
570 571 572 573
  ASSERT_EQ(table_opt.cache_index_and_filter_blocks,
            new_opt.cache_index_and_filter_blocks);
  ASSERT_EQ(table_opt.filter_policy, new_opt.filter_policy);

574 575 576 577 578
  // unrecognized filter policy config
  ASSERT_NOK(GetBlockBasedTableOptionsFromString(table_opt,
             "cache_index_and_filter_blocks=1;"
             "filter_policy=bloomfilter:4",
             &new_opt));
579 580 581
  ASSERT_EQ(table_opt.cache_index_and_filter_blocks,
            new_opt.cache_index_and_filter_blocks);
  ASSERT_EQ(table_opt.filter_policy, new_opt.filter_policy);
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

  // Check block cache options are overwritten when specified
  // in new format as a struct.
  ASSERT_OK(GetBlockBasedTableOptionsFromString(table_opt,
             "block_cache={capacity=1M;num_shard_bits=4;"
             "strict_capacity_limit=true;high_pri_pool_ratio=0.5;};"
             "block_cache_compressed={capacity=1M;num_shard_bits=4;"
             "strict_capacity_limit=true;high_pri_pool_ratio=0.5;}",
             &new_opt));
  ASSERT_TRUE(new_opt.block_cache != nullptr);
  ASSERT_EQ(new_opt.block_cache->GetCapacity(), 1024UL*1024UL);
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache)->GetNumShardBits(), 4);
  ASSERT_EQ(new_opt.block_cache->HasStrictCapacityLimit(), true);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache)->GetHighPriPoolRatio(), 0.5);
  ASSERT_TRUE(new_opt.block_cache_compressed != nullptr);
  ASSERT_EQ(new_opt.block_cache_compressed->GetCapacity(), 1024UL*1024UL);
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache_compressed)->GetNumShardBits(), 4);
  ASSERT_EQ(new_opt.block_cache_compressed->HasStrictCapacityLimit(), true);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache_compressed)->GetHighPriPoolRatio(),
                0.5);

  // Set only block cache capacity. Check other values are
  // reset to default values.
  ASSERT_OK(GetBlockBasedTableOptionsFromString(table_opt,
             "block_cache={capacity=2M};"
             "block_cache_compressed={capacity=2M}",
             &new_opt));
  ASSERT_TRUE(new_opt.block_cache != nullptr);
  ASSERT_EQ(new_opt.block_cache->GetCapacity(), 2*1024UL*1024UL);
  // Default values
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache)->GetNumShardBits(),
                GetDefaultCacheShardBits(new_opt.block_cache->GetCapacity()));
  ASSERT_EQ(new_opt.block_cache->HasStrictCapacityLimit(), false);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache)->GetHighPriPoolRatio(), 0.0);
  ASSERT_TRUE(new_opt.block_cache_compressed != nullptr);
  ASSERT_EQ(new_opt.block_cache_compressed->GetCapacity(), 2*1024UL*1024UL);
  // Default values
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache_compressed)->GetNumShardBits(),
                GetDefaultCacheShardBits(
                    new_opt.block_cache_compressed->GetCapacity()));
  ASSERT_EQ(new_opt.block_cache_compressed->HasStrictCapacityLimit(), false);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache_compressed)->GetHighPriPoolRatio(),
                0.0);

  // Set couple of block cache options.
  ASSERT_OK(GetBlockBasedTableOptionsFromString(table_opt,
             "block_cache={num_shard_bits=5;high_pri_pool_ratio=0.5;};"
             "block_cache_compressed={num_shard_bits=5;"
             "high_pri_pool_ratio=0.5;}",
             &new_opt));
  ASSERT_EQ(new_opt.block_cache->GetCapacity(), 0);
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache)->GetNumShardBits(), 5);
  ASSERT_EQ(new_opt.block_cache->HasStrictCapacityLimit(), false);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache)->GetHighPriPoolRatio(), 0.5);
  ASSERT_TRUE(new_opt.block_cache_compressed != nullptr);
  ASSERT_EQ(new_opt.block_cache_compressed->GetCapacity(), 0);
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache_compressed)->GetNumShardBits(), 5);
  ASSERT_EQ(new_opt.block_cache_compressed->HasStrictCapacityLimit(), false);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache_compressed)->GetHighPriPoolRatio(),
                0.5);

  // Set couple of block cache options.
  ASSERT_OK(GetBlockBasedTableOptionsFromString(table_opt,
             "block_cache={capacity=1M;num_shard_bits=4;"
             "strict_capacity_limit=true;};"
             "block_cache_compressed={capacity=1M;num_shard_bits=4;"
             "strict_capacity_limit=true;}",
             &new_opt));
  ASSERT_TRUE(new_opt.block_cache != nullptr);
  ASSERT_EQ(new_opt.block_cache->GetCapacity(), 1024UL*1024UL);
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache)->GetNumShardBits(), 4);
  ASSERT_EQ(new_opt.block_cache->HasStrictCapacityLimit(), true);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache)->GetHighPriPoolRatio(), 0.0);
  ASSERT_TRUE(new_opt.block_cache_compressed != nullptr);
  ASSERT_EQ(new_opt.block_cache_compressed->GetCapacity(), 1024UL*1024UL);
  ASSERT_EQ(std::dynamic_pointer_cast<ShardedCache>(
                new_opt.block_cache_compressed)->GetNumShardBits(), 4);
  ASSERT_EQ(new_opt.block_cache_compressed->HasStrictCapacityLimit(), true);
  ASSERT_EQ(std::dynamic_pointer_cast<LRUCache>(
                new_opt.block_cache_compressed)->GetHighPriPoolRatio(),
                0.0);
677
}
678
#endif  // !ROCKSDB_LITE
679

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

#ifndef ROCKSDB_LITE  // GetPlainTableOptionsFromString is not supported
TEST_F(OptionsTest, GetPlainTableOptionsFromString) {
  PlainTableOptions table_opt;
  PlainTableOptions new_opt;
  // make sure default values are overwritten by something else
  ASSERT_OK(GetPlainTableOptionsFromString(table_opt,
            "user_key_len=66;bloom_bits_per_key=20;hash_table_ratio=0.5;"
            "index_sparseness=8;huge_page_tlb_size=4;encoding_type=kPrefix;"
            "full_scan_mode=true;store_index_in_file=true",
            &new_opt));
  ASSERT_EQ(new_opt.user_key_len, 66);
  ASSERT_EQ(new_opt.bloom_bits_per_key, 20);
  ASSERT_EQ(new_opt.hash_table_ratio, 0.5);
  ASSERT_EQ(new_opt.index_sparseness, 8);
  ASSERT_EQ(new_opt.huge_page_tlb_size, 4);
  ASSERT_EQ(new_opt.encoding_type, EncodingType::kPrefix);
  ASSERT_TRUE(new_opt.full_scan_mode);
698
  ASSERT_TRUE(new_opt.store_index_in_file);
699 700 701 702 703 704 705 706

  // unknown option
  ASSERT_NOK(GetPlainTableOptionsFromString(table_opt,
             "user_key_len=66;bloom_bits_per_key=20;hash_table_ratio=0.5;"
             "bad_option=1",
             &new_opt));

  // unrecognized EncodingType
707 708 709 710 711 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 745
  ASSERT_NOK(GetPlainTableOptionsFromString(table_opt,
             "user_key_len=66;bloom_bits_per_key=20;hash_table_ratio=0.5;"
             "encoding_type=kPrefixXX",
             &new_opt));
}
#endif  // !ROCKSDB_LITE

#ifndef ROCKSDB_LITE  // GetMemTableRepFactoryFromString is not supported
TEST_F(OptionsTest, GetMemTableRepFactoryFromString) {
  std::unique_ptr<MemTableRepFactory> new_mem_factory = nullptr;

  ASSERT_OK(GetMemTableRepFactoryFromString("skip_list", &new_mem_factory));
  ASSERT_OK(GetMemTableRepFactoryFromString("skip_list:16", &new_mem_factory));
  ASSERT_EQ(std::string(new_mem_factory->Name()), "SkipListFactory");
  ASSERT_NOK(GetMemTableRepFactoryFromString("skip_list:16:invalid_opt",
                                             &new_mem_factory));

  ASSERT_OK(GetMemTableRepFactoryFromString("prefix_hash", &new_mem_factory));
  ASSERT_OK(GetMemTableRepFactoryFromString("prefix_hash:1000",
                                            &new_mem_factory));
  ASSERT_EQ(std::string(new_mem_factory->Name()), "HashSkipListRepFactory");
  ASSERT_NOK(GetMemTableRepFactoryFromString("prefix_hash:1000:invalid_opt",
                                             &new_mem_factory));

  ASSERT_OK(GetMemTableRepFactoryFromString("hash_linkedlist",
                                            &new_mem_factory));
  ASSERT_OK(GetMemTableRepFactoryFromString("hash_linkedlist:1000",
                                            &new_mem_factory));
  ASSERT_EQ(std::string(new_mem_factory->Name()), "HashLinkListRepFactory");
  ASSERT_NOK(GetMemTableRepFactoryFromString("hash_linkedlist:1000:invalid_opt",
                                             &new_mem_factory));

  ASSERT_OK(GetMemTableRepFactoryFromString("vector", &new_mem_factory));
  ASSERT_OK(GetMemTableRepFactoryFromString("vector:1024", &new_mem_factory));
  ASSERT_EQ(std::string(new_mem_factory->Name()), "VectorRepFactory");
  ASSERT_NOK(GetMemTableRepFactoryFromString("vector:1024:invalid_opt",
                                             &new_mem_factory));

  ASSERT_NOK(GetMemTableRepFactoryFromString("cuckoo", &new_mem_factory));
746 747
  // CuckooHash memtable is already removed.
  ASSERT_NOK(GetMemTableRepFactoryFromString("cuckoo:1024", &new_mem_factory));
748 749

  ASSERT_NOK(GetMemTableRepFactoryFromString("bad_factory", &new_mem_factory));
750 751 752
}
#endif  // !ROCKSDB_LITE

753
#ifndef ROCKSDB_LITE  // GetOptionsFromString is not supported in RocksDB Lite
I
Igor Sugak 已提交
754
TEST_F(OptionsTest, GetOptionsFromStringTest) {
755 756 757 758 759 760 761 762 763 764 765
  Options base_options, new_options;
  base_options.write_buffer_size = 20;
  base_options.min_write_buffer_number_to_merge = 15;
  BlockBasedTableOptions block_based_table_options;
  block_based_table_options.cache_index_and_filter_blocks = true;
  base_options.table_factory.reset(
      NewBlockBasedTableFactory(block_based_table_options));
  ASSERT_OK(GetOptionsFromString(
      base_options,
      "write_buffer_size=10;max_write_buffer_number=16;"
      "block_based_table_factory={block_cache=1M;block_size=4;};"
766
      "compression_opts=4:5:6;create_if_missing=true;max_open_files=1;"
767 768
      "bottommost_compression_opts=5:6:7;create_if_missing=true;max_open_files="
      "1;"
769
      "rate_limiter_bytes_per_sec=1024",
770 771
      &new_options));

772 773 774 775
  ASSERT_EQ(new_options.compression_opts.window_bits, 4);
  ASSERT_EQ(new_options.compression_opts.level, 5);
  ASSERT_EQ(new_options.compression_opts.strategy, 6);
  ASSERT_EQ(new_options.compression_opts.max_dict_bytes, 0);
776 777
  ASSERT_EQ(new_options.compression_opts.zstd_max_train_bytes, 0);
  ASSERT_EQ(new_options.compression_opts.enabled, false);
778
  ASSERT_EQ(new_options.bottommost_compression, kDisableCompressionOption);
779 780 781 782 783 784
  ASSERT_EQ(new_options.bottommost_compression_opts.window_bits, 5);
  ASSERT_EQ(new_options.bottommost_compression_opts.level, 6);
  ASSERT_EQ(new_options.bottommost_compression_opts.strategy, 7);
  ASSERT_EQ(new_options.bottommost_compression_opts.max_dict_bytes, 0);
  ASSERT_EQ(new_options.bottommost_compression_opts.zstd_max_train_bytes, 0);
  ASSERT_EQ(new_options.bottommost_compression_opts.enabled, false);
785
  ASSERT_EQ(new_options.write_buffer_size, 10U);
I
Igor Canadi 已提交
786
  ASSERT_EQ(new_options.max_write_buffer_number, 16);
787 788
  BlockBasedTableOptions new_block_based_table_options =
      dynamic_cast<BlockBasedTableFactory*>(new_options.table_factory.get())
S
SherlockNoMad 已提交
789
          ->table_options();
790
  ASSERT_EQ(new_block_based_table_options.block_cache->GetCapacity(), 1U << 20);
I
Igor Canadi 已提交
791
  ASSERT_EQ(new_block_based_table_options.block_size, 4U);
792 793 794 795 796
  // don't overwrite block based table options
  ASSERT_TRUE(new_block_based_table_options.cache_index_and_filter_blocks);

  ASSERT_EQ(new_options.create_if_missing, true);
  ASSERT_EQ(new_options.max_open_files, 1);
I
Igor Canadi 已提交
797
  ASSERT_TRUE(new_options.rate_limiter.get() != nullptr);
798
}
799 800 801 802 803 804

TEST_F(OptionsTest, DBOptionsSerialization) {
  Options base_options, new_options;
  Random rnd(301);

  // Phase 1: Make big change in base_options
805
  test::RandomInitDBOptions(&base_options, &rnd);
806 807

  // Phase 2: obtain a string from base_option
808 809
  std::string base_options_file_content;
  ASSERT_OK(GetStringFromDBOptions(&base_options_file_content, base_options));
810 811 812

  // Phase 3: Set new_options from the derived string and expect
  //          new_options == base_options
813 814 815
  ASSERT_OK(GetDBOptionsFromString(DBOptions(), base_options_file_content,
                                   &new_options));
  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(base_options, new_options));
816
}
817

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
TEST_F(OptionsTest, OptionsComposeDecompose) {
  // build an Options from DBOptions + CFOptions, then decompose it to verify
  // we get same constituent options.
  DBOptions base_db_opts;
  ColumnFamilyOptions base_cf_opts;

  Random rnd(301);
  test::RandomInitDBOptions(&base_db_opts, &rnd);
  test::RandomInitCFOptions(&base_cf_opts, &rnd);

  Options base_opts(base_db_opts, base_cf_opts);
  DBOptions new_db_opts(base_opts);
  ColumnFamilyOptions new_cf_opts(base_opts);

  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(base_db_opts, new_db_opts));
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_cf_opts, new_cf_opts));
834
  delete new_cf_opts.compaction_filter;
835 836
}

837 838 839 840 841
TEST_F(OptionsTest, ColumnFamilyOptionsSerialization) {
  ColumnFamilyOptions base_opt, new_opt;
  Random rnd(302);
  // Phase 1: randomly assign base_opt
  // custom type options
842
  test::RandomInitCFOptions(&base_opt, &rnd);
843 844

  // Phase 2: obtain a string from base_opt
845 846 847
  std::string base_options_file_content;
  ASSERT_OK(
      GetStringFromColumnFamilyOptions(&base_options_file_content, base_opt));
848 849 850

  // Phase 3: Set new_opt from the derived string and expect
  //          new_opt == base_opt
851 852 853
  ASSERT_OK(GetColumnFamilyOptionsFromString(
      ColumnFamilyOptions(), base_options_file_content, &new_opt));
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(base_opt, new_opt));
854 855 856
  if (base_opt.compaction_filter) {
    delete base_opt.compaction_filter;
  }
857 858
}

859 860
#endif  // !ROCKSDB_LITE

861 862 863 864
Status StringToMap(
    const std::string& opts_str,
    std::unordered_map<std::string, std::string>* opts_map);

865
#ifndef ROCKSDB_LITE  // StringToMap is not supported in ROCKSDB_LITE
I
Igor Sugak 已提交
866
TEST_F(OptionsTest, StringToMapTest) {
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
  std::unordered_map<std::string, std::string> opts_map;
  // Regular options
  ASSERT_OK(StringToMap("k1=v1;k2=v2;k3=v3", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "v2");
  ASSERT_EQ(opts_map["k3"], "v3");
  // Value with '='
  opts_map.clear();
  ASSERT_OK(StringToMap("k1==v1;k2=v2=;", &opts_map));
  ASSERT_EQ(opts_map["k1"], "=v1");
  ASSERT_EQ(opts_map["k2"], "v2=");
  // Overwrriten option
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k1=v2;k3=v3", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v2");
  ASSERT_EQ(opts_map["k3"], "v3");
  // Empty value
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2=;k3=v3;k4=", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_TRUE(opts_map.find("k2") != opts_map.end());
  ASSERT_EQ(opts_map["k2"], "");
  ASSERT_EQ(opts_map["k3"], "v3");
  ASSERT_TRUE(opts_map.find("k4") != opts_map.end());
  ASSERT_EQ(opts_map["k4"], "");
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2=;k3=v3;k4=   ", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_TRUE(opts_map.find("k2") != opts_map.end());
  ASSERT_EQ(opts_map["k2"], "");
  ASSERT_EQ(opts_map["k3"], "v3");
  ASSERT_TRUE(opts_map.find("k4") != opts_map.end());
  ASSERT_EQ(opts_map["k4"], "");
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2=;k3=", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_TRUE(opts_map.find("k2") != opts_map.end());
  ASSERT_EQ(opts_map["k2"], "");
  ASSERT_TRUE(opts_map.find("k3") != opts_map.end());
  ASSERT_EQ(opts_map["k3"], "");
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2=;k3=;", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_TRUE(opts_map.find("k2") != opts_map.end());
  ASSERT_EQ(opts_map["k2"], "");
  ASSERT_TRUE(opts_map.find("k3") != opts_map.end());
  ASSERT_EQ(opts_map["k3"], "");
  // Regular nested options
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2={nk1=nv1;nk2=nv2};k3=v3", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "nk1=nv1;nk2=nv2");
  ASSERT_EQ(opts_map["k3"], "v3");
  // Multi-level nested options
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2={nk1=nv1;nk2={nnk1=nnk2}};"
                        "k3={nk1={nnk1={nnnk1=nnnv1;nnnk2;nnnv2}}};k4=v4",
                        &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "nk1=nv1;nk2={nnk1=nnk2}");
  ASSERT_EQ(opts_map["k3"], "nk1={nnk1={nnnk1=nnnv1;nnnk2;nnnv2}}");
  ASSERT_EQ(opts_map["k4"], "v4");
  // Garbage inside curly braces
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2={dfad=};k3={=};k4=v4",
                        &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "dfad=");
  ASSERT_EQ(opts_map["k3"], "=");
  ASSERT_EQ(opts_map["k4"], "v4");
  // Empty nested options
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2={};", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "");
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2={{{{}}}{}{}};", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "{{{}}}{}{}");
  // With random spaces
  opts_map.clear();
  ASSERT_OK(StringToMap("  k1 =  v1 ; k2= {nk1=nv1; nk2={nnk1=nnk2}}  ; "
                        "k3={  {   } }; k4= v4  ",
                        &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "nk1=nv1; nk2={nnk1=nnk2}");
  ASSERT_EQ(opts_map["k3"], "{   }");
  ASSERT_EQ(opts_map["k4"], "v4");

  // Empty key
  ASSERT_NOK(StringToMap("k1=v1;k2=v2;=", &opts_map));
  ASSERT_NOK(StringToMap("=v1;k2=v2", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2v2;", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2=v2;fadfa", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2=v2;;", &opts_map));
  // Mismatch curly braces
  ASSERT_NOK(StringToMap("k1=v1;k2={;k3=v3", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{};k3=v3", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={}};k3=v3", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{}{}}};k3=v3", &opts_map));
  // However this is valid!
  opts_map.clear();
  ASSERT_OK(StringToMap("k1=v1;k2=};k3=v3", &opts_map));
  ASSERT_EQ(opts_map["k1"], "v1");
  ASSERT_EQ(opts_map["k2"], "}");
  ASSERT_EQ(opts_map["k3"], "v3");

  // Invalid chars after closing curly brace
  ASSERT_NOK(StringToMap("k1=v1;k2={{}}{};k3=v3", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{}}cfda;k3=v3", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{}}  cfda;k3=v3", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{}}  cfda", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{}}{}", &opts_map));
  ASSERT_NOK(StringToMap("k1=v1;k2={{dfdl}adfa}{}", &opts_map));
}
982
#endif  // ROCKSDB_LITE
983

984
#ifndef ROCKSDB_LITE  // StringToMap is not supported in ROCKSDB_LITE
I
Igor Sugak 已提交
985
TEST_F(OptionsTest, StringToMapRandomTest) {
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  std::unordered_map<std::string, std::string> opts_map;
  // Make sure segfault is not hit by semi-random strings

  std::vector<std::string> bases = {
      "a={aa={};tt={xxx={}}};c=defff",
      "a={aa={};tt={xxx={}}};c=defff;d={{}yxx{}3{xx}}",
      "abc={{}{}{}{{{}}}{{}{}{}{}{}{}{}"};

  for (std::string base : bases) {
    for (int rand_seed = 301; rand_seed < 401; rand_seed++) {
      Random rnd(rand_seed);
      for (int attempt = 0; attempt < 10; attempt++) {
        std::string str = base;
        // Replace random position to space
        size_t pos = static_cast<size_t>(
            rnd.Uniform(static_cast<int>(base.size())));
        str[pos] = ' ';
        Status s = StringToMap(str, &opts_map);
        ASSERT_TRUE(s.ok() || s.IsInvalidArgument());
        opts_map.clear();
      }
    }
  }

  // Random Construct a string
  std::vector<char> chars = {'{', '}', ' ', '=', ';', 'c'};
  for (int rand_seed = 301; rand_seed < 1301; rand_seed++) {
    Random rnd(rand_seed);
    int len = rnd.Uniform(30);
    std::string str = "";
    for (int attempt = 0; attempt < len; attempt++) {
      // Add a random character
      size_t pos = static_cast<size_t>(
          rnd.Uniform(static_cast<int>(chars.size())));
      str.append(1, chars[pos]);
    }
    Status s = StringToMap(str, &opts_map);
    ASSERT_TRUE(s.ok() || s.IsInvalidArgument());
    s = StringToMap("name=" + str, &opts_map);
    ASSERT_TRUE(s.ok() || s.IsInvalidArgument());
    opts_map.clear();
  }
1028
}
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

TEST_F(OptionsTest, GetStringFromCompressionType) {
  std::string res;

  ASSERT_OK(GetStringFromCompressionType(&res, kNoCompression));
  ASSERT_EQ(res, "kNoCompression");

  ASSERT_OK(GetStringFromCompressionType(&res, kSnappyCompression));
  ASSERT_EQ(res, "kSnappyCompression");

  ASSERT_OK(GetStringFromCompressionType(&res, kDisableCompressionOption));
  ASSERT_EQ(res, "kDisableCompressionOption");

  ASSERT_OK(GetStringFromCompressionType(&res, kLZ4Compression));
  ASSERT_EQ(res, "kLZ4Compression");

  ASSERT_OK(GetStringFromCompressionType(&res, kZlibCompression));
  ASSERT_EQ(res, "kZlibCompression");

  ASSERT_NOK(
      GetStringFromCompressionType(&res, static_cast<CompressionType>(-10)));
}
1051
#endif  // !ROCKSDB_LITE
1052

I
Igor Sugak 已提交
1053
TEST_F(OptionsTest, ConvertOptionsTest) {
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
  LevelDBOptions leveldb_opt;
  Options converted_opt = ConvertOptions(leveldb_opt);

  ASSERT_EQ(converted_opt.create_if_missing, leveldb_opt.create_if_missing);
  ASSERT_EQ(converted_opt.error_if_exists, leveldb_opt.error_if_exists);
  ASSERT_EQ(converted_opt.paranoid_checks, leveldb_opt.paranoid_checks);
  ASSERT_EQ(converted_opt.env, leveldb_opt.env);
  ASSERT_EQ(converted_opt.info_log.get(), leveldb_opt.info_log);
  ASSERT_EQ(converted_opt.write_buffer_size, leveldb_opt.write_buffer_size);
  ASSERT_EQ(converted_opt.max_open_files, leveldb_opt.max_open_files);
  ASSERT_EQ(converted_opt.compression, leveldb_opt.compression);

S
Siying Dong 已提交
1066 1067 1068
  std::shared_ptr<TableFactory> tb_guard = converted_opt.table_factory;
  BlockBasedTableFactory* table_factory =
      dynamic_cast<BlockBasedTableFactory*>(converted_opt.table_factory.get());
1069

S
Siying Dong 已提交
1070
  ASSERT_TRUE(table_factory != nullptr);
1071

S
SherlockNoMad 已提交
1072
  const BlockBasedTableOptions table_opt = table_factory->table_options();
1073 1074 1075 1076 1077 1078 1079 1080

  ASSERT_EQ(table_opt.block_cache->GetCapacity(), 8UL << 20);
  ASSERT_EQ(table_opt.block_size, leveldb_opt.block_size);
  ASSERT_EQ(table_opt.block_restart_interval,
            leveldb_opt.block_restart_interval);
  ASSERT_EQ(table_opt.filter_policy.get(), leveldb_opt.filter_policy);
}

1081 1082 1083
#ifndef ROCKSDB_LITE
class OptionsParserTest : public testing::Test {
 public:
1084
  OptionsParserTest() { env_.reset(new test::StringEnv(Env::Default())); }
1085 1086

 protected:
1087
  std::unique_ptr<test::StringEnv> env_;
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 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 1168 1169 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 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 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
};

TEST_F(OptionsParserTest, Comment) {
  DBOptions db_opt;
  db_opt.max_open_files = 12345;
  db_opt.max_background_flushes = 301;
  db_opt.max_total_wal_size = 1024;
  ColumnFamilyOptions cf_opt;

  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.14.0\n"
      "  options_file_version=1\n"
      "[ DBOptions ]\n"
      "  # note that we don't support space around \"=\"\n"
      "  max_open_files=12345;\n"
      "  max_background_flushes=301  # comment after a statement is fine\n"
      "  # max_background_flushes=1000  # this line would be ignored\n"
      "  # max_background_compactions=2000 # so does this one\n"
      "  max_total_wal_size=1024  # keep_log_file_num=1000\n"
      "[CFOptions   \"default\"]  # column family must be specified\n"
      "                     # in the correct order\n"
      "  # if a section is blank, we will use the default\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_OK(parser.Parse(kTestFileName, env_.get()));

  ASSERT_OK(RocksDBOptionsParser::VerifyDBOptions(*parser.db_opt(), db_opt));
  ASSERT_EQ(parser.NumColumnFamilies(), 1U);
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(
      *parser.GetCFOptions("default"), cf_opt));
}

TEST_F(OptionsParserTest, ExtraSpace) {
  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[      Version   ]\n"
      "  rocksdb_version     = 3.14.0      \n"
      "  options_file_version=1   # some comment\n"
      "[DBOptions  ]  # some comment\n"
      "max_open_files=12345   \n"
      "    max_background_flushes   =    301   \n"
      " max_total_wal_size     =   1024  # keep_log_file_num=1000\n"
      "        [CFOptions      \"default\"     ]\n"
      "  # if a section is blank, we will use the default\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_OK(parser.Parse(kTestFileName, env_.get()));
}

TEST_F(OptionsParserTest, MissingDBOptions) {
  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.14.0\n"
      "  options_file_version=1\n"
      "[CFOptions \"default\"]\n"
      "  # if a section is blank, we will use the default\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_NOK(parser.Parse(kTestFileName, env_.get()));
}

TEST_F(OptionsParserTest, DoubleDBOptions) {
  DBOptions db_opt;
  db_opt.max_open_files = 12345;
  db_opt.max_background_flushes = 301;
  db_opt.max_total_wal_size = 1024;
  ColumnFamilyOptions cf_opt;

  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.14.0\n"
      "  options_file_version=1\n"
      "[DBOptions]\n"
      "  max_open_files=12345\n"
      "  max_background_flushes=301\n"
      "  max_total_wal_size=1024  # keep_log_file_num=1000\n"
      "[DBOptions]\n"
      "[CFOptions \"default\"]\n"
      "  # if a section is blank, we will use the default\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_NOK(parser.Parse(kTestFileName, env_.get()));
}

TEST_F(OptionsParserTest, NoDefaultCFOptions) {
  DBOptions db_opt;
  db_opt.max_open_files = 12345;
  db_opt.max_background_flushes = 301;
  db_opt.max_total_wal_size = 1024;
  ColumnFamilyOptions cf_opt;

  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.14.0\n"
      "  options_file_version=1\n"
      "[DBOptions]\n"
      "  max_open_files=12345\n"
      "  max_background_flushes=301\n"
      "  max_total_wal_size=1024  # keep_log_file_num=1000\n"
      "[CFOptions \"something_else\"]\n"
      "  # if a section is blank, we will use the default\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_NOK(parser.Parse(kTestFileName, env_.get()));
}

TEST_F(OptionsParserTest, DefaultCFOptionsMustBeTheFirst) {
  DBOptions db_opt;
  db_opt.max_open_files = 12345;
  db_opt.max_background_flushes = 301;
  db_opt.max_total_wal_size = 1024;
  ColumnFamilyOptions cf_opt;

  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.14.0\n"
      "  options_file_version=1\n"
      "[DBOptions]\n"
      "  max_open_files=12345\n"
      "  max_background_flushes=301\n"
      "  max_total_wal_size=1024  # keep_log_file_num=1000\n"
      "[CFOptions \"something_else\"]\n"
      "  # if a section is blank, we will use the default\n"
      "[CFOptions \"default\"]\n"
      "  # if a section is blank, we will use the default\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_NOK(parser.Parse(kTestFileName, env_.get()));
}

TEST_F(OptionsParserTest, DuplicateCFOptions) {
  DBOptions db_opt;
  db_opt.max_open_files = 12345;
  db_opt.max_background_flushes = 301;
  db_opt.max_total_wal_size = 1024;
  ColumnFamilyOptions cf_opt;

  std::string options_file_content =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.14.0\n"
      "  options_file_version=1\n"
      "[DBOptions]\n"
      "  max_open_files=12345\n"
      "  max_background_flushes=301\n"
      "  max_total_wal_size=1024  # keep_log_file_num=1000\n"
      "[CFOptions \"default\"]\n"
      "[CFOptions \"something_else\"]\n"
      "[CFOptions \"something_else\"]\n";

  const std::string kTestFileName = "test-rocksdb-options.ini";
  env_->WriteToNewFile(kTestFileName, options_file_content);
  RocksDBOptionsParser parser;
  ASSERT_NOK(parser.Parse(kTestFileName, env_.get()));
}

1276
TEST_F(OptionsParserTest, IgnoreUnknownOptions) {
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
  for (int case_id = 0; case_id < 5; case_id++) {
    DBOptions db_opt;
    db_opt.max_open_files = 12345;
    db_opt.max_background_flushes = 301;
    db_opt.max_total_wal_size = 1024;
    ColumnFamilyOptions cf_opt;

    std::string version_string;
    bool should_ignore = true;
    if (case_id == 0) {
      // same version
      should_ignore = false;
      version_string =
          ToString(ROCKSDB_MAJOR) + "." + ToString(ROCKSDB_MINOR) + ".0";
    } else if (case_id == 1) {
      // higher minor version
      should_ignore = true;
      version_string =
          ToString(ROCKSDB_MAJOR) + "." + ToString(ROCKSDB_MINOR + 1) + ".0";
    } else if (case_id == 2) {
      // higher major version.
      should_ignore = true;
      version_string = ToString(ROCKSDB_MAJOR + 1) + ".0.0";
    } else if (case_id == 3) {
      // lower minor version
#if ROCKSDB_MINOR == 0
      continue;
#else
      version_string =
          ToString(ROCKSDB_MAJOR) + "." + ToString(ROCKSDB_MINOR - 1) + ".0";
      should_ignore = false;
#endif
    } else {
      // lower major version
      should_ignore = false;
      version_string =
          ToString(ROCKSDB_MAJOR - 1) + "." + ToString(ROCKSDB_MINOR) + ".0";
    }
1315

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    std::string options_file_content =
        "# This is a testing option string.\n"
        "# Currently we only support \"#\" styled comment.\n"
        "\n"
        "[Version]\n"
        "  rocksdb_version=" +
        version_string +
        "\n"
        "  options_file_version=1\n"
        "[DBOptions]\n"
        "  max_open_files=12345\n"
        "  max_background_flushes=301\n"
        "  max_total_wal_size=1024  # keep_log_file_num=1000\n"
        "  unknown_db_option1=321\n"
        "  unknown_db_option2=false\n"
        "[CFOptions \"default\"]\n"
        "  unknown_cf_option1=hello\n"
        "[CFOptions \"something_else\"]\n"
        "  unknown_cf_option2=world\n"
        "  # if a section is blank, we will use the default\n";

    const std::string kTestFileName = "test-rocksdb-options.ini";
    env_->DeleteFile(kTestFileName);
    env_->WriteToNewFile(kTestFileName, options_file_content);
    RocksDBOptionsParser parser;
    ASSERT_NOK(parser.Parse(kTestFileName, env_.get()));
    if (should_ignore) {
      ASSERT_OK(parser.Parse(kTestFileName, env_.get(),
                             true /* ignore_unknown_options */));
    } else {
      ASSERT_NOK(parser.Parse(kTestFileName, env_.get(),
                              true /* ignore_unknown_options */));
    }
  }
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 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
TEST_F(OptionsParserTest, ParseVersion) {
  DBOptions db_opt;
  db_opt.max_open_files = 12345;
  db_opt.max_background_flushes = 301;
  db_opt.max_total_wal_size = 1024;
  ColumnFamilyOptions cf_opt;

  std::string file_template =
      "# This is a testing option string.\n"
      "# Currently we only support \"#\" styled comment.\n"
      "\n"
      "[Version]\n"
      "  rocksdb_version=3.13.1\n"
      "  options_file_version=%s\n"
      "[DBOptions]\n"
      "[CFOptions \"default\"]\n";
  const int kLength = 1000;
  char buffer[kLength];
  RocksDBOptionsParser parser;

  const std::vector<std::string> invalid_versions = {
      "a.b.c", "3.2.2b", "3.-12", "3. 1",  // only digits and dots are allowed
      "1.2.3.4",
      "1.2.3"  // can only contains at most one dot.
      "0",     // options_file_version must be at least one
      "3..2",
      ".", ".1.2",             // must have at least one digit before each dot
      "1.2.", "1.", "2.34."};  // must have at least one digit after each dot
  for (auto iv : invalid_versions) {
    snprintf(buffer, kLength - 1, file_template.c_str(), iv.c_str());

    parser.Reset();
    env_->WriteToNewFile(iv, buffer);
    ASSERT_NOK(parser.Parse(iv, env_.get()));
  }

  const std::vector<std::string> valid_versions = {
      "1.232", "100", "3.12", "1", "12.3  ", "  1.25  "};
  for (auto vv : valid_versions) {
    snprintf(buffer, kLength - 1, file_template.c_str(), vv.c_str());
    parser.Reset();
    env_->WriteToNewFile(vv, buffer);
    ASSERT_OK(parser.Parse(vv, env_.get()));
  }
}

1398 1399 1400 1401 1402 1403 1404 1405 1406
void VerifyCFPointerTypedOptions(
    ColumnFamilyOptions* base_cf_opt, const ColumnFamilyOptions* new_cf_opt,
    const std::unordered_map<std::string, std::string>* new_cf_opt_map) {
  std::string name_buffer;
  ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(*base_cf_opt, *new_cf_opt,
                                                  new_cf_opt_map));

  // change the name of merge operator back-and-forth
  {
1407
    auto* merge_operator = dynamic_cast<test::ChanglingMergeOperator*>(
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
        base_cf_opt->merge_operator.get());
    if (merge_operator != nullptr) {
      name_buffer = merge_operator->Name();
      // change the name  and expect non-ok status
      merge_operator->SetName("some-other-name");
      ASSERT_NOK(RocksDBOptionsParser::VerifyCFOptions(
          *base_cf_opt, *new_cf_opt, new_cf_opt_map));
      // change the name back and expect ok status
      merge_operator->SetName(name_buffer);
      ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(*base_cf_opt, *new_cf_opt,
                                                      new_cf_opt_map));
    }
  }

  // change the name of the compaction filter factory back-and-forth
  {
    auto* compaction_filter_factory =
1425
        dynamic_cast<test::ChanglingCompactionFilterFactory*>(
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
            base_cf_opt->compaction_filter_factory.get());
    if (compaction_filter_factory != nullptr) {
      name_buffer = compaction_filter_factory->Name();
      // change the name and expect non-ok status
      compaction_filter_factory->SetName("some-other-name");
      ASSERT_NOK(RocksDBOptionsParser::VerifyCFOptions(
          *base_cf_opt, *new_cf_opt, new_cf_opt_map));
      // change the name back and expect ok status
      compaction_filter_factory->SetName(name_buffer);
      ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(*base_cf_opt, *new_cf_opt,
                                                      new_cf_opt_map));
    }
  }

  // test by setting compaction_filter to nullptr
  {
    auto* tmp_compaction_filter = base_cf_opt->compaction_filter;
    if (tmp_compaction_filter != nullptr) {
      base_cf_opt->compaction_filter = nullptr;
      // set compaction_filter to nullptr and expect non-ok status
      ASSERT_NOK(RocksDBOptionsParser::VerifyCFOptions(
          *base_cf_opt, *new_cf_opt, new_cf_opt_map));
      // set the value back and expect ok status
      base_cf_opt->compaction_filter = tmp_compaction_filter;
      ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(*base_cf_opt, *new_cf_opt,
                                                      new_cf_opt_map));
    }
  }

  // test by setting table_factory to nullptr
  {
    auto tmp_table_factory = base_cf_opt->table_factory;
    if (tmp_table_factory != nullptr) {
      base_cf_opt->table_factory.reset();
      // set table_factory to nullptr and expect non-ok status
      ASSERT_NOK(RocksDBOptionsParser::VerifyCFOptions(
          *base_cf_opt, *new_cf_opt, new_cf_opt_map));
      // set the value back and expect ok status
      base_cf_opt->table_factory = tmp_table_factory;
      ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(*base_cf_opt, *new_cf_opt,
                                                      new_cf_opt_map));
    }
  }

  // test by setting memtable_factory to nullptr
  {
    auto tmp_memtable_factory = base_cf_opt->memtable_factory;
    if (tmp_memtable_factory != nullptr) {
      base_cf_opt->memtable_factory.reset();
      // set memtable_factory to nullptr and expect non-ok status
      ASSERT_NOK(RocksDBOptionsParser::VerifyCFOptions(
          *base_cf_opt, *new_cf_opt, new_cf_opt_map));
      // set the value back and expect ok status
      base_cf_opt->memtable_factory = tmp_memtable_factory;
      ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(*base_cf_opt, *new_cf_opt,
                                                      new_cf_opt_map));
    }
  }
}

1486 1487 1488
TEST_F(OptionsParserTest, DumpAndParse) {
  DBOptions base_db_opt;
  std::vector<ColumnFamilyOptions> base_cf_opts;
1489 1490 1491 1492
  std::vector<std::string> cf_names = {"default", "cf1", "cf2", "cf3",
                                       "c:f:4:4:4"
                                       "p\\i\\k\\a\\chu\\\\\\",
                                       "###rocksdb#1-testcf#2###"};
1493 1494
  const int num_cf = static_cast<int>(cf_names.size());
  Random rnd(302);
1495
  test::RandomInitDBOptions(&base_db_opt, &rnd);
1496
  base_db_opt.db_log_dir += "/#odd #but #could #happen #path #/\\\\#OMG";
S
Siying Dong 已提交
1497 1498 1499 1500 1501

  BlockBasedTableOptions special_bbto;
  special_bbto.cache_index_and_filter_blocks = true;
  special_bbto.block_size = 999999;

1502 1503 1504
  for (int c = 0; c < num_cf; ++c) {
    ColumnFamilyOptions cf_opt;
    Random cf_rnd(0xFB + c);
1505
    test::RandomInitCFOptions(&cf_opt, &cf_rnd);
1506
    if (c < 4) {
1507
      cf_opt.prefix_extractor.reset(test::RandomSliceTransform(&rnd, c));
1508 1509
    }
    if (c < 3) {
1510
      cf_opt.table_factory.reset(test::RandomTableFactory(&rnd, c));
S
Siying Dong 已提交
1511 1512
    } else if (c == 4) {
      cf_opt.table_factory.reset(NewBlockBasedTableFactory(special_bbto));
1513
    }
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    base_cf_opts.emplace_back(cf_opt);
  }

  const std::string kOptionsFileName = "test-persisted-options.ini";
  ASSERT_OK(PersistRocksDBOptions(base_db_opt, cf_names, base_cf_opts,
                                  kOptionsFileName, env_.get()));

  RocksDBOptionsParser parser;
  ASSERT_OK(parser.Parse(kOptionsFileName, env_.get()));

S
Siying Dong 已提交
1524 1525 1526 1527 1528 1529 1530 1531 1532
  // Make sure block-based table factory options was deserialized correctly
  std::shared_ptr<TableFactory> ttf = (*parser.cf_opts())[4].table_factory;
  ASSERT_EQ(BlockBasedTableFactory::kName, std::string(ttf->Name()));
  const BlockBasedTableOptions& parsed_bbto =
      static_cast<BlockBasedTableFactory*>(ttf.get())->table_options();
  ASSERT_EQ(special_bbto.block_size, parsed_bbto.block_size);
  ASSERT_EQ(special_bbto.cache_index_and_filter_blocks,
            parsed_bbto.cache_index_and_filter_blocks);

1533 1534 1535 1536 1537 1538 1539 1540
  ASSERT_OK(RocksDBOptionsParser::VerifyRocksDBOptionsFromFile(
      base_db_opt, cf_names, base_cf_opts, kOptionsFileName, env_.get()));

  ASSERT_OK(
      RocksDBOptionsParser::VerifyDBOptions(*parser.db_opt(), base_db_opt));
  for (int c = 0; c < num_cf; ++c) {
    const auto* cf_opt = parser.GetCFOptions(cf_names[c]);
    ASSERT_NE(cf_opt, nullptr);
1541 1542
    ASSERT_OK(RocksDBOptionsParser::VerifyCFOptions(
        base_cf_opts[c], *cf_opt, &(parser.cf_opt_maps()->at(c))));
1543
  }
1544 1545 1546 1547 1548 1549 1550 1551 1552

  // Further verify pointer-typed options
  for (int c = 0; c < num_cf; ++c) {
    const auto* cf_opt = parser.GetCFOptions(cf_names[c]);
    ASSERT_NE(cf_opt, nullptr);
    VerifyCFPointerTypedOptions(&base_cf_opts[c], cf_opt,
                                &(parser.cf_opt_maps()->at(c)));
  }

1553 1554 1555 1556 1557
  ASSERT_EQ(parser.GetCFOptions("does not exist"), nullptr);

  base_db_opt.max_open_files++;
  ASSERT_NOK(RocksDBOptionsParser::VerifyRocksDBOptionsFromFile(
      base_db_opt, cf_names, base_cf_opts, kOptionsFileName, env_.get()));
1558 1559 1560 1561 1562 1563

  for (int c = 0; c < num_cf; ++c) {
    if (base_cf_opts[c].compaction_filter) {
      delete base_cf_opts[c].compaction_filter;
    }
  }
1564 1565
}

1566 1567 1568 1569
TEST_F(OptionsParserTest, DifferentDefault) {
  const std::string kOptionsFileName = "test-persisted-options.ini";

  ColumnFamilyOptions cf_level_opts;
1570
  ASSERT_EQ(CompactionPri::kMinOverlappingRatio, cf_level_opts.compaction_pri);
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
  cf_level_opts.OptimizeLevelStyleCompaction();

  ColumnFamilyOptions cf_univ_opts;
  cf_univ_opts.OptimizeUniversalStyleCompaction();

  ASSERT_OK(PersistRocksDBOptions(DBOptions(), {"default", "universal"},
                                  {cf_level_opts, cf_univ_opts},
                                  kOptionsFileName, env_.get()));

  RocksDBOptionsParser parser;
  ASSERT_OK(parser.Parse(kOptionsFileName, env_.get()));
S
sdong 已提交
1582

S
sdong 已提交
1583 1584 1585 1586 1587
  {
    Options old_default_opts;
    old_default_opts.OldDefaults();
    ASSERT_EQ(10 * 1048576, old_default_opts.max_bytes_for_level_base);
    ASSERT_EQ(5000, old_default_opts.max_open_files);
1588
    ASSERT_EQ(2 * 1024U * 1024U, old_default_opts.delayed_write_rate);
S
sdong 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    ASSERT_EQ(WALRecoveryMode::kTolerateCorruptedTailRecords,
              old_default_opts.wal_recovery_mode);
  }
  {
    Options old_default_opts;
    old_default_opts.OldDefaults(4, 6);
    ASSERT_EQ(10 * 1048576, old_default_opts.max_bytes_for_level_base);
    ASSERT_EQ(5000, old_default_opts.max_open_files);
  }
  {
    Options old_default_opts;
    old_default_opts.OldDefaults(4, 7);
    ASSERT_NE(10 * 1048576, old_default_opts.max_bytes_for_level_base);
    ASSERT_NE(4, old_default_opts.table_cache_numshardbits);
    ASSERT_EQ(5000, old_default_opts.max_open_files);
1604
    ASSERT_EQ(2 * 1024U * 1024U, old_default_opts.delayed_write_rate);
S
sdong 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
  }
  {
    ColumnFamilyOptions old_default_cf_opts;
    old_default_cf_opts.OldDefaults();
    ASSERT_EQ(2 * 1048576, old_default_cf_opts.target_file_size_base);
    ASSERT_EQ(4 << 20, old_default_cf_opts.write_buffer_size);
    ASSERT_EQ(2 * 1048576, old_default_cf_opts.target_file_size_base);
    ASSERT_EQ(0, old_default_cf_opts.soft_pending_compaction_bytes_limit);
    ASSERT_EQ(0, old_default_cf_opts.hard_pending_compaction_bytes_limit);
    ASSERT_EQ(CompactionPri::kByCompensatedSize,
              old_default_cf_opts.compaction_pri);
  }
  {
    ColumnFamilyOptions old_default_cf_opts;
    old_default_cf_opts.OldDefaults(4, 6);
    ASSERT_EQ(2 * 1048576, old_default_cf_opts.target_file_size_base);
    ASSERT_EQ(CompactionPri::kByCompensatedSize,
              old_default_cf_opts.compaction_pri);
  }
  {
    ColumnFamilyOptions old_default_cf_opts;
    old_default_cf_opts.OldDefaults(4, 7);
    ASSERT_NE(2 * 1048576, old_default_cf_opts.target_file_size_base);
    ASSERT_EQ(CompactionPri::kByCompensatedSize,
              old_default_cf_opts.compaction_pri);
  }
1631 1632 1633 1634 1635 1636 1637 1638 1639
  {
    Options old_default_opts;
    old_default_opts.OldDefaults(5, 1);
    ASSERT_EQ(2 * 1024U * 1024U, old_default_opts.delayed_write_rate);
  }
  {
    Options old_default_opts;
    old_default_opts.OldDefaults(5, 2);
    ASSERT_EQ(16 * 1024U * 1024U, old_default_opts.delayed_write_rate);
1640 1641 1642 1643 1644 1645 1646 1647
    ASSERT_TRUE(old_default_opts.compaction_pri ==
                CompactionPri::kByCompensatedSize);
  }
  {
    Options old_default_opts;
    old_default_opts.OldDefaults(5, 18);
    ASSERT_TRUE(old_default_opts.compaction_pri ==
                CompactionPri::kByCompensatedSize);
1648
  }
S
sdong 已提交
1649

1650 1651 1652 1653
  Options small_opts;
  small_opts.OptimizeForSmallDb();
  ASSERT_EQ(2 << 20, small_opts.write_buffer_size);
  ASSERT_EQ(5000, small_opts.max_open_files);
1654 1655
}

Y
Yueh-Hsuan Chiang 已提交
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
class OptionsSanityCheckTest : public OptionsParserTest {
 public:
  OptionsSanityCheckTest() {}

 protected:
  Status SanityCheckCFOptions(const ColumnFamilyOptions& cf_opts,
                              OptionsSanityCheckLevel level) {
    return RocksDBOptionsParser::VerifyRocksDBOptionsFromFile(
        DBOptions(), {"default"}, {cf_opts}, kOptionsFileName, env_.get(),
        level);
  }

  Status PersistCFOptions(const ColumnFamilyOptions& cf_opts) {
    Status s = env_->DeleteFile(kOptionsFileName);
    if (!s.ok()) {
      return s;
    }
    return PersistRocksDBOptions(DBOptions(), {"default"}, {cf_opts},
                                 kOptionsFileName, env_.get());
  }

  const std::string kOptionsFileName = "OPTIONS";
};

TEST_F(OptionsSanityCheckTest, SanityCheck) {
  ColumnFamilyOptions opts;
  Random rnd(301);

  // default ColumnFamilyOptions
  {
    ASSERT_OK(PersistCFOptions(opts));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
  }

  // prefix_extractor
  {
1692 1693
    // Okay to change prefix_extractor form nullptr to non-nullptr
    ASSERT_EQ(opts.prefix_extractor.get(), nullptr);
Y
Yueh-Hsuan Chiang 已提交
1694
    opts.prefix_extractor.reset(NewCappedPrefixTransform(10));
1695
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
Y
Yueh-Hsuan Chiang 已提交
1696 1697 1698 1699 1700 1701 1702 1703
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

    // persist the change
    ASSERT_OK(PersistCFOptions(opts));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));

    // use same prefix extractor but with different parameter
    opts.prefix_extractor.reset(NewCappedPrefixTransform(15));
1704 1705 1706
    // expect pass only in kSanityLevelLooselyCompatible
    ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
Y
Yueh-Hsuan Chiang 已提交
1707 1708 1709 1710
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

    // repeat the test with FixedPrefixTransform
    opts.prefix_extractor.reset(NewFixedPrefixTransform(10));
1711 1712
    ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
Y
Yueh-Hsuan Chiang 已提交
1713 1714 1715 1716 1717 1718 1719 1720
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

    // persist the change of prefix_extractor
    ASSERT_OK(PersistCFOptions(opts));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));

    // use same prefix extractor but with different parameter
    opts.prefix_extractor.reset(NewFixedPrefixTransform(15));
1721 1722 1723
    // expect pass only in kSanityLevelLooselyCompatible
    ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
Y
Yueh-Hsuan Chiang 已提交
1724
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));
1725 1726 1727 1728 1729 1730 1731

    // Change prefix extractor from non-nullptr to nullptr
    opts.prefix_extractor.reset();
    // expect pass as it's safe to change prefix_extractor
    // from non-null to null
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));
Y
Yueh-Hsuan Chiang 已提交
1732
  }
1733 1734 1735
  // persist the change
  ASSERT_OK(PersistCFOptions(opts));
  ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
Y
Yueh-Hsuan Chiang 已提交
1736 1737 1738

  // table_factory
  {
1739
    for (int tb = 0; tb <= 2; ++tb) {
Y
Yueh-Hsuan Chiang 已提交
1740
      // change the table factory
1741
      opts.table_factory.reset(test::RandomTableFactory(&rnd, tb));
Y
Yueh-Hsuan Chiang 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
      ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

      // persist the change
      ASSERT_OK(PersistCFOptions(opts));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
    }
  }

  // merge_operator
  {
1753 1754 1755 1756 1757 1758 1759 1760 1761
    // Test when going from nullptr -> merge operator
    opts.merge_operator.reset(test::RandomMergeOperator(&rnd));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

    // persist the change
    ASSERT_OK(PersistCFOptions(opts));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));

Y
Yueh-Hsuan Chiang 已提交
1762 1763
    for (int test = 0; test < 5; ++test) {
      // change the merge operator
1764
      opts.merge_operator.reset(test::RandomMergeOperator(&rnd));
Y
Yueh-Hsuan Chiang 已提交
1765 1766 1767 1768 1769 1770 1771
      ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

      // persist the change
      ASSERT_OK(PersistCFOptions(opts));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
    }
1772 1773 1774 1775 1776 1777 1778 1779 1780

    // Test when going from merge operator -> nullptr
    opts.merge_operator = nullptr;
    ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelNone));

    // persist the change
    ASSERT_OK(PersistCFOptions(opts));
    ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
Y
Yueh-Hsuan Chiang 已提交
1781 1782 1783 1784 1785 1786
  }

  // compaction_filter
  {
    for (int test = 0; test < 5; ++test) {
      // change the compaction filter
1787
      opts.compaction_filter = test::RandomCompactionFilter(&rnd);
Y
Yueh-Hsuan Chiang 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
      ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));

      // persist the change
      ASSERT_OK(PersistCFOptions(opts));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
      delete opts.compaction_filter;
      opts.compaction_filter = nullptr;
    }
  }

  // compaction_filter_factory
  {
    for (int test = 0; test < 5; ++test) {
      // change the compaction filter factory
1803 1804
      opts.compaction_filter_factory.reset(
          test::RandomCompactionFilterFactory(&rnd));
Y
Yueh-Hsuan Chiang 已提交
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
      ASSERT_NOK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelLooselyCompatible));

      // persist the change
      ASSERT_OK(PersistCFOptions(opts));
      ASSERT_OK(SanityCheckCFOptions(opts, kSanityLevelExactMatch));
    }
  }
}

1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
namespace {
bool IsEscapedString(const std::string& str) {
  for (size_t i = 0; i < str.size(); ++i) {
    if (str[i] == '\\') {
      // since we already handle those two consecutive '\'s in
      // the next if-then branch, any '\' appear at the end
      // of an escaped string in such case is not valid.
      if (i == str.size() - 1) {
        return false;
      }
      if (str[i + 1] == '\\') {
        // if there're two consecutive '\'s, skip the second one.
        i++;
        continue;
      }
      switch (str[i + 1]) {
        case ':':
        case '\\':
        case '#':
          continue;
        default:
          // if true, '\' together with str[i + 1] is not a valid escape.
          if (UnescapeChar(str[i + 1]) == str[i + 1]) {
            return false;
          }
      }
    } else if (isSpecialChar(str[i]) && (i == 0 || str[i - 1] != '\\')) {
      return false;
    }
  }
  return true;
}
}  // namespace

Z
Zhongyi Xie 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
TEST_F(OptionsParserTest, IntegerParsing) {
  ASSERT_EQ(ParseUint64("18446744073709551615"), 18446744073709551615U);
  ASSERT_EQ(ParseUint32("4294967295"), 4294967295U);
  ASSERT_EQ(ParseSizeT("18446744073709551615"), 18446744073709551615U);
  ASSERT_EQ(ParseInt64("9223372036854775807"), 9223372036854775807U);
  ASSERT_EQ(ParseInt64("-9223372036854775808"), port::kMinInt64);
  ASSERT_EQ(ParseInt32("2147483647"), 2147483647U);
  ASSERT_EQ(ParseInt32("-2147483648"), port::kMinInt32);
  ASSERT_EQ(ParseInt("-32767"), -32767);
  ASSERT_EQ(ParseDouble("-1.234567"), -1.234567);
}

1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
TEST_F(OptionsParserTest, EscapeOptionString) {
  ASSERT_EQ(UnescapeOptionString(
                "This is a test string with \\# \\: and \\\\ escape chars."),
            "This is a test string with # : and \\ escape chars.");

  ASSERT_EQ(
      EscapeOptionString("This is a test string with # : and \\ escape chars."),
      "This is a test string with \\# \\: and \\\\ escape chars.");

  std::string readible_chars =
      "A String like this \"1234567890-=_)(*&^%$#@!ertyuiop[]{POIU"
      "YTREWQasdfghjkl;':LKJHGFDSAzxcvbnm,.?>"
      "<MNBVCXZ\\\" should be okay to \\#\\\\\\:\\#\\#\\#\\ "
      "be serialized and deserialized";

  std::string escaped_string = EscapeOptionString(readible_chars);
  ASSERT_TRUE(IsEscapedString(escaped_string));
  // This two transformations should be canceled and should output
  // the original input.
  ASSERT_EQ(UnescapeOptionString(escaped_string), readible_chars);

  std::string all_chars;
  for (unsigned char c = 0;; ++c) {
    all_chars += c;
    if (c == 255) {
      break;
    }
  }
  escaped_string = EscapeOptionString(all_chars);
  ASSERT_TRUE(IsEscapedString(escaped_string));
  ASSERT_EQ(UnescapeOptionString(escaped_string), all_chars);

  ASSERT_EQ(RocksDBOptionsParser::TrimAndRemoveComment(
                "     A simple statement with a comment.  # like this :)"),
            "A simple statement with a comment.");

  ASSERT_EQ(RocksDBOptionsParser::TrimAndRemoveComment(
                "Escape \\# and # comment together   ."),
            "Escape \\# and");
}
#endif  // !ROCKSDB_LITE
1902 1903 1904
}  // namespace rocksdb

int main(int argc, char** argv) {
I
Igor Sugak 已提交
1905
  ::testing::InitGoogleTest(&argc, argv);
I
Igor Canadi 已提交
1906
#ifdef GFLAGS
1907
  ParseCommandLineFlags(&argc, &argv, true);
I
Igor Canadi 已提交
1908
#endif  // GFLAGS
I
Igor Sugak 已提交
1909
  return RUN_ALL_TESTS();
1910
}