小组成员:姚凯文(kevinyao0901),姜嘉琪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1562 line
50 KiB

5 年之前
5 年之前
5 年之前
5 年之前
5 年之前
5 年之前
5 年之前
5 年之前
Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
4 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Fix snapshot compaction bug Closes google/leveldb#320 During compaction it was possible that records from a block b1=(l1,u1) would be pushed down from level i to level i+1. If there is a block b2=(l2,u2) at level i with k1 = user_key(u1) = user_key(l2) then a subsequent search for k1 will yield the record l2 which has a smaller sequence number than u1 because the sort order for records sorts increasing by user key but decreaing by sequence number. This change add a call to a new function AddBoundaryInputs to SetupOtherInputs. AddBoundaryInputs searches for a block b2 matching the criteria above and adds it to the set of files to be compacted. Whenever AddBoundaryInputs is called it is important that the compaction fileset in level i+1 (known as c->inputs_[1] in the code) be recomputed. Each call to AddBoundaryInputs is followed by a call to GetOverlappingInputs. SetupOtherInputs is called on both manual and automated compaction passes. It is called for both level zero and for levels greater than 0. The original change posted in https://github.com/google/leveldb/pull/339 has been modified to also include changed made by Chris Mumford<cmumford@google.com> in https://github.com/cmumford/leveldb/commit/4b72cb14f8da2aab12451c24b8e205aff686e9dc 1. Releasing snapshots during test cleanup to avoid memory leak warnings. 2. Refactored test to use testutil.h to be in line with other issue tests and to create the test database in the correct temporary location. 3. Added copyright banner. Otherwise, just minor formatting and limiting character width to 80 characters. Additionally the change was rebased on top of current master and changes previously made to the Makefile were ported to the CMakeLists.txt. Testing Done: A test program (issue320_test) was constructed that performs mutations while snapshots are active. issue320_test fails without this bug fix after 64k writes. It passes with this bug fix. It was run with 200M writes and passed. Unit tests were written for the new function that was added to the code. Make test was run and seen to pass. Signed-off-by: Richard Cole <richcole@amazon.com>
8 年之前
Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
4 年之前
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "db/version_set.h"
  5. #include <algorithm>
  6. #include <cstdio>
  7. #include "db/filename.h"
  8. #include "db/log_reader.h"
  9. #include "db/log_writer.h"
  10. #include "db/memtable.h"
  11. #include "db/table_cache.h"
  12. #include "leveldb/env.h"
  13. #include "leveldb/table_builder.h"
  14. #include "table/merger.h"
  15. #include "table/two_level_iterator.h"
  16. #include "util/coding.h"
  17. #include "util/logging.h"
  18. namespace leveldb {
  19. static size_t TargetFileSize(const Options* options) {
  20. return options->max_file_size;
  21. }
  22. // Maximum bytes of overlaps in grandparent (i.e., level+2) before we
  23. // stop building a single file in a level->level+1 compaction.
  24. static int64_t MaxGrandParentOverlapBytes(const Options* options) {
  25. return 10 * TargetFileSize(options);
  26. }
  27. // Maximum number of bytes in all compacted files. We avoid expanding
  28. // the lower level file set of a compaction if it would make the
  29. // total compaction cover more than this many bytes.
  30. static int64_t ExpandedCompactionByteSizeLimit(const Options* options) {
  31. return 25 * TargetFileSize(options);
  32. }
  33. static double MaxBytesForLevel(const Options* options, int level) {
  34. // Note: the result for level zero is not really used since we set
  35. // the level-0 compaction threshold based on number of files.
  36. // Result for both level-0 and level-1
  37. double result = 10. * 1048576.0;
  38. while (level > 1) {
  39. result *= 10;
  40. level--;
  41. }
  42. return result;
  43. }
  44. static uint64_t MaxFileSizeForLevel(const Options* options, int level) {
  45. // We could vary per level to reduce number of files?
  46. return TargetFileSize(options);
  47. }
  48. static int64_t TotalFileSize(const std::vector<FileMetaData*>& files) {
  49. int64_t sum = 0;
  50. for (size_t i = 0; i < files.size(); i++) {
  51. sum += files[i]->file_size;
  52. }
  53. return sum;
  54. }
  55. Version::~Version() {
  56. assert(refs_ == 0);
  57. // Remove from linked list
  58. prev_->next_ = next_;
  59. next_->prev_ = prev_;
  60. // Drop references to files
  61. for (int level = 0; level < config::kNumLevels; level++) {
  62. for (size_t i = 0; i < files_[level].size(); i++) {
  63. FileMetaData* f = files_[level][i];
  64. assert(f->refs > 0);
  65. f->refs--;
  66. if (f->refs <= 0) {
  67. delete f;
  68. }
  69. }
  70. }
  71. }
  72. int FindFile(const InternalKeyComparator& icmp,
  73. const std::vector<FileMetaData*>& files, const Slice& key) {
  74. uint32_t left = 0;
  75. uint32_t right = files.size();
  76. while (left < right) {
  77. uint32_t mid = (left + right) / 2;
  78. const FileMetaData* f = files[mid];
  79. if (icmp.InternalKeyComparator::Compare(f->largest.Encode(), key) < 0) {
  80. // Key at "mid.largest" is < "target". Therefore all
  81. // files at or before "mid" are uninteresting.
  82. left = mid + 1;
  83. } else {
  84. // Key at "mid.largest" is >= "target". Therefore all files
  85. // after "mid" are uninteresting.
  86. right = mid;
  87. }
  88. }
  89. return right;
  90. }
  91. static bool AfterFile(const Comparator* ucmp, const Slice* user_key,
  92. const FileMetaData* f) {
  93. // null user_key occurs before all keys and is therefore never after *f
  94. return (user_key != nullptr &&
  95. ucmp->Compare(*user_key, f->largest.user_key()) > 0);
  96. }
  97. static bool BeforeFile(const Comparator* ucmp, const Slice* user_key,
  98. const FileMetaData* f) {
  99. // null user_key occurs after all keys and is therefore never before *f
  100. return (user_key != nullptr &&
  101. ucmp->Compare(*user_key, f->smallest.user_key()) < 0);
  102. }
  103. bool SomeFileOverlapsRange(const InternalKeyComparator& icmp,
  104. bool disjoint_sorted_files,
  105. const std::vector<FileMetaData*>& files,
  106. const Slice* smallest_user_key,
  107. const Slice* largest_user_key) {
  108. const Comparator* ucmp = icmp.user_comparator();
  109. if (!disjoint_sorted_files) {
  110. // Need to check against all files
  111. for (size_t i = 0; i < files.size(); i++) {
  112. const FileMetaData* f = files[i];
  113. if (AfterFile(ucmp, smallest_user_key, f) ||
  114. BeforeFile(ucmp, largest_user_key, f)) {
  115. // No overlap
  116. } else {
  117. return true; // Overlap
  118. }
  119. }
  120. return false;
  121. }
  122. // Binary search over file list
  123. uint32_t index = 0;
  124. if (smallest_user_key != nullptr) {
  125. // Find the earliest possible internal key for smallest_user_key
  126. InternalKey small_key(*smallest_user_key, kMaxSequenceNumber,
  127. kValueTypeForSeek);
  128. index = FindFile(icmp, files, small_key.Encode());
  129. }
  130. if (index >= files.size()) {
  131. // beginning of range is after all files, so no overlap.
  132. return false;
  133. }
  134. return !BeforeFile(ucmp, largest_user_key, files[index]);
  135. }
  136. // An internal iterator. For a given version/level pair, yields
  137. // information about the files in the level. For a given entry, key()
  138. // is the largest key that occurs in the file, and value() is an
  139. // 16-byte value containing the file number and file size, both
  140. // encoded using EncodeFixed64.
  141. class Version::LevelFileNumIterator : public Iterator {
  142. public:
  143. LevelFileNumIterator(const InternalKeyComparator& icmp,
  144. const std::vector<FileMetaData*>* flist)
  145. : icmp_(icmp), flist_(flist), index_(flist->size()) { // Marks as invalid
  146. }
  147. bool Valid() const override { return index_ < flist_->size(); }
  148. void Seek(const Slice& target) override {
  149. index_ = FindFile(icmp_, *flist_, target);
  150. }
  151. void SeekToFirst() override { index_ = 0; }
  152. void SeekToLast() override {
  153. index_ = flist_->empty() ? 0 : flist_->size() - 1;
  154. }
  155. void Next() override {
  156. assert(Valid());
  157. index_++;
  158. }
  159. void Prev() override {
  160. assert(Valid());
  161. if (index_ == 0) {
  162. index_ = flist_->size(); // Marks as invalid
  163. } else {
  164. index_--;
  165. }
  166. }
  167. Slice key() const override {
  168. assert(Valid());
  169. return (*flist_)[index_]->largest.Encode();
  170. }
  171. Slice value() const override {
  172. assert(Valid());
  173. EncodeFixed64(value_buf_, (*flist_)[index_]->number);
  174. EncodeFixed64(value_buf_ + 8, (*flist_)[index_]->file_size);
  175. return Slice(value_buf_, sizeof(value_buf_));
  176. }
  177. Status status() const override { return Status::OK(); }
  178. private:
  179. const InternalKeyComparator icmp_;
  180. const std::vector<FileMetaData*>* const flist_;
  181. uint32_t index_;
  182. // Backing store for value(). Holds the file number and size.
  183. mutable char value_buf_[16];
  184. };
  185. static Iterator* GetFileIterator(void* arg, const ReadOptions& options,
  186. const Slice& file_value) {
  187. TableCache* cache = reinterpret_cast<TableCache*>(arg);
  188. if (file_value.size() != 16) {
  189. return NewErrorIterator(
  190. Status::Corruption("FileReader invoked with unexpected value"));
  191. } else {
  192. return cache->NewIterator(options, DecodeFixed64(file_value.data()),
  193. DecodeFixed64(file_value.data() + 8));
  194. }
  195. }
  196. Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
  197. int level) const {
  198. return NewTwoLevelIterator(
  199. new LevelFileNumIterator(vset_->icmp_, &files_[level]), &GetFileIterator,
  200. vset_->table_cache_, options);
  201. }
  202. void Version::AddIterators(const ReadOptions& options,
  203. std::vector<Iterator*>* iters) {
  204. // Merge all level zero files together since they may overlap
  205. for (size_t i = 0; i < files_[0].size(); i++) {
  206. iters->push_back(vset_->table_cache_->NewIterator(
  207. options, files_[0][i]->number, files_[0][i]->file_size));
  208. }
  209. // For levels > 0, we can use a concatenating iterator that sequentially
  210. // walks through the non-overlapping files in the level, opening them
  211. // lazily.
  212. for (int level = 1; level < config::kNumLevels; level++) {
  213. if (!files_[level].empty()) {
  214. iters->push_back(NewConcatenatingIterator(options, level));
  215. }
  216. }
  217. }
  218. // Callback from TableCache::Get()
  219. namespace {
  220. enum SaverState {
  221. kNotFound,
  222. kFound,
  223. kDeleted,
  224. kCorrupt,
  225. };
  226. struct Saver {
  227. SaverState state;
  228. const Comparator* ucmp;
  229. Slice user_key;
  230. std::string* value;
  231. };
  232. } // namespace
  233. static void SaveValue(void* arg, const Slice& ikey, const Slice& v) {
  234. Saver* s = reinterpret_cast<Saver*>(arg);
  235. ParsedInternalKey parsed_key;
  236. if (!ParseInternalKey(ikey, &parsed_key)) {
  237. s->state = kCorrupt;
  238. } else {
  239. if (s->ucmp->Compare(parsed_key.user_key, s->user_key) == 0) {
  240. s->state = (parsed_key.type == kTypeValue) ? kFound : kDeleted;
  241. if (s->state == kFound) {
  242. s->value->assign(v.data(), v.size());
  243. }
  244. }
  245. }
  246. }
  247. static bool NewestFirst(FileMetaData* a, FileMetaData* b) {
  248. return a->number > b->number;
  249. }
  250. void Version::ForEachOverlapping(Slice user_key, Slice internal_key, void* arg,
  251. bool (*func)(void*, int, FileMetaData*)) {
  252. const Comparator* ucmp = vset_->icmp_.user_comparator();
  253. // Search level-0 in order from newest to oldest.
  254. std::vector<FileMetaData*> tmp;
  255. tmp.reserve(files_[0].size());
  256. for (uint32_t i = 0; i < files_[0].size(); i++) {
  257. FileMetaData* f = files_[0][i];
  258. if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
  259. ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
  260. tmp.push_back(f);
  261. }
  262. }
  263. if (!tmp.empty()) {
  264. std::sort(tmp.begin(), tmp.end(), NewestFirst);
  265. for (uint32_t i = 0; i < tmp.size(); i++) {
  266. if (!(*func)(arg, 0, tmp[i])) {
  267. return;
  268. }
  269. }
  270. }
  271. // Search other levels.
  272. for (int level = 1; level < config::kNumLevels; level++) {
  273. size_t num_files = files_[level].size();
  274. if (num_files == 0) continue;
  275. // Binary search to find earliest index whose largest key >= internal_key.
  276. uint32_t index = FindFile(vset_->icmp_, files_[level], internal_key);
  277. if (index < num_files) {
  278. FileMetaData* f = files_[level][index];
  279. if (ucmp->Compare(user_key, f->smallest.user_key()) < 0) {
  280. // All of "f" is past any data for user_key
  281. } else {
  282. if (!(*func)(arg, level, f)) {
  283. return;
  284. }
  285. }
  286. }
  287. }
  288. }
  289. Status Version::Get(const ReadOptions& options, const LookupKey& k,
  290. std::string* value, GetStats* stats) {
  291. stats->seek_file = nullptr;
  292. stats->seek_file_level = -1;
  293. struct State {
  294. Saver saver;
  295. GetStats* stats;
  296. const ReadOptions* options;
  297. Slice ikey;
  298. FileMetaData* last_file_read;
  299. int last_file_read_level;
  300. VersionSet* vset;
  301. Status s;
  302. bool found;
  303. static bool Match(void* arg, int level, FileMetaData* f) {
  304. State* state = reinterpret_cast<State*>(arg);
  305. if (state->stats->seek_file == nullptr &&
  306. state->last_file_read != nullptr) {
  307. // We have had more than one seek for this read. Charge the 1st file.
  308. state->stats->seek_file = state->last_file_read;
  309. state->stats->seek_file_level = state->last_file_read_level;
  310. }
  311. state->last_file_read = f;
  312. state->last_file_read_level = level;
  313. state->s = state->vset->table_cache_->Get(*state->options, f->number,
  314. f->file_size, state->ikey,
  315. &state->saver, SaveValue);
  316. if (!state->s.ok()) {
  317. state->found = true;
  318. return false;
  319. }
  320. switch (state->saver.state) {
  321. case kNotFound:
  322. return true; // Keep searching in other files
  323. case kFound:
  324. state->found = true;
  325. return false;
  326. case kDeleted:
  327. return false;
  328. case kCorrupt:
  329. state->s =
  330. Status::Corruption("corrupted key for ", state->saver.user_key);
  331. state->found = true;
  332. return false;
  333. }
  334. // Not reached. Added to avoid false compilation warnings of
  335. // "control reaches end of non-void function".
  336. return false;
  337. }
  338. };
  339. State state;
  340. state.found = false;
  341. state.stats = stats;
  342. state.last_file_read = nullptr;
  343. state.last_file_read_level = -1;
  344. state.options = &options;
  345. state.ikey = k.internal_key();
  346. state.vset = vset_;
  347. state.saver.state = kNotFound;
  348. state.saver.ucmp = vset_->icmp_.user_comparator();
  349. state.saver.user_key = k.user_key();
  350. state.saver.value = value;
  351. ForEachOverlapping(state.saver.user_key, state.ikey, &state, &State::Match);
  352. return state.found ? state.s : Status::NotFound(Slice());
  353. }
  354. bool Version::UpdateStats(const GetStats& stats) {
  355. FileMetaData* f = stats.seek_file;
  356. if (f != nullptr) {
  357. f->allowed_seeks--;
  358. if (f->allowed_seeks <= 0 && file_to_compact_ == nullptr) {
  359. file_to_compact_ = f;
  360. file_to_compact_level_ = stats.seek_file_level;
  361. return true;
  362. }
  363. }
  364. return false;
  365. }
  366. bool Version::RecordReadSample(Slice internal_key) {
  367. ParsedInternalKey ikey;
  368. if (!ParseInternalKey(internal_key, &ikey)) {
  369. return false;
  370. }
  371. struct State {
  372. GetStats stats; // Holds first matching file
  373. int matches;
  374. static bool Match(void* arg, int level, FileMetaData* f) {
  375. State* state = reinterpret_cast<State*>(arg);
  376. state->matches++;
  377. if (state->matches == 1) {
  378. // Remember first match.
  379. state->stats.seek_file = f;
  380. state->stats.seek_file_level = level;
  381. }
  382. // We can stop iterating once we have a second match.
  383. return state->matches < 2;
  384. }
  385. };
  386. State state;
  387. state.matches = 0;
  388. ForEachOverlapping(ikey.user_key, internal_key, &state, &State::Match);
  389. // Must have at least two matches since we want to merge across
  390. // files. But what if we have a single file that contains many
  391. // overwrites and deletions? Should we have another mechanism for
  392. // finding such files?
  393. if (state.matches >= 2) {
  394. // 1MB cost is about 1 seek (see comment in Builder::Apply).
  395. return UpdateStats(state.stats);
  396. }
  397. return false;
  398. }
  399. void Version::Ref() { ++refs_; }
  400. void Version::Unref() {
  401. assert(this != &vset_->dummy_versions_);
  402. assert(refs_ >= 1);
  403. --refs_;
  404. if (refs_ == 0) {
  405. delete this;
  406. }
  407. }
  408. bool Version::OverlapInLevel(int level, const Slice* smallest_user_key,
  409. const Slice* largest_user_key) {
  410. return SomeFileOverlapsRange(vset_->icmp_, (level > 0), files_[level],
  411. smallest_user_key, largest_user_key);
  412. }
  413. int Version::PickLevelForMemTableOutput(const Slice& smallest_user_key,
  414. const Slice& largest_user_key) {
  415. int level = 0;
  416. if (!OverlapInLevel(0, &smallest_user_key, &largest_user_key)) {
  417. // Push to next level if there is no overlap in next level,
  418. // and the #bytes overlapping in the level after that are limited.
  419. InternalKey start(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek);
  420. InternalKey limit(largest_user_key, 0, static_cast<ValueType>(0));
  421. std::vector<FileMetaData*> overlaps;
  422. while (level < config::kMaxMemCompactLevel) {
  423. if (OverlapInLevel(level + 1, &smallest_user_key, &largest_user_key)) {
  424. break;
  425. }
  426. if (level + 2 < config::kNumLevels) {
  427. // Check that file does not overlap too many grandparent bytes.
  428. GetOverlappingInputs(level + 2, &start, &limit, &overlaps);
  429. const int64_t sum = TotalFileSize(overlaps);
  430. if (sum > MaxGrandParentOverlapBytes(vset_->options_)) {
  431. break;
  432. }
  433. }
  434. level++;
  435. }
  436. }
  437. return level;
  438. }
  439. // Store in "*inputs" all files in "level" that overlap [begin,end]
  440. void Version::GetOverlappingInputs(int level, const InternalKey* begin,
  441. const InternalKey* end,
  442. std::vector<FileMetaData*>* inputs) {
  443. assert(level >= 0);
  444. assert(level < config::kNumLevels);
  445. inputs->clear();
  446. Slice user_begin, user_end;
  447. if (begin != nullptr) {
  448. user_begin = begin->user_key();
  449. }
  450. if (end != nullptr) {
  451. user_end = end->user_key();
  452. }
  453. const Comparator* user_cmp = vset_->icmp_.user_comparator();
  454. for (size_t i = 0; i < files_[level].size();) {
  455. FileMetaData* f = files_[level][i++];
  456. const Slice file_start = f->smallest.user_key();
  457. const Slice file_limit = f->largest.user_key();
  458. if (begin != nullptr && user_cmp->Compare(file_limit, user_begin) < 0) {
  459. // "f" is completely before specified range; skip it
  460. } else if (end != nullptr && user_cmp->Compare(file_start, user_end) > 0) {
  461. // "f" is completely after specified range; skip it
  462. } else {
  463. inputs->push_back(f);
  464. if (level == 0) {
  465. // Level-0 files may overlap each other. So check if the newly
  466. // added file has expanded the range. If so, restart search.
  467. if (begin != nullptr && user_cmp->Compare(file_start, user_begin) < 0) {
  468. user_begin = file_start;
  469. inputs->clear();
  470. i = 0;
  471. } else if (end != nullptr &&
  472. user_cmp->Compare(file_limit, user_end) > 0) {
  473. user_end = file_limit;
  474. inputs->clear();
  475. i = 0;
  476. }
  477. }
  478. }
  479. }
  480. }
  481. std::string Version::DebugString() const {
  482. std::string r;
  483. for (int level = 0; level < config::kNumLevels; level++) {
  484. // E.g.,
  485. // --- level 1 ---
  486. // 17:123['a' .. 'd']
  487. // 20:43['e' .. 'g']
  488. r.append("--- level ");
  489. AppendNumberTo(&r, level);
  490. r.append(" ---\n");
  491. const std::vector<FileMetaData*>& files = files_[level];
  492. for (size_t i = 0; i < files.size(); i++) {
  493. r.push_back(' ');
  494. AppendNumberTo(&r, files[i]->number);
  495. r.push_back(':');
  496. AppendNumberTo(&r, files[i]->file_size);
  497. r.append("[");
  498. r.append(files[i]->smallest.DebugString());
  499. r.append(" .. ");
  500. r.append(files[i]->largest.DebugString());
  501. r.append("]\n");
  502. }
  503. }
  504. return r;
  505. }
  506. // A helper class so we can efficiently apply a whole sequence
  507. // of edits to a particular state without creating intermediate
  508. // Versions that contain full copies of the intermediate state.
  509. class VersionSet::Builder {
  510. private:
  511. // Helper to sort by v->files_[file_number].smallest
  512. struct BySmallestKey {
  513. const InternalKeyComparator* internal_comparator;
  514. bool operator()(FileMetaData* f1, FileMetaData* f2) const {
  515. int r = internal_comparator->Compare(f1->smallest, f2->smallest);
  516. if (r != 0) {
  517. return (r < 0);
  518. } else {
  519. // Break ties by file number
  520. return (f1->number < f2->number);
  521. }
  522. }
  523. };
  524. typedef std::set<FileMetaData*, BySmallestKey> FileSet;
  525. struct LevelState {
  526. std::set<uint64_t> deleted_files;
  527. FileSet* added_files;
  528. };
  529. VersionSet* vset_;
  530. Version* base_;
  531. LevelState levels_[config::kNumLevels];
  532. public:
  533. // Initialize a builder with the files from *base and other info from *vset
  534. Builder(VersionSet* vset, Version* base) : vset_(vset), base_(base) {
  535. base_->Ref();
  536. BySmallestKey cmp;
  537. cmp.internal_comparator = &vset_->icmp_;
  538. for (int level = 0; level < config::kNumLevels; level++) {
  539. levels_[level].added_files = new FileSet(cmp);
  540. }
  541. }
  542. ~Builder() {
  543. for (int level = 0; level < config::kNumLevels; level++) {
  544. const FileSet* added = levels_[level].added_files;
  545. std::vector<FileMetaData*> to_unref;
  546. to_unref.reserve(added->size());
  547. for (FileSet::const_iterator it = added->begin(); it != added->end();
  548. ++it) {
  549. to_unref.push_back(*it);
  550. }
  551. delete added;
  552. for (uint32_t i = 0; i < to_unref.size(); i++) {
  553. FileMetaData* f = to_unref[i];
  554. f->refs--;
  555. if (f->refs <= 0) {
  556. delete f;
  557. }
  558. }
  559. }
  560. base_->Unref();
  561. }
  562. // Apply all of the edits in *edit to the current state.
  563. void Apply(VersionEdit* edit) {
  564. // Update compaction pointers
  565. for (size_t i = 0; i < edit->compact_pointers_.size(); i++) {
  566. const int level = edit->compact_pointers_[i].first;
  567. vset_->compact_pointer_[level] =
  568. edit->compact_pointers_[i].second.Encode().ToString();
  569. }
  570. // Delete files
  571. for (const auto& deleted_file_set_kvp : edit->deleted_files_) {
  572. const int level = deleted_file_set_kvp.first;
  573. const uint64_t number = deleted_file_set_kvp.second;
  574. levels_[level].deleted_files.insert(number);
  575. }
  576. // Add new files
  577. for (size_t i = 0; i < edit->new_files_.size(); i++) {
  578. const int level = edit->new_files_[i].first;
  579. FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
  580. f->refs = 1;
  581. // We arrange to automatically compact this file after
  582. // a certain number of seeks. Let's assume:
  583. // (1) One seek costs 10ms
  584. // (2) Writing or reading 1MB costs 10ms (100MB/s)
  585. // (3) A compaction of 1MB does 25MB of IO:
  586. // 1MB read from this level
  587. // 10-12MB read from next level (boundaries may be misaligned)
  588. // 10-12MB written to next level
  589. // This implies that 25 seeks cost the same as the compaction
  590. // of 1MB of data. I.e., one seek costs approximately the
  591. // same as the compaction of 40KB of data. We are a little
  592. // conservative and allow approximately one seek for every 16KB
  593. // of data before triggering a compaction.
  594. f->allowed_seeks = static_cast<int>((f->file_size / 16384U));
  595. if (f->allowed_seeks < 100) f->allowed_seeks = 100;
  596. levels_[level].deleted_files.erase(f->number);
  597. levels_[level].added_files->insert(f);
  598. }
  599. }
  600. // Save the current state in *v.
  601. void SaveTo(Version* v) {
  602. BySmallestKey cmp;
  603. cmp.internal_comparator = &vset_->icmp_;
  604. for (int level = 0; level < config::kNumLevels; level++) {
  605. // Merge the set of added files with the set of pre-existing files.
  606. // Drop any deleted files. Store the result in *v.
  607. const std::vector<FileMetaData*>& base_files = base_->files_[level];
  608. std::vector<FileMetaData*>::const_iterator base_iter = base_files.begin();
  609. std::vector<FileMetaData*>::const_iterator base_end = base_files.end();
  610. const FileSet* added_files = levels_[level].added_files;
  611. v->files_[level].reserve(base_files.size() + added_files->size());
  612. for (const auto& added_file : *added_files) {
  613. // Add all smaller files listed in base_
  614. for (std::vector<FileMetaData*>::const_iterator bpos =
  615. std::upper_bound(base_iter, base_end, added_file, cmp);
  616. base_iter != bpos; ++base_iter) {
  617. MaybeAddFile(v, level, *base_iter);
  618. }
  619. MaybeAddFile(v, level, added_file);
  620. }
  621. // Add remaining base files
  622. for (; base_iter != base_end; ++base_iter) {
  623. MaybeAddFile(v, level, *base_iter);
  624. }
  625. #ifndef NDEBUG
  626. // Make sure there is no overlap in levels > 0
  627. if (level > 0) {
  628. for (uint32_t i = 1; i < v->files_[level].size(); i++) {
  629. const InternalKey& prev_end = v->files_[level][i - 1]->largest;
  630. const InternalKey& this_begin = v->files_[level][i]->smallest;
  631. if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) {
  632. std::fprintf(stderr, "overlapping ranges in same level %s vs. %s\n",
  633. prev_end.DebugString().c_str(),
  634. this_begin.DebugString().c_str());
  635. std::abort();
  636. }
  637. }
  638. }
  639. #endif
  640. }
  641. }
  642. void MaybeAddFile(Version* v, int level, FileMetaData* f) {
  643. if (levels_[level].deleted_files.count(f->number) > 0) {
  644. // File is deleted: do nothing
  645. } else {
  646. std::vector<FileMetaData*>* files = &v->files_[level];
  647. if (level > 0 && !files->empty()) {
  648. // Must not overlap
  649. assert(vset_->icmp_.Compare((*files)[files->size() - 1]->largest,
  650. f->smallest) < 0);
  651. }
  652. f->refs++;
  653. files->push_back(f);
  654. }
  655. }
  656. };
  657. VersionSet::VersionSet(const std::string& dbname, const Options* options,
  658. TableCache* table_cache,
  659. const InternalKeyComparator* cmp)
  660. : env_(options->env),
  661. dbname_(dbname),
  662. options_(options),
  663. table_cache_(table_cache),
  664. icmp_(*cmp),
  665. next_file_number_(2),
  666. manifest_file_number_(0), // Filled by Recover()
  667. last_sequence_(0),
  668. log_number_(0),
  669. prev_log_number_(0),
  670. descriptor_file_(nullptr),
  671. descriptor_log_(nullptr),
  672. dummy_versions_(this),
  673. current_(nullptr) {
  674. AppendVersion(new Version(this));
  675. }
  676. VersionSet::~VersionSet() {
  677. current_->Unref();
  678. assert(dummy_versions_.next_ == &dummy_versions_); // List must be empty
  679. delete descriptor_log_;
  680. delete descriptor_file_;
  681. }
  682. void VersionSet::AppendVersion(Version* v) {
  683. // Make "v" current
  684. assert(v->refs_ == 0);
  685. assert(v != current_);
  686. if (current_ != nullptr) {
  687. current_->Unref();
  688. }
  689. current_ = v;
  690. v->Ref();
  691. // Append to linked list
  692. v->prev_ = dummy_versions_.prev_;
  693. v->next_ = &dummy_versions_;
  694. v->prev_->next_ = v;
  695. v->next_->prev_ = v;
  696. }
  697. Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) {
  698. if (edit->has_log_number_) {
  699. assert(edit->log_number_ >= log_number_);
  700. assert(edit->log_number_ < next_file_number_);
  701. } else {
  702. edit->SetLogNumber(log_number_);
  703. }
  704. if (!edit->has_prev_log_number_) {
  705. edit->SetPrevLogNumber(prev_log_number_);
  706. }
  707. edit->SetNextFile(next_file_number_);
  708. edit->SetLastSequence(last_sequence_);
  709. Version* v = new Version(this);
  710. {
  711. Builder builder(this, current_);
  712. builder.Apply(edit);
  713. builder.SaveTo(v);
  714. }
  715. Finalize(v);
  716. // Initialize new descriptor log file if necessary by creating
  717. // a temporary file that contains a snapshot of the current version.
  718. std::string new_manifest_file;
  719. Status s;
  720. if (descriptor_log_ == nullptr) {
  721. // No reason to unlock *mu here since we only hit this path in the
  722. // first call to LogAndApply (when opening the database).
  723. assert(descriptor_file_ == nullptr);
  724. new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
  725. edit->SetNextFile(next_file_number_);
  726. s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
  727. if (s.ok()) {
  728. descriptor_log_ = new log::Writer(descriptor_file_);
  729. s = WriteSnapshot(descriptor_log_);
  730. }
  731. }
  732. // Unlock during expensive MANIFEST log write
  733. {
  734. mu->Unlock();
  735. // Write new record to MANIFEST log
  736. if (s.ok()) {
  737. std::string record;
  738. edit->EncodeTo(&record);
  739. s = descriptor_log_->AddRecord(record);
  740. if (s.ok()) {
  741. s = descriptor_file_->Sync();
  742. }
  743. if (!s.ok()) {
  744. Log(options_->info_log, "MANIFEST write: %s\n", s.ToString().c_str());
  745. }
  746. }
  747. // If we just created a new descriptor file, install it by writing a
  748. // new CURRENT file that points to it.
  749. if (s.ok() && !new_manifest_file.empty()) {
  750. s = SetCurrentFile(env_, dbname_, manifest_file_number_);
  751. }
  752. mu->Lock();
  753. }
  754. // Install the new version
  755. if (s.ok()) {
  756. AppendVersion(v);
  757. log_number_ = edit->log_number_;
  758. prev_log_number_ = edit->prev_log_number_;
  759. } else {
  760. delete v;
  761. if (!new_manifest_file.empty()) {
  762. delete descriptor_log_;
  763. delete descriptor_file_;
  764. descriptor_log_ = nullptr;
  765. descriptor_file_ = nullptr;
  766. env_->RemoveFile(new_manifest_file);
  767. }
  768. }
  769. return s;
  770. }
  771. Status VersionSet::Recover(bool* save_manifest) {
  772. struct LogReporter : public log::Reader::Reporter {
  773. Status* status;
  774. void Corruption(size_t bytes, const Status& s) override {
  775. if (this->status->ok()) *this->status = s;
  776. }
  777. };
  778. // Read "CURRENT" file, which contains a pointer to the current manifest file
  779. std::string current;
  780. Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  781. if (!s.ok()) {
  782. return s;
  783. }
  784. if (current.empty() || current[current.size() - 1] != '\n') {
  785. return Status::Corruption("CURRENT file does not end with newline");
  786. }
  787. current.resize(current.size() - 1);
  788. std::string dscname = dbname_ + "/" + current;
  789. SequentialFile* file;
  790. s = env_->NewSequentialFile(dscname, &file);
  791. if (!s.ok()) {
  792. if (s.IsNotFound()) {
  793. return Status::Corruption("CURRENT points to a non-existent file",
  794. s.ToString());
  795. }
  796. return s;
  797. }
  798. bool have_log_number = false;
  799. bool have_prev_log_number = false;
  800. bool have_next_file = false;
  801. bool have_last_sequence = false;
  802. uint64_t next_file = 0;
  803. uint64_t last_sequence = 0;
  804. uint64_t log_number = 0;
  805. uint64_t prev_log_number = 0;
  806. Builder builder(this, current_);
  807. {
  808. LogReporter reporter;
  809. reporter.status = &s;
  810. log::Reader reader(file, &reporter, true /*checksum*/,
  811. 0 /*initial_offset*/);
  812. Slice record;
  813. std::string scratch;
  814. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  815. VersionEdit edit;
  816. s = edit.DecodeFrom(record);
  817. if (s.ok()) {
  818. if (edit.has_comparator_ &&
  819. edit.comparator_ != icmp_.user_comparator()->Name()) {
  820. s = Status::InvalidArgument(
  821. edit.comparator_ + " does not match existing comparator ",
  822. icmp_.user_comparator()->Name());
  823. }
  824. }
  825. if (s.ok()) {
  826. builder.Apply(&edit);
  827. }
  828. if (edit.has_log_number_) {
  829. log_number = edit.log_number_;
  830. have_log_number = true;
  831. }
  832. if (edit.has_prev_log_number_) {
  833. prev_log_number = edit.prev_log_number_;
  834. have_prev_log_number = true;
  835. }
  836. if (edit.has_next_file_number_) {
  837. next_file = edit.next_file_number_;
  838. have_next_file = true;
  839. }
  840. if (edit.has_last_sequence_) {
  841. last_sequence = edit.last_sequence_;
  842. have_last_sequence = true;
  843. }
  844. }
  845. }
  846. delete file;
  847. file = nullptr;
  848. if (s.ok()) {
  849. if (!have_next_file) {
  850. s = Status::Corruption("no meta-nextfile entry in descriptor");
  851. } else if (!have_log_number) {
  852. s = Status::Corruption("no meta-lognumber entry in descriptor");
  853. } else if (!have_last_sequence) {
  854. s = Status::Corruption("no last-sequence-number entry in descriptor");
  855. }
  856. if (!have_prev_log_number) {
  857. prev_log_number = 0;
  858. }
  859. MarkFileNumberUsed(prev_log_number);
  860. MarkFileNumberUsed(log_number);
  861. }
  862. if (s.ok()) {
  863. Version* v = new Version(this);
  864. builder.SaveTo(v);
  865. // Install recovered version
  866. Finalize(v);
  867. AppendVersion(v);
  868. manifest_file_number_ = next_file;
  869. next_file_number_ = next_file + 1;
  870. last_sequence_ = last_sequence;
  871. log_number_ = log_number;
  872. prev_log_number_ = prev_log_number;
  873. // See if we can reuse the existing MANIFEST file.
  874. if (ReuseManifest(dscname, current)) {
  875. // No need to save new manifest
  876. } else {
  877. *save_manifest = true;
  878. }
  879. }
  880. return s;
  881. }
  882. bool VersionSet::ReuseManifest(const std::string& dscname,
  883. const std::string& dscbase) {
  884. if (!options_->reuse_logs) {
  885. return false;
  886. }
  887. FileType manifest_type;
  888. uint64_t manifest_number;
  889. uint64_t manifest_size;
  890. if (!ParseFileName(dscbase, &manifest_number, &manifest_type) ||
  891. manifest_type != kDescriptorFile ||
  892. !env_->GetFileSize(dscname, &manifest_size).ok() ||
  893. // Make new compacted MANIFEST if old one is too big
  894. manifest_size >= TargetFileSize(options_)) {
  895. return false;
  896. }
  897. assert(descriptor_file_ == nullptr);
  898. assert(descriptor_log_ == nullptr);
  899. Status r = env_->NewAppendableFile(dscname, &descriptor_file_);
  900. if (!r.ok()) {
  901. Log(options_->info_log, "Reuse MANIFEST: %s\n", r.ToString().c_str());
  902. assert(descriptor_file_ == nullptr);
  903. return false;
  904. }
  905. Log(options_->info_log, "Reusing MANIFEST %s\n", dscname.c_str());
  906. descriptor_log_ = new log::Writer(descriptor_file_, manifest_size);
  907. manifest_file_number_ = manifest_number;
  908. return true;
  909. }
  910. void VersionSet::MarkFileNumberUsed(uint64_t number) {
  911. if (next_file_number_ <= number) {
  912. next_file_number_ = number + 1;
  913. }
  914. }
  915. void VersionSet::Finalize(Version* v) {
  916. // Precomputed best level for next compaction
  917. int best_level = -1;
  918. double best_score = -1;
  919. for (int level = 0; level < config::kNumLevels - 1; level++) {
  920. double score;
  921. if (level == 0) {
  922. // We treat level-0 specially by bounding the number of files
  923. // instead of number of bytes for two reasons:
  924. //
  925. // (1) With larger write-buffer sizes, it is nice not to do too
  926. // many level-0 compactions.
  927. //
  928. // (2) The files in level-0 are merged on every read and
  929. // therefore we wish to avoid too many files when the individual
  930. // file size is small (perhaps because of a small write-buffer
  931. // setting, or very high compression ratios, or lots of
  932. // overwrites/deletions).
  933. score = v->files_[level].size() /
  934. static_cast<double>(config::kL0_CompactionTrigger);
  935. } else {
  936. // Compute the ratio of current size to size limit.
  937. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  938. score =
  939. static_cast<double>(level_bytes) / MaxBytesForLevel(options_, level);
  940. }
  941. if (score > best_score) {
  942. best_level = level;
  943. best_score = score;
  944. }
  945. }
  946. v->compaction_level_ = best_level;
  947. v->compaction_score_ = best_score;
  948. }
  949. Status VersionSet::WriteSnapshot(log::Writer* log) {
  950. // TODO: Break up into multiple records to reduce memory usage on recovery?
  951. // Save metadata
  952. VersionEdit edit;
  953. edit.SetComparatorName(icmp_.user_comparator()->Name());
  954. // Save compaction pointers
  955. for (int level = 0; level < config::kNumLevels; level++) {
  956. if (!compact_pointer_[level].empty()) {
  957. InternalKey key;
  958. key.DecodeFrom(compact_pointer_[level]);
  959. edit.SetCompactPointer(level, key);
  960. }
  961. }
  962. // Save files
  963. for (int level = 0; level < config::kNumLevels; level++) {
  964. const std::vector<FileMetaData*>& files = current_->files_[level];
  965. for (size_t i = 0; i < files.size(); i++) {
  966. const FileMetaData* f = files[i];
  967. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  968. }
  969. }
  970. std::string record;
  971. edit.EncodeTo(&record);
  972. return log->AddRecord(record);
  973. }
  974. int VersionSet::NumLevelFiles(int level) const {
  975. assert(level >= 0);
  976. assert(level < config::kNumLevels);
  977. return current_->files_[level].size();
  978. }
  979. const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  980. // Update code if kNumLevels changes
  981. static_assert(config::kNumLevels == 7, "");
  982. std::snprintf(
  983. scratch->buffer, sizeof(scratch->buffer), "files[ %d %d %d %d %d %d %d ]",
  984. int(current_->files_[0].size()), int(current_->files_[1].size()),
  985. int(current_->files_[2].size()), int(current_->files_[3].size()),
  986. int(current_->files_[4].size()), int(current_->files_[5].size()),
  987. int(current_->files_[6].size()));
  988. return scratch->buffer;
  989. }
  990. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  991. uint64_t result = 0;
  992. for (int level = 0; level < config::kNumLevels; level++) {
  993. const std::vector<FileMetaData*>& files = v->files_[level];
  994. for (size_t i = 0; i < files.size(); i++) {
  995. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  996. // Entire file is before "ikey", so just add the file size
  997. result += files[i]->file_size;
  998. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  999. // Entire file is after "ikey", so ignore
  1000. if (level > 0) {
  1001. // Files other than level 0 are sorted by meta->smallest, so
  1002. // no further files in this level will contain data for
  1003. // "ikey".
  1004. break;
  1005. }
  1006. } else {
  1007. // "ikey" falls in the range for this table. Add the
  1008. // approximate offset of "ikey" within the table.
  1009. Table* tableptr;
  1010. Iterator* iter = table_cache_->NewIterator(
  1011. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  1012. if (tableptr != nullptr) {
  1013. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  1014. }
  1015. delete iter;
  1016. }
  1017. }
  1018. }
  1019. return result;
  1020. }
  1021. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  1022. for (Version* v = dummy_versions_.next_; v != &dummy_versions_;
  1023. v = v->next_) {
  1024. for (int level = 0; level < config::kNumLevels; level++) {
  1025. const std::vector<FileMetaData*>& files = v->files_[level];
  1026. for (size_t i = 0; i < files.size(); i++) {
  1027. live->insert(files[i]->number);
  1028. }
  1029. }
  1030. }
  1031. }
  1032. int64_t VersionSet::NumLevelBytes(int level) const {
  1033. assert(level >= 0);
  1034. assert(level < config::kNumLevels);
  1035. return TotalFileSize(current_->files_[level]);
  1036. }
  1037. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  1038. int64_t result = 0;
  1039. std::vector<FileMetaData*> overlaps;
  1040. for (int level = 1; level < config::kNumLevels - 1; level++) {
  1041. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1042. const FileMetaData* f = current_->files_[level][i];
  1043. current_->GetOverlappingInputs(level + 1, &f->smallest, &f->largest,
  1044. &overlaps);
  1045. const int64_t sum = TotalFileSize(overlaps);
  1046. if (sum > result) {
  1047. result = sum;
  1048. }
  1049. }
  1050. }
  1051. return result;
  1052. }
  1053. // Stores the minimal range that covers all entries in inputs in
  1054. // *smallest, *largest.
  1055. // REQUIRES: inputs is not empty
  1056. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  1057. InternalKey* smallest, InternalKey* largest) {
  1058. assert(!inputs.empty());
  1059. smallest->Clear();
  1060. largest->Clear();
  1061. for (size_t i = 0; i < inputs.size(); i++) {
  1062. FileMetaData* f = inputs[i];
  1063. if (i == 0) {
  1064. *smallest = f->smallest;
  1065. *largest = f->largest;
  1066. } else {
  1067. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  1068. *smallest = f->smallest;
  1069. }
  1070. if (icmp_.Compare(f->largest, *largest) > 0) {
  1071. *largest = f->largest;
  1072. }
  1073. }
  1074. }
  1075. }
  1076. // Stores the minimal range that covers all entries in inputs1 and inputs2
  1077. // in *smallest, *largest.
  1078. // REQUIRES: inputs is not empty
  1079. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  1080. const std::vector<FileMetaData*>& inputs2,
  1081. InternalKey* smallest, InternalKey* largest) {
  1082. std::vector<FileMetaData*> all = inputs1;
  1083. all.insert(all.end(), inputs2.begin(), inputs2.end());
  1084. GetRange(all, smallest, largest);
  1085. }
  1086. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  1087. ReadOptions options;
  1088. options.verify_checksums = options_->paranoid_checks;
  1089. options.fill_cache = false;
  1090. // Level-0 files have to be merged together. For other levels,
  1091. // we will make a concatenating iterator per level.
  1092. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  1093. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  1094. Iterator** list = new Iterator*[space];
  1095. int num = 0;
  1096. for (int which = 0; which < 2; which++) {
  1097. if (!c->inputs_[which].empty()) {
  1098. if (c->level() + which == 0) {
  1099. const std::vector<FileMetaData*>& files = c->inputs_[which];
  1100. for (size_t i = 0; i < files.size(); i++) {
  1101. list[num++] = table_cache_->NewIterator(options, files[i]->number,
  1102. files[i]->file_size);
  1103. }
  1104. } else {
  1105. // Create concatenating iterator for the files from this level
  1106. list[num++] = NewTwoLevelIterator(
  1107. new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
  1108. &GetFileIterator, table_cache_, options);
  1109. }
  1110. }
  1111. }
  1112. assert(num <= space);
  1113. Iterator* result = NewMergingIterator(&icmp_, list, num);
  1114. delete[] list;
  1115. return result;
  1116. }
  1117. Compaction* VersionSet::PickCompaction() {
  1118. Compaction* c;
  1119. int level;
  1120. // We prefer compactions triggered by too much data in a level over
  1121. // the compactions triggered by seeks.
  1122. const bool size_compaction = (current_->compaction_score_ >= 1);
  1123. const bool seek_compaction = (current_->file_to_compact_ != nullptr);
  1124. if (size_compaction) {
  1125. level = current_->compaction_level_;
  1126. assert(level >= 0);
  1127. assert(level + 1 < config::kNumLevels);
  1128. c = new Compaction(options_, level);
  1129. // Pick the first file that comes after compact_pointer_[level]
  1130. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1131. FileMetaData* f = current_->files_[level][i];
  1132. if (compact_pointer_[level].empty() ||
  1133. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  1134. c->inputs_[0].push_back(f);
  1135. break;
  1136. }
  1137. }
  1138. if (c->inputs_[0].empty()) {
  1139. // Wrap-around to the beginning of the key space
  1140. c->inputs_[0].push_back(current_->files_[level][0]);
  1141. }
  1142. } else if (seek_compaction) {
  1143. level = current_->file_to_compact_level_;
  1144. c = new Compaction(options_, level);
  1145. c->inputs_[0].push_back(current_->file_to_compact_);
  1146. } else {
  1147. return nullptr;
  1148. }
  1149. c->input_version_ = current_;
  1150. c->input_version_->Ref();
  1151. // Files in level 0 may overlap each other, so pick up all overlapping ones
  1152. if (level == 0) {
  1153. InternalKey smallest, largest;
  1154. GetRange(c->inputs_[0], &smallest, &largest);
  1155. // Note that the next call will discard the file we placed in
  1156. // c->inputs_[0] earlier and replace it with an overlapping set
  1157. // which will include the picked file.
  1158. current_->GetOverlappingInputs(0, &smallest, &largest, &c->inputs_[0]);
  1159. assert(!c->inputs_[0].empty());
  1160. }
  1161. SetupOtherInputs(c);
  1162. return c;
  1163. }
  1164. // Finds the largest key in a vector of files. Returns true if files it not
  1165. // empty.
  1166. bool FindLargestKey(const InternalKeyComparator& icmp,
  1167. const std::vector<FileMetaData*>& files,
  1168. InternalKey* largest_key) {
  1169. if (files.empty()) {
  1170. return false;
  1171. }
  1172. *largest_key = files[0]->largest;
  1173. for (size_t i = 1; i < files.size(); ++i) {
  1174. FileMetaData* f = files[i];
  1175. if (icmp.Compare(f->largest, *largest_key) > 0) {
  1176. *largest_key = f->largest;
  1177. }
  1178. }
  1179. return true;
  1180. }
  1181. // Finds minimum file b2=(l2, u2) in level file for which l2 > u1 and
  1182. // user_key(l2) = user_key(u1)
  1183. FileMetaData* FindSmallestBoundaryFile(
  1184. const InternalKeyComparator& icmp,
  1185. const std::vector<FileMetaData*>& level_files,
  1186. const InternalKey& largest_key) {
  1187. const Comparator* user_cmp = icmp.user_comparator();
  1188. FileMetaData* smallest_boundary_file = nullptr;
  1189. for (size_t i = 0; i < level_files.size(); ++i) {
  1190. FileMetaData* f = level_files[i];
  1191. if (icmp.Compare(f->smallest, largest_key) > 0 &&
  1192. user_cmp->Compare(f->smallest.user_key(), largest_key.user_key()) ==
  1193. 0) {
  1194. if (smallest_boundary_file == nullptr ||
  1195. icmp.Compare(f->smallest, smallest_boundary_file->smallest) < 0) {
  1196. smallest_boundary_file = f;
  1197. }
  1198. }
  1199. }
  1200. return smallest_boundary_file;
  1201. }
  1202. // Extracts the largest file b1 from |compaction_files| and then searches for a
  1203. // b2 in |level_files| for which user_key(u1) = user_key(l2). If it finds such a
  1204. // file b2 (known as a boundary file) it adds it to |compaction_files| and then
  1205. // searches again using this new upper bound.
  1206. //
  1207. // If there are two blocks, b1=(l1, u1) and b2=(l2, u2) and
  1208. // user_key(u1) = user_key(l2), and if we compact b1 but not b2 then a
  1209. // subsequent get operation will yield an incorrect result because it will
  1210. // return the record from b2 in level i rather than from b1 because it searches
  1211. // level by level for records matching the supplied user key.
  1212. //
  1213. // parameters:
  1214. // in level_files: List of files to search for boundary files.
  1215. // in/out compaction_files: List of files to extend by adding boundary files.
  1216. void AddBoundaryInputs(const InternalKeyComparator& icmp,
  1217. const std::vector<FileMetaData*>& level_files,
  1218. std::vector<FileMetaData*>* compaction_files) {
  1219. InternalKey largest_key;
  1220. // Quick return if compaction_files is empty.
  1221. if (!FindLargestKey(icmp, *compaction_files, &largest_key)) {
  1222. return;
  1223. }
  1224. bool continue_searching = true;
  1225. while (continue_searching) {
  1226. FileMetaData* smallest_boundary_file =
  1227. FindSmallestBoundaryFile(icmp, level_files, largest_key);
  1228. // If a boundary file was found advance largest_key, otherwise we're done.
  1229. if (smallest_boundary_file != NULL) {
  1230. compaction_files->push_back(smallest_boundary_file);
  1231. largest_key = smallest_boundary_file->largest;
  1232. } else {
  1233. continue_searching = false;
  1234. }
  1235. }
  1236. }
  1237. void VersionSet::SetupOtherInputs(Compaction* c) {
  1238. const int level = c->level();
  1239. InternalKey smallest, largest;
  1240. AddBoundaryInputs(icmp_, current_->files_[level], &c->inputs_[0]);
  1241. GetRange(c->inputs_[0], &smallest, &largest);
  1242. current_->GetOverlappingInputs(level + 1, &smallest, &largest,
  1243. &c->inputs_[1]);
  1244. // Get entire range covered by compaction
  1245. InternalKey all_start, all_limit;
  1246. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1247. // See if we can grow the number of inputs in "level" without
  1248. // changing the number of "level+1" files we pick up.
  1249. if (!c->inputs_[1].empty()) {
  1250. std::vector<FileMetaData*> expanded0;
  1251. current_->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0);
  1252. AddBoundaryInputs(icmp_, current_->files_[level], &expanded0);
  1253. const int64_t inputs0_size = TotalFileSize(c->inputs_[0]);
  1254. const int64_t inputs1_size = TotalFileSize(c->inputs_[1]);
  1255. const int64_t expanded0_size = TotalFileSize(expanded0);
  1256. if (expanded0.size() > c->inputs_[0].size() &&
  1257. inputs1_size + expanded0_size <
  1258. ExpandedCompactionByteSizeLimit(options_)) {
  1259. InternalKey new_start, new_limit;
  1260. GetRange(expanded0, &new_start, &new_limit);
  1261. std::vector<FileMetaData*> expanded1;
  1262. current_->GetOverlappingInputs(level + 1, &new_start, &new_limit,
  1263. &expanded1);
  1264. if (expanded1.size() == c->inputs_[1].size()) {
  1265. Log(options_->info_log,
  1266. "Expanding@%d %d+%d (%ld+%ld bytes) to %d+%d (%ld+%ld bytes)\n",
  1267. level, int(c->inputs_[0].size()), int(c->inputs_[1].size()),
  1268. long(inputs0_size), long(inputs1_size), int(expanded0.size()),
  1269. int(expanded1.size()), long(expanded0_size), long(inputs1_size));
  1270. smallest = new_start;
  1271. largest = new_limit;
  1272. c->inputs_[0] = expanded0;
  1273. c->inputs_[1] = expanded1;
  1274. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1275. }
  1276. }
  1277. }
  1278. // Compute the set of grandparent files that overlap this compaction
  1279. // (parent == level+1; grandparent == level+2)
  1280. if (level + 2 < config::kNumLevels) {
  1281. current_->GetOverlappingInputs(level + 2, &all_start, &all_limit,
  1282. &c->grandparents_);
  1283. }
  1284. // Update the place where we will do the next compaction for this level.
  1285. // We update this immediately instead of waiting for the VersionEdit
  1286. // to be applied so that if the compaction fails, we will try a different
  1287. // key range next time.
  1288. compact_pointer_[level] = largest.Encode().ToString();
  1289. c->edit_.SetCompactPointer(level, largest);
  1290. }
  1291. Compaction* VersionSet::CompactRange(int level, const InternalKey* begin,
  1292. const InternalKey* end) {
  1293. std::vector<FileMetaData*> inputs;
  1294. current_->GetOverlappingInputs(level, begin, end, &inputs);
  1295. if (inputs.empty()) {
  1296. return nullptr;
  1297. }
  1298. // Avoid compacting too much in one shot in case the range is large.
  1299. // But we cannot do this for level-0 since level-0 files can overlap
  1300. // and we must not pick one file and drop another older file if the
  1301. // two files overlap.
  1302. if (level > 0) {
  1303. const uint64_t limit = MaxFileSizeForLevel(options_, level);
  1304. uint64_t total = 0;
  1305. for (size_t i = 0; i < inputs.size(); i++) {
  1306. uint64_t s = inputs[i]->file_size;
  1307. total += s;
  1308. if (total >= limit) {
  1309. inputs.resize(i + 1);
  1310. break;
  1311. }
  1312. }
  1313. }
  1314. Compaction* c = new Compaction(options_, level);
  1315. c->input_version_ = current_;
  1316. c->input_version_->Ref();
  1317. c->inputs_[0] = inputs;
  1318. SetupOtherInputs(c);
  1319. return c;
  1320. }
  1321. Compaction::Compaction(const Options* options, int level)
  1322. : level_(level),
  1323. max_output_file_size_(MaxFileSizeForLevel(options, level)),
  1324. input_version_(nullptr),
  1325. grandparent_index_(0),
  1326. seen_key_(false),
  1327. overlapped_bytes_(0) {
  1328. for (int i = 0; i < config::kNumLevels; i++) {
  1329. level_ptrs_[i] = 0;
  1330. }
  1331. }
  1332. Compaction::~Compaction() {
  1333. if (input_version_ != nullptr) {
  1334. input_version_->Unref();
  1335. }
  1336. }
  1337. bool Compaction::IsTrivialMove() const {
  1338. const VersionSet* vset = input_version_->vset_;
  1339. // Avoid a move if there is lots of overlapping grandparent data.
  1340. // Otherwise, the move could create a parent file that will require
  1341. // a very expensive merge later on.
  1342. return (num_input_files(0) == 1 && num_input_files(1) == 0 &&
  1343. TotalFileSize(grandparents_) <=
  1344. MaxGrandParentOverlapBytes(vset->options_));
  1345. }
  1346. void Compaction::AddInputDeletions(VersionEdit* edit) {
  1347. for (int which = 0; which < 2; which++) {
  1348. for (size_t i = 0; i < inputs_[which].size(); i++) {
  1349. edit->RemoveFile(level_ + which, inputs_[which][i]->number);
  1350. }
  1351. }
  1352. }
  1353. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  1354. // Maybe use binary search to find right entry instead of linear search?
  1355. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  1356. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  1357. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  1358. while (level_ptrs_[lvl] < files.size()) {
  1359. FileMetaData* f = files[level_ptrs_[lvl]];
  1360. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  1361. // We've advanced far enough
  1362. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  1363. // Key falls in this file's range, so definitely not base level
  1364. return false;
  1365. }
  1366. break;
  1367. }
  1368. level_ptrs_[lvl]++;
  1369. }
  1370. }
  1371. return true;
  1372. }
  1373. bool Compaction::ShouldStopBefore(const Slice& internal_key) {
  1374. const VersionSet* vset = input_version_->vset_;
  1375. // Scan to find earliest grandparent file that contains key.
  1376. const InternalKeyComparator* icmp = &vset->icmp_;
  1377. while (grandparent_index_ < grandparents_.size() &&
  1378. icmp->Compare(internal_key,
  1379. grandparents_[grandparent_index_]->largest.Encode()) >
  1380. 0) {
  1381. if (seen_key_) {
  1382. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  1383. }
  1384. grandparent_index_++;
  1385. }
  1386. seen_key_ = true;
  1387. if (overlapped_bytes_ > MaxGrandParentOverlapBytes(vset->options_)) {
  1388. // Too much overlap for current output; start new output
  1389. overlapped_bytes_ = 0;
  1390. return true;
  1391. } else {
  1392. return false;
  1393. }
  1394. }
  1395. void Compaction::ReleaseInputs() {
  1396. if (input_version_ != nullptr) {
  1397. input_version_->Unref();
  1398. input_version_ = nullptr;
  1399. }
  1400. }
  1401. } // namespace leveldb