作者: 韩晨旭 10225101440 李畅 10225102463
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1558 linhas
50 KiB

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