file_reader_writer_test.cc 14.8 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
//
#include "util/file_reader_writer.h"
7 8
#include <algorithm>
#include <vector>
9 10
#include "test_util/testharness.h"
#include "test_util/testutil.h"
11
#include "util/random.h"
12 13 14 15 16 17 18 19 20 21 22

namespace rocksdb {

class WritableFileWriterTest : public testing::Test {};

const uint32_t kMb = 1 << 20;

TEST_F(WritableFileWriterTest, RangeSync) {
  class FakeWF : public WritableFile {
   public:
    explicit FakeWF() : size_(0), last_synced_(0) {}
23
    ~FakeWF() override {}
24 25 26 27 28

    Status Append(const Slice& data) override {
      size_ += data.size();
      return Status::OK();
    }
29
    Status Truncate(uint64_t /*size*/) override { return Status::OK(); }
30 31 32 33 34 35 36 37 38 39
    Status Close() override {
      EXPECT_GE(size_, last_synced_ + kMb);
      EXPECT_LT(size_, last_synced_ + 2 * kMb);
      // Make sure random writes generated enough writes.
      EXPECT_GT(size_, 10 * kMb);
      return Status::OK();
    }
    Status Flush() override { return Status::OK(); }
    Status Sync() override { return Status::OK(); }
    Status Fsync() override { return Status::OK(); }
A
Andrew Kryczka 已提交
40
    void SetIOPriority(Env::IOPriority /*pri*/) override {}
41
    uint64_t GetFileSize() override { return size_; }
A
Andrew Kryczka 已提交
42 43 44 45 46 47
    void GetPreallocationStatus(size_t* /*block_size*/,
                                size_t* /*last_allocated_block*/) override {}
    size_t GetUniqueId(char* /*id*/, size_t /*max_size*/) const override {
      return 0;
    }
    Status InvalidateCache(size_t /*offset*/, size_t /*length*/) override {
48 49 50 51
      return Status::OK();
    }

   protected:
A
Andrew Kryczka 已提交
52 53 54
    Status Allocate(uint64_t /*offset*/, uint64_t /*len*/) override {
      return Status::OK();
    }
55
    Status RangeSync(uint64_t offset, uint64_t nbytes) override {
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
      EXPECT_EQ(offset % 4096, 0u);
      EXPECT_EQ(nbytes % 4096, 0u);

      EXPECT_EQ(offset, last_synced_);
      last_synced_ = offset + nbytes;
      EXPECT_GE(size_, last_synced_ + kMb);
      if (size_ > 2 * kMb) {
        EXPECT_LT(size_, last_synced_ + 2 * kMb);
      }
      return Status::OK();
    }

    uint64_t size_;
    uint64_t last_synced_;
  };

  EnvOptions env_options;
  env_options.bytes_per_sync = kMb;
74 75
  std::unique_ptr<FakeWF> wf(new FakeWF);
  std::unique_ptr<WritableFileWriter> writer(
76
      new WritableFileWriter(std::move(wf), "" /* don't care */, env_options));
77 78 79 80 81 82 83 84 85 86 87 88 89 90
  Random r(301);
  std::unique_ptr<char[]> large_buf(new char[10 * kMb]);
  for (int i = 0; i < 1000; i++) {
    int skew_limit = (i < 700) ? 10 : 15;
    uint32_t num = r.Skewed(skew_limit) * 100 + r.Uniform(100);
    writer->Append(Slice(large_buf.get(), num));

    // Flush in a chance of 1/10.
    if (r.Uniform(10) == 0) {
      writer->Flush();
    }
  }
  writer->Close();
}
91

92 93 94 95 96 97 98 99
TEST_F(WritableFileWriterTest, IncrementalBuffer) {
  class FakeWF : public WritableFile {
   public:
    explicit FakeWF(std::string* _file_data, bool _use_direct_io,
                    bool _no_flush)
        : file_data_(_file_data),
          use_direct_io_(_use_direct_io),
          no_flush_(_no_flush) {}
100
    ~FakeWF() override {}
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

    Status Append(const Slice& data) override {
      file_data_->append(data.data(), data.size());
      size_ += data.size();
      return Status::OK();
    }
    Status PositionedAppend(const Slice& data, uint64_t pos) override {
      EXPECT_TRUE(pos % 512 == 0);
      EXPECT_TRUE(data.size() % 512 == 0);
      file_data_->resize(pos);
      file_data_->append(data.data(), data.size());
      size_ += data.size();
      return Status::OK();
    }

116
    Status Truncate(uint64_t size) override {
117 118 119 120 121 122 123
      file_data_->resize(size);
      return Status::OK();
    }
    Status Close() override { return Status::OK(); }
    Status Flush() override { return Status::OK(); }
    Status Sync() override { return Status::OK(); }
    Status Fsync() override { return Status::OK(); }
A
Andrew Kryczka 已提交
124
    void SetIOPriority(Env::IOPriority /*pri*/) override {}
125
    uint64_t GetFileSize() override { return size_; }
A
Andrew Kryczka 已提交
126 127 128 129 130 131
    void GetPreallocationStatus(size_t* /*block_size*/,
                                size_t* /*last_allocated_block*/) override {}
    size_t GetUniqueId(char* /*id*/, size_t /*max_size*/) const override {
      return 0;
    }
    Status InvalidateCache(size_t /*offset*/, size_t /*length*/) override {
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
      return Status::OK();
    }
    bool use_direct_io() const override { return use_direct_io_; }

    std::string* file_data_;
    bool use_direct_io_;
    bool no_flush_;
    size_t size_ = 0;
  };

  Random r(301);
  const int kNumAttempts = 50;
  for (int attempt = 0; attempt < kNumAttempts; attempt++) {
    bool no_flush = (attempt % 3 == 0);
    EnvOptions env_options;
    env_options.writable_file_max_buffer_size =
        (attempt < kNumAttempts / 2) ? 512 * 1024 : 700 * 1024;
    std::string actual;
150
    std::unique_ptr<FakeWF> wf(new FakeWF(&actual,
S
Siying Dong 已提交
151
#ifndef ROCKSDB_LITE
152
                                          attempt % 2 == 1,
S
Siying Dong 已提交
153
#else
154
                                          false,
S
Siying Dong 已提交
155
#endif
156 157
                                          no_flush));
    std::unique_ptr<WritableFileWriter> writer(new WritableFileWriter(
158
        std::move(wf), "" /* don't care */, env_options));
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

    std::string target;
    for (int i = 0; i < 20; i++) {
      uint32_t num = r.Skewed(16) * 100 + r.Uniform(100);
      std::string random_string;
      test::RandomString(&r, num, &random_string);
      writer->Append(Slice(random_string.c_str(), num));
      target.append(random_string.c_str(), num);

      // In some attempts, flush in a chance of 1/10.
      if (!no_flush && r.Uniform(10) == 0) {
        writer->Flush();
      }
    }
    writer->Flush();
    writer->Close();
    ASSERT_EQ(target.size(), actual.size());
    ASSERT_EQ(target, actual);
  }
}

A
Aaron Gao 已提交
180
#ifndef ROCKSDB_LITE
181 182 183
TEST_F(WritableFileWriterTest, AppendStatusReturn) {
  class FakeWF : public WritableFile {
   public:
A
Aaron Gao 已提交
184
    explicit FakeWF() : use_direct_io_(false), io_error_(false) {}
185

186
    bool use_direct_io() const override { return use_direct_io_; }
A
Andrew Kryczka 已提交
187
    Status Append(const Slice& /*data*/) override {
188 189 190 191 192
      if (io_error_) {
        return Status::IOError("Fake IO error");
      }
      return Status::OK();
    }
A
Andrew Kryczka 已提交
193
    Status PositionedAppend(const Slice& /*data*/, uint64_t) override {
194 195 196 197 198 199 200 201
      if (io_error_) {
        return Status::IOError("Fake IO error");
      }
      return Status::OK();
    }
    Status Close() override { return Status::OK(); }
    Status Flush() override { return Status::OK(); }
    Status Sync() override { return Status::OK(); }
202
    void Setuse_direct_io(bool val) { use_direct_io_ = val; }
203 204 205
    void SetIOError(bool val) { io_error_ = val; }

   protected:
A
Aaron Gao 已提交
206
    bool use_direct_io_;
207 208
    bool io_error_;
  };
209
  std::unique_ptr<FakeWF> wf(new FakeWF());
210
  wf->Setuse_direct_io(true);
211
  std::unique_ptr<WritableFileWriter> writer(
212
      new WritableFileWriter(std::move(wf), "" /* don't care */, EnvOptions()));
213 214 215 216 217 218 219

  ASSERT_OK(writer->Append(std::string(2 * kMb, 'a')));

  // Next call to WritableFile::Append() should fail
  dynamic_cast<FakeWF*>(writer->writable_file())->SetIOError(true);
  ASSERT_NOK(writer->Append(std::string(2 * kMb, 'b')));
}
A
Aaron Gao 已提交
220
#endif
221

222 223 224 225 226 227 228
class ReadaheadRandomAccessFileTest
    : public testing::Test,
      public testing::WithParamInterface<size_t> {
 public:
  static std::vector<size_t> GetReadaheadSizeList() {
    return {1lu << 12, 1lu << 16};
  }
229
  void SetUp() override {
230 231 232 233 234 235 236 237 238 239 240
    readahead_size_ = GetParam();
    scratch_.reset(new char[2 * readahead_size_]);
    ResetSourceStr();
  }
  ReadaheadRandomAccessFileTest() : control_contents_() {}
  std::string Read(uint64_t offset, size_t n) {
    Slice result;
    test_read_holder_->Read(offset, n, &result, scratch_.get());
    return std::string(result.data(), result.size());
  }
  void ResetSourceStr(const std::string& str = "") {
241 242 243
    auto write_holder =
        std::unique_ptr<WritableFileWriter>(test::GetWritableFileWriter(
            new test::StringSink(&control_contents_), "" /* don't care */));
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    write_holder->Append(Slice(str));
    write_holder->Flush();
    auto read_holder = std::unique_ptr<RandomAccessFile>(
        new test::StringSource(control_contents_));
    test_read_holder_ =
        NewReadaheadRandomAccessFile(std::move(read_holder), readahead_size_);
  }
  size_t GetReadaheadSize() const { return readahead_size_; }

 private:
  size_t readahead_size_;
  Slice control_contents_;
  std::unique_ptr<RandomAccessFile> test_read_holder_;
  std::unique_ptr<char[]> scratch_;
};

TEST_P(ReadaheadRandomAccessFileTest, EmptySourceStrTest) {
  ASSERT_EQ("", Read(0, 1));
  ASSERT_EQ("", Read(0, 0));
  ASSERT_EQ("", Read(13, 13));
}

TEST_P(ReadaheadRandomAccessFileTest, SourceStrLenLessThanReadaheadSizeTest) {
  std::string str = "abcdefghijklmnopqrs";
  ResetSourceStr(str);
  ASSERT_EQ(str.substr(3, 4), Read(3, 4));
  ASSERT_EQ(str.substr(0, 3), Read(0, 3));
  ASSERT_EQ(str, Read(0, str.size()));
  ASSERT_EQ(str.substr(7, std::min(static_cast<int>(str.size()) - 7, 30)),
            Read(7, 30));
  ASSERT_EQ("", Read(100, 100));
}

TEST_P(ReadaheadRandomAccessFileTest,
278
       SourceStrLenGreaterThanReadaheadSizeTest) {
279 280 281 282 283 284 285 286 287 288
  Random rng(42);
  for (int k = 0; k < 100; ++k) {
    size_t strLen = k * GetReadaheadSize() +
                    rng.Uniform(static_cast<int>(GetReadaheadSize()));
    std::string str =
        test::RandomHumanReadableString(&rng, static_cast<int>(strLen));
    ResetSourceStr(str);
    for (int test = 1; test <= 100; ++test) {
      size_t offset = rng.Uniform(static_cast<int>(strLen));
      size_t n = rng.Uniform(static_cast<int>(GetReadaheadSize()));
289
      ASSERT_EQ(str.substr(offset, std::min(n, strLen - offset)),
290 291 292 293 294
                Read(offset, n));
    }
  }
}

295
TEST_P(ReadaheadRandomAccessFileTest, ReadExceedsReadaheadSizeTest) {
296 297 298 299 300 301 302 303 304 305
  Random rng(7);
  size_t strLen = 4 * GetReadaheadSize() +
                  rng.Uniform(static_cast<int>(GetReadaheadSize()));
  std::string str =
      test::RandomHumanReadableString(&rng, static_cast<int>(strLen));
  ResetSourceStr(str);
  for (int test = 1; test <= 100; ++test) {
    size_t offset = rng.Uniform(static_cast<int>(strLen));
    size_t n =
        GetReadaheadSize() + rng.Uniform(static_cast<int>(GetReadaheadSize()));
306
    ASSERT_EQ(str.substr(offset, std::min(n, strLen - offset)),
307 308 309 310 311 312 313 314 315 316 317
              Read(offset, n));
  }
}

INSTANTIATE_TEST_CASE_P(
    EmptySourceStrTest, ReadaheadRandomAccessFileTest,
    ::testing::ValuesIn(ReadaheadRandomAccessFileTest::GetReadaheadSizeList()));
INSTANTIATE_TEST_CASE_P(
    SourceStrLenLessThanReadaheadSizeTest, ReadaheadRandomAccessFileTest,
    ::testing::ValuesIn(ReadaheadRandomAccessFileTest::GetReadaheadSizeList()));
INSTANTIATE_TEST_CASE_P(
318
    SourceStrLenGreaterThanReadaheadSizeTest, ReadaheadRandomAccessFileTest,
319 320
    ::testing::ValuesIn(ReadaheadRandomAccessFileTest::GetReadaheadSizeList()));
INSTANTIATE_TEST_CASE_P(
321
    ReadExceedsReadaheadSizeTest, ReadaheadRandomAccessFileTest,
322 323
    ::testing::ValuesIn(ReadaheadRandomAccessFileTest::GetReadaheadSizeList()));

324 325 326 327
class ReadaheadSequentialFileTest : public testing::Test,
                                    public testing::WithParamInterface<size_t> {
 public:
  static std::vector<size_t> GetReadaheadSizeList() {
328
    return {1lu << 8, 1lu << 12, 1lu << 16, 1lu << 18};
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
  }
  void SetUp() override {
    readahead_size_ = GetParam();
    scratch_.reset(new char[2 * readahead_size_]);
    ResetSourceStr();
  }
  ReadaheadSequentialFileTest() {}
  std::string Read(size_t n) {
    Slice result;
    test_read_holder_->Read(n, &result, scratch_.get());
    return std::string(result.data(), result.size());
  }
  void Skip(size_t n) { test_read_holder_->Skip(n); }
  void ResetSourceStr(const std::string& str = "") {
    auto read_holder =
        std::unique_ptr<SequentialFile>(new test::SeqStringSource(str));
    test_read_holder_.reset(new SequentialFileReader(std::move(read_holder),
                                                     "test", readahead_size_));
  }
  size_t GetReadaheadSize() const { return readahead_size_; }

 private:
  size_t readahead_size_;
  std::unique_ptr<SequentialFileReader> test_read_holder_;
  std::unique_ptr<char[]> scratch_;
};

TEST_P(ReadaheadSequentialFileTest, EmptySourceStrTest) {
  ASSERT_EQ("", Read(0));
  ASSERT_EQ("", Read(1));
  ASSERT_EQ("", Read(13));
}

TEST_P(ReadaheadSequentialFileTest, SourceStrLenLessThanReadaheadSizeTest) {
  std::string str = "abcdefghijklmnopqrs";
  ResetSourceStr(str);
  ASSERT_EQ(str.substr(0, 3), Read(3));
  ASSERT_EQ(str.substr(3, 1), Read(1));
  ASSERT_EQ(str.substr(4), Read(str.size()));
  ASSERT_EQ("", Read(100));
}

TEST_P(ReadaheadSequentialFileTest, SourceStrLenGreaterThanReadaheadSizeTest) {
  Random rng(42);
  for (int s = 0; s < 1; ++s) {
    for (int k = 0; k < 100; ++k) {
      size_t strLen = k * GetReadaheadSize() +
                      rng.Uniform(static_cast<int>(GetReadaheadSize()));
      std::string str =
          test::RandomHumanReadableString(&rng, static_cast<int>(strLen));
      ResetSourceStr(str);
      size_t offset = 0;
      for (int test = 1; test <= 100; ++test) {
        size_t n = rng.Uniform(static_cast<int>(GetReadaheadSize()));
        if (s && test % 2) {
          Skip(n);
        } else {
          ASSERT_EQ(str.substr(offset, std::min(n, strLen - offset)), Read(n));
        }
        offset = std::min(offset + n, strLen);
      }
    }
  }
}

TEST_P(ReadaheadSequentialFileTest, ReadExceedsReadaheadSizeTest) {
  Random rng(42);
  for (int s = 0; s < 1; ++s) {
    for (int k = 0; k < 100; ++k) {
      size_t strLen = k * GetReadaheadSize() +
                      rng.Uniform(static_cast<int>(GetReadaheadSize()));
      std::string str =
          test::RandomHumanReadableString(&rng, static_cast<int>(strLen));
      ResetSourceStr(str);
      size_t offset = 0;
      for (int test = 1; test <= 100; ++test) {
        size_t n = GetReadaheadSize() +
                   rng.Uniform(static_cast<int>(GetReadaheadSize()));
        if (s && test % 2) {
          Skip(n);
        } else {
          ASSERT_EQ(str.substr(offset, std::min(n, strLen - offset)), Read(n));
        }
        offset = std::min(offset + n, strLen);
      }
    }
  }
}

INSTANTIATE_TEST_CASE_P(
    EmptySourceStrTest, ReadaheadSequentialFileTest,
    ::testing::ValuesIn(ReadaheadSequentialFileTest::GetReadaheadSizeList()));
INSTANTIATE_TEST_CASE_P(
    SourceStrLenLessThanReadaheadSizeTest, ReadaheadSequentialFileTest,
    ::testing::ValuesIn(ReadaheadSequentialFileTest::GetReadaheadSizeList()));
INSTANTIATE_TEST_CASE_P(
    SourceStrLenGreaterThanReadaheadSizeTest, ReadaheadSequentialFileTest,
    ::testing::ValuesIn(ReadaheadSequentialFileTest::GetReadaheadSizeList()));
INSTANTIATE_TEST_CASE_P(
    ReadExceedsReadaheadSizeTest, ReadaheadSequentialFileTest,
    ::testing::ValuesIn(ReadaheadSequentialFileTest::GetReadaheadSizeList()));
430 431 432 433 434 435
}  // namespace rocksdb

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}