小组成员:谢瑞阳、徐翔宇
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.

1576 lines
51 KiB

пре 3 недеља
пре 3 недеља
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 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. // kTypeValue 对应被插入的数据
  241. if(parsed_key.type == kTypeValue){
  242. time_t now = time(nullptr);
  243. uint64_t ttl=*(uint64_t*)(v.data()+v.size()-sizeof(uint64_t)); // 将 TTL 从 new_data 的末尾取出
  244. if(ttl < static_cast<uint64_t>(now))return; // 如果 TTL 超过当前时间,说明数据已经过期,直接返回
  245. }
  246. s->state = (parsed_key.type == kTypeValue) ? kFound : kDeleted;
  247. if (s->state == kFound) {
  248. s->value->assign(v.data(), v.size()-sizeof(uint64_t));
  249. }
  250. }
  251. }
  252. }
  253. static bool NewestFirst(FileMetaData* a, FileMetaData* b) {
  254. return a->number > b->number;
  255. }
  256. void Version::ForEachOverlapping(Slice user_key, Slice internal_key, void* arg,
  257. bool (*func)(void*, int, FileMetaData*)) {
  258. const Comparator* ucmp = vset_->icmp_.user_comparator();
  259. // Search level-0 in order from newest to oldest.
  260. std::vector<FileMetaData*> tmp;
  261. tmp.reserve(files_[0].size());
  262. for (uint32_t i = 0; i < files_[0].size(); i++) {
  263. FileMetaData* f = files_[0][i];
  264. if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
  265. ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
  266. tmp.push_back(f);
  267. }
  268. }
  269. if (!tmp.empty()) {
  270. std::sort(tmp.begin(), tmp.end(), NewestFirst);
  271. for (uint32_t i = 0; i < tmp.size(); i++) {
  272. if (!(*func)(arg, 0, tmp[i])) {
  273. return;
  274. }
  275. }
  276. }
  277. // Search other levels.
  278. for (int level = 1; level < config::kNumLevels; level++) {
  279. size_t num_files = files_[level].size();
  280. if (num_files == 0) continue;
  281. // Binary search to find earliest index whose largest key >= internal_key.
  282. uint32_t index = FindFile(vset_->icmp_, files_[level], internal_key);
  283. if (index < num_files) {
  284. FileMetaData* f = files_[level][index];
  285. if (ucmp->Compare(user_key, f->smallest.user_key()) < 0) {
  286. // All of "f" is past any data for user_key
  287. } else {
  288. if (!(*func)(arg, level, f)) {
  289. return;
  290. }
  291. }
  292. }
  293. }
  294. }
  295. Status Version::Get(const ReadOptions& options, const LookupKey& k,
  296. std::string* value, GetStats* stats) {
  297. stats->seek_file = nullptr;
  298. stats->seek_file_level = -1;
  299. struct State {
  300. Saver saver;
  301. GetStats* stats;
  302. const ReadOptions* options;
  303. Slice ikey;
  304. FileMetaData* last_file_read;
  305. int last_file_read_level;
  306. VersionSet* vset;
  307. Status s;
  308. bool found;
  309. static bool Match(void* arg, int level, FileMetaData* f) {
  310. State* state = reinterpret_cast<State*>(arg);
  311. if (state->stats->seek_file == nullptr &&
  312. state->last_file_read != nullptr) {
  313. // We have had more than one seek for this read. Charge the 1st file.
  314. state->stats->seek_file = state->last_file_read;
  315. state->stats->seek_file_level = state->last_file_read_level;
  316. }
  317. state->last_file_read = f;
  318. state->last_file_read_level = level;
  319. state->s = state->vset->table_cache_->Get(*state->options, f->number,
  320. f->file_size, state->ikey,
  321. &state->saver, SaveValue);
  322. if (!state->s.ok()) {
  323. state->found = true;
  324. return false;
  325. }
  326. switch (state->saver.state) {
  327. case kNotFound:
  328. return true; // Keep searching in other files
  329. case kFound:
  330. state->found = true;
  331. return false;
  332. case kDeleted:
  333. return false;
  334. case kCorrupt:
  335. state->s =
  336. Status::Corruption("corrupted key for ", state->saver.user_key);
  337. state->found = true;
  338. return false;
  339. }
  340. // Not reached. Added to avoid false compilation warnings of
  341. // "control reaches end of non-void function".
  342. return false;
  343. }
  344. };
  345. State state;
  346. state.found = false;
  347. state.stats = stats;
  348. state.last_file_read = nullptr;
  349. state.last_file_read_level = -1;
  350. state.options = &options;
  351. state.ikey = k.internal_key();
  352. state.vset = vset_;
  353. state.saver.state = kNotFound;
  354. state.saver.ucmp = vset_->icmp_.user_comparator();
  355. state.saver.user_key = k.user_key();
  356. state.saver.value = value;
  357. ForEachOverlapping(state.saver.user_key, state.ikey, &state, &State::Match);
  358. return state.found ? state.s : Status::NotFound(Slice());
  359. }
  360. bool Version::UpdateStats(const GetStats& stats) {
  361. FileMetaData* f = stats.seek_file;
  362. if (f != nullptr) {
  363. f->allowed_seeks--;
  364. if (f->allowed_seeks <= 0 && file_to_compact_ == nullptr) {
  365. file_to_compact_ = f;
  366. file_to_compact_level_ = stats.seek_file_level;
  367. return true;
  368. }
  369. }
  370. return false;
  371. }
  372. bool Version::RecordReadSample(Slice internal_key) {
  373. ParsedInternalKey ikey;
  374. if (!ParseInternalKey(internal_key, &ikey)) {
  375. return false;
  376. }
  377. struct State {
  378. GetStats stats; // Holds first matching file
  379. int matches;
  380. static bool Match(void* arg, int level, FileMetaData* f) {
  381. State* state = reinterpret_cast<State*>(arg);
  382. state->matches++;
  383. if (state->matches == 1) {
  384. // Remember first match.
  385. state->stats.seek_file = f;
  386. state->stats.seek_file_level = level;
  387. }
  388. // We can stop iterating once we have a second match.
  389. return state->matches < 2;
  390. }
  391. };
  392. State state;
  393. state.matches = 0;
  394. ForEachOverlapping(ikey.user_key, internal_key, &state, &State::Match);
  395. // Must have at least two matches since we want to merge across
  396. // files. But what if we have a single file that contains many
  397. // overwrites and deletions? Should we have another mechanism for
  398. // finding such files?
  399. if (state.matches >= 2) {
  400. // 1MB cost is about 1 seek (see comment in Builder::Apply).
  401. return UpdateStats(state.stats);
  402. }
  403. return false;
  404. }
  405. void Version::Ref() { ++refs_; }
  406. void Version::Unref() {
  407. assert(this != &vset_->dummy_versions_);
  408. assert(refs_ >= 1);
  409. --refs_;
  410. if (refs_ == 0) {
  411. delete this;
  412. }
  413. }
  414. bool Version::OverlapInLevel(int level, const Slice* smallest_user_key,
  415. const Slice* largest_user_key) {
  416. return SomeFileOverlapsRange(vset_->icmp_, (level > 0), files_[level],
  417. smallest_user_key, largest_user_key);
  418. }
  419. int Version::PickLevelForMemTableOutput(const Slice& smallest_user_key,
  420. const Slice& largest_user_key) {
  421. int level = 0;
  422. if (!OverlapInLevel(0, &smallest_user_key, &largest_user_key)) {
  423. // Push to next level if there is no overlap in next level,
  424. // and the #bytes overlapping in the level after that are limited.
  425. InternalKey start(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek);
  426. InternalKey limit(largest_user_key, 0, static_cast<ValueType>(0));
  427. std::vector<FileMetaData*> overlaps;
  428. while (level < config::kMaxMemCompactLevel) {
  429. if (OverlapInLevel(level + 1, &smallest_user_key, &largest_user_key)) {
  430. break;
  431. }
  432. if (level + 2 < config::kNumLevels) {
  433. // Check that file does not overlap too many grandparent bytes.
  434. GetOverlappingInputs(level + 2, &start, &limit, &overlaps);
  435. const int64_t sum = TotalFileSize(overlaps);
  436. if (sum > MaxGrandParentOverlapBytes(vset_->options_)) {
  437. break;
  438. }
  439. }
  440. level++;
  441. }
  442. }
  443. return level;
  444. }
  445. // Store in "*inputs" all files in "level" that overlap [begin,end]
  446. void Version::GetOverlappingInputs(int level, const InternalKey* begin,
  447. const InternalKey* end,
  448. std::vector<FileMetaData*>* inputs) {
  449. assert(level >= 0);
  450. assert(level < config::kNumLevels);
  451. inputs->clear();
  452. Slice user_begin, user_end;
  453. if (begin != nullptr) {
  454. user_begin = begin->user_key();
  455. }
  456. if (end != nullptr) {
  457. user_end = end->user_key();
  458. }
  459. const Comparator* user_cmp = vset_->icmp_.user_comparator();
  460. for (size_t i = 0; i < files_[level].size();) {
  461. FileMetaData* f = files_[level][i++];
  462. const Slice file_start = f->smallest.user_key();
  463. const Slice file_limit = f->largest.user_key();
  464. if (begin != nullptr && user_cmp->Compare(file_limit, user_begin) < 0) {
  465. // "f" is completely before specified range; skip it
  466. } else if (end != nullptr && user_cmp->Compare(file_start, user_end) > 0) {
  467. // "f" is completely after specified range; skip it
  468. } else {
  469. inputs->push_back(f);
  470. if (level == 0) {
  471. // Level-0 files may overlap each other. So check if the newly
  472. // added file has expanded the range. If so, restart search.
  473. if (begin != nullptr && user_cmp->Compare(file_start, user_begin) < 0) {
  474. user_begin = file_start;
  475. inputs->clear();
  476. i = 0;
  477. } else if (end != nullptr &&
  478. user_cmp->Compare(file_limit, user_end) > 0) {
  479. user_end = file_limit;
  480. inputs->clear();
  481. i = 0;
  482. }
  483. }
  484. }
  485. }
  486. }
  487. std::string Version::DebugString() const {
  488. std::string r;
  489. for (int level = 0; level < config::kNumLevels; level++) {
  490. // E.g.,
  491. // --- level 1 ---
  492. // 17:123['a' .. 'd']
  493. // 20:43['e' .. 'g']
  494. r.append("--- level ");
  495. AppendNumberTo(&r, level);
  496. r.append(" ---\n");
  497. const std::vector<FileMetaData*>& files = files_[level];
  498. for (size_t i = 0; i < files.size(); i++) {
  499. r.push_back(' ');
  500. AppendNumberTo(&r, files[i]->number);
  501. r.push_back(':');
  502. AppendNumberTo(&r, files[i]->file_size);
  503. r.append("[");
  504. r.append(files[i]->smallest.DebugString());
  505. r.append(" .. ");
  506. r.append(files[i]->largest.DebugString());
  507. r.append("]\n");
  508. }
  509. }
  510. return r;
  511. }
  512. // A helper class so we can efficiently apply a whole sequence
  513. // of edits to a particular state without creating intermediate
  514. // Versions that contain full copies of the intermediate state.
  515. class VersionSet::Builder {
  516. private:
  517. // Helper to sort by v->files_[file_number].smallest
  518. struct BySmallestKey {
  519. const InternalKeyComparator* internal_comparator;
  520. bool operator()(FileMetaData* f1, FileMetaData* f2) const {
  521. int r = internal_comparator->Compare(f1->smallest, f2->smallest);
  522. if (r != 0) {
  523. return (r < 0);
  524. } else {
  525. // Break ties by file number
  526. return (f1->number < f2->number);
  527. }
  528. }
  529. };
  530. typedef std::set<FileMetaData*, BySmallestKey> FileSet;
  531. struct LevelState {
  532. std::set<uint64_t> deleted_files;
  533. FileSet* added_files;
  534. };
  535. VersionSet* vset_;
  536. Version* base_;
  537. LevelState levels_[config::kNumLevels];
  538. public:
  539. // Initialize a builder with the files from *base and other info from *vset
  540. Builder(VersionSet* vset, Version* base) : vset_(vset), base_(base) {
  541. base_->Ref();
  542. BySmallestKey cmp;
  543. cmp.internal_comparator = &vset_->icmp_;
  544. for (int level = 0; level < config::kNumLevels; level++) {
  545. levels_[level].added_files = new FileSet(cmp);
  546. }
  547. }
  548. ~Builder() {
  549. for (int level = 0; level < config::kNumLevels; level++) {
  550. const FileSet* added = levels_[level].added_files;
  551. std::vector<FileMetaData*> to_unref;
  552. to_unref.reserve(added->size());
  553. for (FileSet::const_iterator it = added->begin(); it != added->end();
  554. ++it) {
  555. to_unref.push_back(*it);
  556. }
  557. delete added;
  558. for (uint32_t i = 0; i < to_unref.size(); i++) {
  559. FileMetaData* f = to_unref[i];
  560. f->refs--;
  561. if (f->refs <= 0) {
  562. delete f;
  563. }
  564. }
  565. }
  566. base_->Unref();
  567. }
  568. // Apply all of the edits in *edit to the current state.
  569. void Apply(const VersionEdit* edit) {
  570. // Update compaction pointers
  571. for (size_t i = 0; i < edit->compact_pointers_.size(); i++) {
  572. const int level = edit->compact_pointers_[i].first;
  573. vset_->compact_pointer_[level] =
  574. edit->compact_pointers_[i].second.Encode().ToString();
  575. }
  576. // Delete files
  577. for (const auto& deleted_file_set_kvp : edit->deleted_files_) {
  578. const int level = deleted_file_set_kvp.first;
  579. const uint64_t number = deleted_file_set_kvp.second;
  580. levels_[level].deleted_files.insert(number);
  581. }
  582. // Add new files
  583. for (size_t i = 0; i < edit->new_files_.size(); i++) {
  584. const int level = edit->new_files_[i].first;
  585. FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
  586. f->refs = 1;
  587. // We arrange to automatically compact this file after
  588. // a certain number of seeks. Let's assume:
  589. // (1) One seek costs 10ms
  590. // (2) Writing or reading 1MB costs 10ms (100MB/s)
  591. // (3) A compaction of 1MB does 25MB of IO:
  592. // 1MB read from this level
  593. // 10-12MB read from next level (boundaries may be misaligned)
  594. // 10-12MB written to next level
  595. // This implies that 25 seeks cost the same as the compaction
  596. // of 1MB of data. I.e., one seek costs approximately the
  597. // same as the compaction of 40KB of data. We are a little
  598. // conservative and allow approximately one seek for every 16KB
  599. // of data before triggering a compaction.
  600. f->allowed_seeks = static_cast<int>((f->file_size / 16384U));
  601. if (f->allowed_seeks < 100) f->allowed_seeks = 100;
  602. levels_[level].deleted_files.erase(f->number);
  603. levels_[level].added_files->insert(f);
  604. }
  605. }
  606. // Save the current state in *v.
  607. void SaveTo(Version* v) {
  608. BySmallestKey cmp;
  609. cmp.internal_comparator = &vset_->icmp_;
  610. for (int level = 0; level < config::kNumLevels; level++) {
  611. // Merge the set of added files with the set of pre-existing files.
  612. // Drop any deleted files. Store the result in *v.
  613. const std::vector<FileMetaData*>& base_files = base_->files_[level];
  614. std::vector<FileMetaData*>::const_iterator base_iter = base_files.begin();
  615. std::vector<FileMetaData*>::const_iterator base_end = base_files.end();
  616. const FileSet* added_files = levels_[level].added_files;
  617. v->files_[level].reserve(base_files.size() + added_files->size());
  618. for (const auto& added_file : *added_files) {
  619. // Add all smaller files listed in base_
  620. for (std::vector<FileMetaData*>::const_iterator bpos =
  621. std::upper_bound(base_iter, base_end, added_file, cmp);
  622. base_iter != bpos; ++base_iter) {
  623. MaybeAddFile(v, level, *base_iter);
  624. }
  625. MaybeAddFile(v, level, added_file);
  626. }
  627. // Add remaining base files
  628. for (; base_iter != base_end; ++base_iter) {
  629. MaybeAddFile(v, level, *base_iter);
  630. }
  631. #ifndef NDEBUG
  632. // Make sure there is no overlap in levels > 0
  633. if (level > 0) {
  634. for (uint32_t i = 1; i < v->files_[level].size(); i++) {
  635. const InternalKey& prev_end = v->files_[level][i - 1]->largest;
  636. const InternalKey& this_begin = v->files_[level][i]->smallest;
  637. if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) {
  638. std::fprintf(stderr, "overlapping ranges in same level %s vs. %s\n",
  639. prev_end.DebugString().c_str(),
  640. this_begin.DebugString().c_str());
  641. std::abort();
  642. }
  643. }
  644. }
  645. #endif
  646. }
  647. }
  648. void MaybeAddFile(Version* v, int level, FileMetaData* f) {
  649. if (levels_[level].deleted_files.count(f->number) > 0) {
  650. // File is deleted: do nothing
  651. } else {
  652. std::vector<FileMetaData*>* files = &v->files_[level];
  653. if (level > 0 && !files->empty()) {
  654. // Must not overlap
  655. assert(vset_->icmp_.Compare((*files)[files->size() - 1]->largest,
  656. f->smallest) < 0);
  657. }
  658. f->refs++;
  659. files->push_back(f);
  660. }
  661. }
  662. };
  663. VersionSet::VersionSet(const std::string& dbname, const Options* options,
  664. TableCache* table_cache,
  665. const InternalKeyComparator* cmp)
  666. : env_(options->env),
  667. dbname_(dbname),
  668. options_(options),
  669. table_cache_(table_cache),
  670. icmp_(*cmp),
  671. next_file_number_(2),
  672. manifest_file_number_(0), // Filled by Recover()
  673. last_sequence_(0),
  674. log_number_(0),
  675. prev_log_number_(0),
  676. descriptor_file_(nullptr),
  677. descriptor_log_(nullptr),
  678. dummy_versions_(this),
  679. current_(nullptr) {
  680. AppendVersion(new Version(this));
  681. }
  682. VersionSet::~VersionSet() {
  683. current_->Unref();
  684. assert(dummy_versions_.next_ == &dummy_versions_); // List must be empty
  685. delete descriptor_log_;
  686. delete descriptor_file_;
  687. }
  688. void VersionSet::AppendVersion(Version* v) {
  689. // Make "v" current
  690. assert(v->refs_ == 0);
  691. assert(v != current_);
  692. if (current_ != nullptr) {
  693. current_->Unref();
  694. }
  695. current_ = v;
  696. v->Ref();
  697. // Append to linked list
  698. v->prev_ = dummy_versions_.prev_;
  699. v->next_ = &dummy_versions_;
  700. v->prev_->next_ = v;
  701. v->next_->prev_ = v;
  702. }
  703. Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) {
  704. if (edit->has_log_number_) {
  705. assert(edit->log_number_ >= log_number_);
  706. assert(edit->log_number_ < next_file_number_);
  707. } else {
  708. edit->SetLogNumber(log_number_);
  709. }
  710. if (!edit->has_prev_log_number_) {
  711. edit->SetPrevLogNumber(prev_log_number_);
  712. }
  713. edit->SetNextFile(next_file_number_);
  714. edit->SetLastSequence(last_sequence_);
  715. Version* v = new Version(this);
  716. {
  717. Builder builder(this, current_);
  718. builder.Apply(edit);
  719. builder.SaveTo(v);
  720. }
  721. Finalize(v);
  722. // Initialize new descriptor log file if necessary by creating
  723. // a temporary file that contains a snapshot of the current version.
  724. std::string new_manifest_file;
  725. Status s;
  726. if (descriptor_log_ == nullptr) {
  727. // No reason to unlock *mu here since we only hit this path in the
  728. // first call to LogAndApply (when opening the database).
  729. assert(descriptor_file_ == nullptr);
  730. new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
  731. s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
  732. if (s.ok()) {
  733. descriptor_log_ = new log::Writer(descriptor_file_);
  734. s = WriteSnapshot(descriptor_log_);
  735. }
  736. }
  737. // Unlock during expensive MANIFEST log write
  738. {
  739. mu->Unlock();
  740. // Write new record to MANIFEST log
  741. if (s.ok()) {
  742. std::string record;
  743. edit->EncodeTo(&record);
  744. s = descriptor_log_->AddRecord(record);
  745. if (s.ok()) {
  746. s = descriptor_file_->Sync();
  747. }
  748. if (!s.ok()) {
  749. Log(options_->info_log, "MANIFEST write: %s\n", s.ToString().c_str());
  750. }
  751. }
  752. // If we just created a new descriptor file, install it by writing a
  753. // new CURRENT file that points to it.
  754. if (s.ok() && !new_manifest_file.empty()) {
  755. s = SetCurrentFile(env_, dbname_, manifest_file_number_);
  756. }
  757. mu->Lock();
  758. }
  759. // Install the new version
  760. if (s.ok()) {
  761. AppendVersion(v);
  762. log_number_ = edit->log_number_;
  763. prev_log_number_ = edit->prev_log_number_;
  764. } else {
  765. delete v;
  766. if (!new_manifest_file.empty()) {
  767. delete descriptor_log_;
  768. delete descriptor_file_;
  769. descriptor_log_ = nullptr;
  770. descriptor_file_ = nullptr;
  771. env_->RemoveFile(new_manifest_file);
  772. }
  773. }
  774. return s;
  775. }
  776. Status VersionSet::Recover(bool* save_manifest) {
  777. struct LogReporter : public log::Reader::Reporter {
  778. Status* status;
  779. void Corruption(size_t bytes, const Status& s) override {
  780. if (this->status->ok()) *this->status = s;
  781. }
  782. };
  783. // Read "CURRENT" file, which contains a pointer to the current manifest file
  784. std::string current;
  785. Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  786. if (!s.ok()) {
  787. return s;
  788. }
  789. if (current.empty() || current[current.size() - 1] != '\n') {
  790. return Status::Corruption("CURRENT file does not end with newline");
  791. }
  792. current.resize(current.size() - 1);
  793. std::string dscname = dbname_ + "/" + current;
  794. SequentialFile* file;
  795. s = env_->NewSequentialFile(dscname, &file);
  796. if (!s.ok()) {
  797. if (s.IsNotFound()) {
  798. return Status::Corruption("CURRENT points to a non-existent file",
  799. s.ToString());
  800. }
  801. return s;
  802. }
  803. bool have_log_number = false;
  804. bool have_prev_log_number = false;
  805. bool have_next_file = false;
  806. bool have_last_sequence = false;
  807. uint64_t next_file = 0;
  808. uint64_t last_sequence = 0;
  809. uint64_t log_number = 0;
  810. uint64_t prev_log_number = 0;
  811. Builder builder(this, current_);
  812. int read_records = 0;
  813. {
  814. LogReporter reporter;
  815. reporter.status = &s;
  816. log::Reader reader(file, &reporter, true /*checksum*/,
  817. 0 /*initial_offset*/);
  818. Slice record;
  819. std::string scratch;
  820. while (reader.ReadRecord(&record, &scratch) && s.ok()) {
  821. ++read_records;
  822. VersionEdit edit;
  823. s = edit.DecodeFrom(record);
  824. if (s.ok()) {
  825. if (edit.has_comparator_ &&
  826. edit.comparator_ != icmp_.user_comparator()->Name()) {
  827. s = Status::InvalidArgument(
  828. edit.comparator_ + " does not match existing comparator ",
  829. icmp_.user_comparator()->Name());
  830. }
  831. }
  832. if (s.ok()) {
  833. builder.Apply(&edit);
  834. }
  835. if (edit.has_log_number_) {
  836. log_number = edit.log_number_;
  837. have_log_number = true;
  838. }
  839. if (edit.has_prev_log_number_) {
  840. prev_log_number = edit.prev_log_number_;
  841. have_prev_log_number = true;
  842. }
  843. if (edit.has_next_file_number_) {
  844. next_file = edit.next_file_number_;
  845. have_next_file = true;
  846. }
  847. if (edit.has_last_sequence_) {
  848. last_sequence = edit.last_sequence_;
  849. have_last_sequence = true;
  850. }
  851. }
  852. }
  853. delete file;
  854. file = nullptr;
  855. if (s.ok()) {
  856. if (!have_next_file) {
  857. s = Status::Corruption("no meta-nextfile entry in descriptor");
  858. } else if (!have_log_number) {
  859. s = Status::Corruption("no meta-lognumber entry in descriptor");
  860. } else if (!have_last_sequence) {
  861. s = Status::Corruption("no last-sequence-number entry in descriptor");
  862. }
  863. if (!have_prev_log_number) {
  864. prev_log_number = 0;
  865. }
  866. MarkFileNumberUsed(prev_log_number);
  867. MarkFileNumberUsed(log_number);
  868. }
  869. if (s.ok()) {
  870. Version* v = new Version(this);
  871. builder.SaveTo(v);
  872. // Install recovered version
  873. Finalize(v);
  874. AppendVersion(v);
  875. manifest_file_number_ = next_file;
  876. next_file_number_ = next_file + 1;
  877. last_sequence_ = last_sequence;
  878. log_number_ = log_number;
  879. prev_log_number_ = prev_log_number;
  880. // See if we can reuse the existing MANIFEST file.
  881. if (ReuseManifest(dscname, current)) {
  882. // No need to save new manifest
  883. } else {
  884. *save_manifest = true;
  885. }
  886. } else {
  887. std::string error = s.ToString();
  888. Log(options_->info_log, "Error recovering version set with %d records: %s",
  889. read_records, error.c_str());
  890. }
  891. return s;
  892. }
  893. bool VersionSet::ReuseManifest(const std::string& dscname,
  894. const std::string& dscbase) {
  895. if (!options_->reuse_logs) {
  896. return false;
  897. }
  898. FileType manifest_type;
  899. uint64_t manifest_number;
  900. uint64_t manifest_size;
  901. if (!ParseFileName(dscbase, &manifest_number, &manifest_type) ||
  902. manifest_type != kDescriptorFile ||
  903. !env_->GetFileSize(dscname, &manifest_size).ok() ||
  904. // Make new compacted MANIFEST if old one is too big
  905. manifest_size >= TargetFileSize(options_)) {
  906. return false;
  907. }
  908. assert(descriptor_file_ == nullptr);
  909. assert(descriptor_log_ == nullptr);
  910. Status r = env_->NewAppendableFile(dscname, &descriptor_file_);
  911. if (!r.ok()) {
  912. Log(options_->info_log, "Reuse MANIFEST: %s\n", r.ToString().c_str());
  913. assert(descriptor_file_ == nullptr);
  914. return false;
  915. }
  916. Log(options_->info_log, "Reusing MANIFEST %s\n", dscname.c_str());
  917. descriptor_log_ = new log::Writer(descriptor_file_, manifest_size);
  918. manifest_file_number_ = manifest_number;
  919. return true;
  920. }
  921. void VersionSet::MarkFileNumberUsed(uint64_t number) {
  922. if (next_file_number_ <= number) {
  923. next_file_number_ = number + 1;
  924. }
  925. }
  926. void VersionSet::Finalize(Version* v) {
  927. // Precomputed best level for next compaction
  928. int best_level = -1;
  929. double best_score = -1;
  930. for (int level = 0; level < config::kNumLevels - 1; level++) {
  931. double score;
  932. if (level == 0) {
  933. // We treat level-0 specially by bounding the number of files
  934. // instead of number of bytes for two reasons:
  935. //
  936. // (1) With larger write-buffer sizes, it is nice not to do too
  937. // many level-0 compactions.
  938. //
  939. // (2) The files in level-0 are merged on every read and
  940. // therefore we wish to avoid too many files when the individual
  941. // file size is small (perhaps because of a small write-buffer
  942. // setting, or very high compression ratios, or lots of
  943. // overwrites/deletions).
  944. score = v->files_[level].size() /
  945. static_cast<double>(config::kL0_CompactionTrigger);
  946. } else {
  947. // Compute the ratio of current size to size limit.
  948. const uint64_t level_bytes = TotalFileSize(v->files_[level]);
  949. score =
  950. static_cast<double>(level_bytes) / MaxBytesForLevel(options_, level);
  951. }
  952. if (score > best_score) {
  953. best_level = level;
  954. best_score = score;
  955. }
  956. }
  957. v->compaction_level_ = best_level;
  958. v->compaction_score_ = best_score;
  959. }
  960. Status VersionSet::WriteSnapshot(log::Writer* log) {
  961. // TODO: Break up into multiple records to reduce memory usage on recovery?
  962. // Save metadata
  963. VersionEdit edit;
  964. edit.SetComparatorName(icmp_.user_comparator()->Name());
  965. // Save compaction pointers
  966. for (int level = 0; level < config::kNumLevels; level++) {
  967. if (!compact_pointer_[level].empty()) {
  968. InternalKey key;
  969. key.DecodeFrom(compact_pointer_[level]);
  970. edit.SetCompactPointer(level, key);
  971. }
  972. }
  973. // Save files
  974. for (int level = 0; level < config::kNumLevels; level++) {
  975. const std::vector<FileMetaData*>& files = current_->files_[level];
  976. for (size_t i = 0; i < files.size(); i++) {
  977. const FileMetaData* f = files[i];
  978. edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
  979. }
  980. }
  981. std::string record;
  982. edit.EncodeTo(&record);
  983. return log->AddRecord(record);
  984. }
  985. int VersionSet::NumLevelFiles(int level) const {
  986. assert(level >= 0);
  987. assert(level < config::kNumLevels);
  988. return current_->files_[level].size();
  989. }
  990. const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  991. // Update code if kNumLevels changes
  992. static_assert(config::kNumLevels == 7, "");
  993. std::snprintf(
  994. scratch->buffer, sizeof(scratch->buffer), "files[ %d %d %d %d %d %d %d ]",
  995. int(current_->files_[0].size()), int(current_->files_[1].size()),
  996. int(current_->files_[2].size()), int(current_->files_[3].size()),
  997. int(current_->files_[4].size()), int(current_->files_[5].size()),
  998. int(current_->files_[6].size()));
  999. return scratch->buffer;
  1000. }
  1001. uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  1002. uint64_t result = 0;
  1003. for (int level = 0; level < config::kNumLevels; level++) {
  1004. const std::vector<FileMetaData*>& files = v->files_[level];
  1005. for (size_t i = 0; i < files.size(); i++) {
  1006. if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
  1007. // Entire file is before "ikey", so just add the file size
  1008. result += files[i]->file_size;
  1009. } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
  1010. // Entire file is after "ikey", so ignore
  1011. if (level > 0) {
  1012. // Files other than level 0 are sorted by meta->smallest, so
  1013. // no further files in this level will contain data for
  1014. // "ikey".
  1015. break;
  1016. }
  1017. } else {
  1018. // "ikey" falls in the range for this table. Add the
  1019. // approximate offset of "ikey" within the table.
  1020. Table* tableptr;
  1021. Iterator* iter = table_cache_->NewIterator(
  1022. ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
  1023. if (tableptr != nullptr) {
  1024. result += tableptr->ApproximateOffsetOf(ikey.Encode());
  1025. }
  1026. delete iter;
  1027. }
  1028. }
  1029. }
  1030. return result;
  1031. }
  1032. void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
  1033. for (Version* v = dummy_versions_.next_; v != &dummy_versions_;
  1034. v = v->next_) {
  1035. for (int level = 0; level < config::kNumLevels; level++) {
  1036. const std::vector<FileMetaData*>& files = v->files_[level];
  1037. for (size_t i = 0; i < files.size(); i++) {
  1038. live->insert(files[i]->number);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. int64_t VersionSet::NumLevelBytes(int level) const {
  1044. assert(level >= 0);
  1045. assert(level < config::kNumLevels);
  1046. return TotalFileSize(current_->files_[level]);
  1047. }
  1048. int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  1049. int64_t result = 0;
  1050. std::vector<FileMetaData*> overlaps;
  1051. for (int level = 1; level < config::kNumLevels - 1; level++) {
  1052. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1053. const FileMetaData* f = current_->files_[level][i];
  1054. current_->GetOverlappingInputs(level + 1, &f->smallest, &f->largest,
  1055. &overlaps);
  1056. const int64_t sum = TotalFileSize(overlaps);
  1057. if (sum > result) {
  1058. result = sum;
  1059. }
  1060. }
  1061. }
  1062. return result;
  1063. }
  1064. // Stores the minimal range that covers all entries in inputs in
  1065. // *smallest, *largest.
  1066. // REQUIRES: inputs is not empty
  1067. void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
  1068. InternalKey* smallest, InternalKey* largest) {
  1069. assert(!inputs.empty());
  1070. smallest->Clear();
  1071. largest->Clear();
  1072. for (size_t i = 0; i < inputs.size(); i++) {
  1073. FileMetaData* f = inputs[i];
  1074. if (i == 0) {
  1075. *smallest = f->smallest;
  1076. *largest = f->largest;
  1077. } else {
  1078. if (icmp_.Compare(f->smallest, *smallest) < 0) {
  1079. *smallest = f->smallest;
  1080. }
  1081. if (icmp_.Compare(f->largest, *largest) > 0) {
  1082. *largest = f->largest;
  1083. }
  1084. }
  1085. }
  1086. }
  1087. // Stores the minimal range that covers all entries in inputs1 and inputs2
  1088. // in *smallest, *largest.
  1089. // REQUIRES: inputs is not empty
  1090. void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
  1091. const std::vector<FileMetaData*>& inputs2,
  1092. InternalKey* smallest, InternalKey* largest) {
  1093. std::vector<FileMetaData*> all = inputs1;
  1094. all.insert(all.end(), inputs2.begin(), inputs2.end());
  1095. GetRange(all, smallest, largest);
  1096. }
  1097. Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  1098. ReadOptions options;
  1099. options.verify_checksums = options_->paranoid_checks;
  1100. options.fill_cache = false;
  1101. // Level-0 files have to be merged together. For other levels,
  1102. // we will make a concatenating iterator per level.
  1103. // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  1104. const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  1105. Iterator** list = new Iterator*[space];
  1106. int num = 0;
  1107. for (int which = 0; which < 2; which++) {
  1108. if (!c->inputs_[which].empty()) {
  1109. if (c->level() + which == 0) {
  1110. const std::vector<FileMetaData*>& files = c->inputs_[which];
  1111. for (size_t i = 0; i < files.size(); i++) {
  1112. list[num++] = table_cache_->NewIterator(options, files[i]->number,
  1113. files[i]->file_size);
  1114. }
  1115. } else {
  1116. // Create concatenating iterator for the files from this level
  1117. list[num++] = NewTwoLevelIterator(
  1118. new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
  1119. &GetFileIterator, table_cache_, options);
  1120. }
  1121. }
  1122. }
  1123. assert(num <= space);
  1124. Iterator* result = NewMergingIterator(&icmp_, list, num);
  1125. delete[] list;
  1126. return result;
  1127. }
  1128. Compaction* VersionSet::PickCompaction() {
  1129. Compaction* c;
  1130. int level;
  1131. // We prefer compactions triggered by too much data in a level over
  1132. // the compactions triggered by seeks.
  1133. const bool size_compaction = (current_->compaction_score_ >= 1);
  1134. const bool seek_compaction = (current_->file_to_compact_ != nullptr);
  1135. if (size_compaction) {
  1136. level = current_->compaction_level_;
  1137. assert(level >= 0);
  1138. assert(level + 1 < config::kNumLevels);
  1139. c = new Compaction(options_, level);
  1140. // Pick the first file that comes after compact_pointer_[level]
  1141. for (size_t i = 0; i < current_->files_[level].size(); i++) {
  1142. FileMetaData* f = current_->files_[level][i];
  1143. if (compact_pointer_[level].empty() ||
  1144. icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
  1145. c->inputs_[0].push_back(f);
  1146. break;
  1147. }
  1148. }
  1149. if (c->inputs_[0].empty()) {
  1150. // Wrap-around to the beginning of the key space
  1151. c->inputs_[0].push_back(current_->files_[level][0]);
  1152. }
  1153. } else if (seek_compaction) {
  1154. level = current_->file_to_compact_level_;
  1155. c = new Compaction(options_, level);
  1156. c->inputs_[0].push_back(current_->file_to_compact_);
  1157. } else {
  1158. return nullptr;
  1159. }
  1160. c->input_version_ = current_;
  1161. c->input_version_->Ref();
  1162. // Files in level 0 may overlap each other, so pick up all overlapping ones
  1163. if (level == 0) {
  1164. InternalKey smallest, largest;
  1165. GetRange(c->inputs_[0], &smallest, &largest);
  1166. // Note that the next call will discard the file we placed in
  1167. // c->inputs_[0] earlier and replace it with an overlapping set
  1168. // which will include the picked file.
  1169. current_->GetOverlappingInputs(0, &smallest, &largest, &c->inputs_[0]);
  1170. assert(!c->inputs_[0].empty());
  1171. }
  1172. SetupOtherInputs(c);
  1173. return c;
  1174. }
  1175. // Finds the largest key in a vector of files. Returns true if files is not
  1176. // empty.
  1177. bool FindLargestKey(const InternalKeyComparator& icmp,
  1178. const std::vector<FileMetaData*>& files,
  1179. InternalKey* largest_key) {
  1180. if (files.empty()) {
  1181. return false;
  1182. }
  1183. *largest_key = files[0]->largest;
  1184. for (size_t i = 1; i < files.size(); ++i) {
  1185. FileMetaData* f = files[i];
  1186. if (icmp.Compare(f->largest, *largest_key) > 0) {
  1187. *largest_key = f->largest;
  1188. }
  1189. }
  1190. return true;
  1191. }
  1192. // Finds minimum file b2=(l2, u2) in level file for which l2 > u1 and
  1193. // user_key(l2) = user_key(u1)
  1194. FileMetaData* FindSmallestBoundaryFile(
  1195. const InternalKeyComparator& icmp,
  1196. const std::vector<FileMetaData*>& level_files,
  1197. const InternalKey& largest_key) {
  1198. const Comparator* user_cmp = icmp.user_comparator();
  1199. FileMetaData* smallest_boundary_file = nullptr;
  1200. for (size_t i = 0; i < level_files.size(); ++i) {
  1201. FileMetaData* f = level_files[i];
  1202. if (icmp.Compare(f->smallest, largest_key) > 0 &&
  1203. user_cmp->Compare(f->smallest.user_key(), largest_key.user_key()) ==
  1204. 0) {
  1205. if (smallest_boundary_file == nullptr ||
  1206. icmp.Compare(f->smallest, smallest_boundary_file->smallest) < 0) {
  1207. smallest_boundary_file = f;
  1208. }
  1209. }
  1210. }
  1211. return smallest_boundary_file;
  1212. }
  1213. // Extracts the largest file b1 from |compaction_files| and then searches for a
  1214. // b2 in |level_files| for which user_key(u1) = user_key(l2). If it finds such a
  1215. // file b2 (known as a boundary file) it adds it to |compaction_files| and then
  1216. // searches again using this new upper bound.
  1217. //
  1218. // If there are two blocks, b1=(l1, u1) and b2=(l2, u2) and
  1219. // user_key(u1) = user_key(l2), and if we compact b1 but not b2 then a
  1220. // subsequent get operation will yield an incorrect result because it will
  1221. // return the record from b2 in level i rather than from b1 because it searches
  1222. // level by level for records matching the supplied user key.
  1223. //
  1224. // parameters:
  1225. // in level_files: List of files to search for boundary files.
  1226. // in/out compaction_files: List of files to extend by adding boundary files.
  1227. void AddBoundaryInputs(const InternalKeyComparator& icmp,
  1228. const std::vector<FileMetaData*>& level_files,
  1229. std::vector<FileMetaData*>* compaction_files) {
  1230. InternalKey largest_key;
  1231. // Quick return if compaction_files is empty.
  1232. if (!FindLargestKey(icmp, *compaction_files, &largest_key)) {
  1233. return;
  1234. }
  1235. bool continue_searching = true;
  1236. while (continue_searching) {
  1237. FileMetaData* smallest_boundary_file =
  1238. FindSmallestBoundaryFile(icmp, level_files, largest_key);
  1239. // If a boundary file was found advance largest_key, otherwise we're done.
  1240. if (smallest_boundary_file != NULL) {
  1241. compaction_files->push_back(smallest_boundary_file);
  1242. largest_key = smallest_boundary_file->largest;
  1243. } else {
  1244. continue_searching = false;
  1245. }
  1246. }
  1247. }
  1248. void VersionSet::SetupOtherInputs(Compaction* c) {
  1249. const int level = c->level();
  1250. InternalKey smallest, largest;
  1251. AddBoundaryInputs(icmp_, current_->files_[level], &c->inputs_[0]);
  1252. GetRange(c->inputs_[0], &smallest, &largest);
  1253. current_->GetOverlappingInputs(level + 1, &smallest, &largest,
  1254. &c->inputs_[1]);
  1255. AddBoundaryInputs(icmp_, current_->files_[level + 1], &c->inputs_[1]);
  1256. // Get entire range covered by compaction
  1257. InternalKey all_start, all_limit;
  1258. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1259. // See if we can grow the number of inputs in "level" without
  1260. // changing the number of "level+1" files we pick up.
  1261. if (!c->inputs_[1].empty()) {
  1262. std::vector<FileMetaData*> expanded0;
  1263. current_->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0);
  1264. AddBoundaryInputs(icmp_, current_->files_[level], &expanded0);
  1265. const int64_t inputs0_size = TotalFileSize(c->inputs_[0]);
  1266. const int64_t inputs1_size = TotalFileSize(c->inputs_[1]);
  1267. const int64_t expanded0_size = TotalFileSize(expanded0);
  1268. if (expanded0.size() > c->inputs_[0].size() &&
  1269. inputs1_size + expanded0_size <
  1270. ExpandedCompactionByteSizeLimit(options_)) {
  1271. InternalKey new_start, new_limit;
  1272. GetRange(expanded0, &new_start, &new_limit);
  1273. std::vector<FileMetaData*> expanded1;
  1274. current_->GetOverlappingInputs(level + 1, &new_start, &new_limit,
  1275. &expanded1);
  1276. AddBoundaryInputs(icmp_, current_->files_[level + 1], &expanded1);
  1277. if (expanded1.size() == c->inputs_[1].size()) {
  1278. Log(options_->info_log,
  1279. "Expanding@%d %d+%d (%ld+%ld bytes) to %d+%d (%ld+%ld bytes)\n",
  1280. level, int(c->inputs_[0].size()), int(c->inputs_[1].size()),
  1281. long(inputs0_size), long(inputs1_size), int(expanded0.size()),
  1282. int(expanded1.size()), long(expanded0_size), long(inputs1_size));
  1283. smallest = new_start;
  1284. largest = new_limit;
  1285. c->inputs_[0] = expanded0;
  1286. c->inputs_[1] = expanded1;
  1287. GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
  1288. }
  1289. }
  1290. }
  1291. // Compute the set of grandparent files that overlap this compaction
  1292. // (parent == level+1; grandparent == level+2)
  1293. if (level + 2 < config::kNumLevels) {
  1294. current_->GetOverlappingInputs(level + 2, &all_start, &all_limit,
  1295. &c->grandparents_);
  1296. }
  1297. // Update the place where we will do the next compaction for this level.
  1298. // We update this immediately instead of waiting for the VersionEdit
  1299. // to be applied so that if the compaction fails, we will try a different
  1300. // key range next time.
  1301. compact_pointer_[level] = largest.Encode().ToString();
  1302. c->edit_.SetCompactPointer(level, largest);
  1303. }
  1304. Compaction* VersionSet::CompactRange(int level, const InternalKey* begin,
  1305. const InternalKey* end) {
  1306. std::vector<FileMetaData*> inputs;
  1307. current_->GetOverlappingInputs(level, begin, end, &inputs);
  1308. if (inputs.empty()) {
  1309. return nullptr;
  1310. }
  1311. // Avoid compacting too much in one shot in case the range is large.
  1312. // But we cannot do this for level-0 since level-0 files can overlap
  1313. // and we must not pick one file and drop another older file if the
  1314. // two files overlap.
  1315. if (level > 0) {
  1316. const uint64_t limit = MaxFileSizeForLevel(options_, level);
  1317. uint64_t total = 0;
  1318. for (size_t i = 0; i < inputs.size(); i++) {
  1319. uint64_t s = inputs[i]->file_size;
  1320. total += s;
  1321. if (total >= limit) {
  1322. inputs.resize(i + 1);
  1323. break;
  1324. }
  1325. }
  1326. }
  1327. Compaction* c = new Compaction(options_, level);
  1328. c->input_version_ = current_;
  1329. c->input_version_->Ref();
  1330. c->inputs_[0] = inputs;
  1331. SetupOtherInputs(c);
  1332. return c;
  1333. }
  1334. Compaction::Compaction(const Options* options, int level)
  1335. : level_(level),
  1336. max_output_file_size_(MaxFileSizeForLevel(options, level)),
  1337. input_version_(nullptr),
  1338. grandparent_index_(0),
  1339. seen_key_(false),
  1340. overlapped_bytes_(0) {
  1341. for (int i = 0; i < config::kNumLevels; i++) {
  1342. level_ptrs_[i] = 0;
  1343. }
  1344. }
  1345. Compaction::~Compaction() {
  1346. if (input_version_ != nullptr) {
  1347. input_version_->Unref();
  1348. }
  1349. }
  1350. bool Compaction::IsTrivialMove() const {
  1351. const VersionSet* vset = input_version_->vset_;
  1352. // Avoid a move if there is lots of overlapping grandparent data.
  1353. // Otherwise, the move could create a parent file that will require
  1354. // a very expensive merge later on.
  1355. return (num_input_files(0) == 1 && num_input_files(1) == 0 &&
  1356. TotalFileSize(grandparents_) <=
  1357. MaxGrandParentOverlapBytes(vset->options_));
  1358. }
  1359. void Compaction::AddInputDeletions(VersionEdit* edit) {
  1360. for (int which = 0; which < 2; which++) {
  1361. for (size_t i = 0; i < inputs_[which].size(); i++) {
  1362. edit->RemoveFile(level_ + which, inputs_[which][i]->number);
  1363. }
  1364. }
  1365. }
  1366. bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  1367. // Maybe use binary search to find right entry instead of linear search?
  1368. const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  1369. for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
  1370. const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
  1371. while (level_ptrs_[lvl] < files.size()) {
  1372. FileMetaData* f = files[level_ptrs_[lvl]];
  1373. if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
  1374. // We've advanced far enough
  1375. if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
  1376. // Key falls in this file's range, so definitely not base level
  1377. return false;
  1378. }
  1379. break;
  1380. }
  1381. level_ptrs_[lvl]++;
  1382. }
  1383. }
  1384. return true;
  1385. }
  1386. bool Compaction::ShouldStopBefore(const Slice& internal_key) {
  1387. const VersionSet* vset = input_version_->vset_;
  1388. // Scan to find earliest grandparent file that contains key.
  1389. const InternalKeyComparator* icmp = &vset->icmp_;
  1390. while (grandparent_index_ < grandparents_.size() &&
  1391. icmp->Compare(internal_key,
  1392. grandparents_[grandparent_index_]->largest.Encode()) >
  1393. 0) {
  1394. if (seen_key_) {
  1395. overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
  1396. }
  1397. grandparent_index_++;
  1398. }
  1399. seen_key_ = true;
  1400. if (overlapped_bytes_ > MaxGrandParentOverlapBytes(vset->options_)) {
  1401. // Too much overlap for current output; start new output
  1402. overlapped_bytes_ = 0;
  1403. return true;
  1404. } else {
  1405. return false;
  1406. }
  1407. }
  1408. void Compaction::ReleaseInputs() {
  1409. if (input_version_ != nullptr) {
  1410. input_version_->Unref();
  1411. input_version_ = nullptr;
  1412. }
  1413. }
  1414. } // namespace leveldb