作者: 韩晨旭 10225101440 李畅 10225102463
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1563 行
50 KiB

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