Skip to content
This repository has been archived by the owner on Oct 22, 2021. It is now read-only.

Commit

Permalink
Implementation of efficient btree copying.
Browse files Browse the repository at this point in the history
If we have a source of sorted k/v data its possible to efficiently
construct a btree by streaming them to disk and building the upper btree
nodes on demand. This process also has the nice property that it results
in zero garbage for the new btree.

The two downsides to this process are that it can't be resumed if
interrupted and can not be merged into an existing btree.

The couch_btree build API looks like this:

    % Some preparation
    {ok, Fd} = couch_file:open("newbtree.dat", [create]),
    {ok, InitBtree} = couch_btree:open(nil, Fd),

    % Build the new tree.
    Init = couch_btree:build_init(InitBtree),
    Final = lists:foldl(fun(I, Acc) ->
        couch_btree:build_add({I, I}, Acc)
    end, Init, lists:seq(1, 1000)),
    {ok, NewBtree} = couch_btree:build_finish(Final).

Original concept from Filipe Manana
  • Loading branch information
davisp committed Aug 28, 2011
1 parent 2529e3c commit a17ed18
Show file tree
Hide file tree
Showing 2 changed files with 164 additions and 0 deletions.
76 changes: 76 additions & 0 deletions apps/couch/src/couch_btree.erl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
-export([open/2, open/3, query_modify/4, add/2, add_remove/3]).
-export([fold/4, full_reduce/1, final_reduce/2, foldl/3, foldl/4]).
-export([fold_reduce/4, lookup/2, get_state/1, set_options/2]).
-export([copy/2, build_init/1, build_add/2, build_finish/1]).

-record(btree,
{fd,
Expand Down Expand Up @@ -687,3 +688,78 @@ stream_kv_node2(Bt, Reds, PrevKVs, [{K,V} | RestKVs], InRange, Dir, Fun, Acc) ->
{stop, {PrevKVs, Reds}, Acc2}
end
end.


copy(Src, Fd) ->
Dst = Src#btree{fd=Fd, root=nil},
FoldFun = fun(KV, _Red, Acc) ->
{ok, build_add(Acc, extract(Src, KV))}
end,
InitAcc = build_init(Dst),
{ok, _, FinalAcc} = foldl(Src, FoldFun, InitAcc),
build_finish(FinalAcc).


build_init(Bt) ->
ChunkSize = couch_config:get("couchdb", "btree_chunk_size", "1279"),
ChunkSizeInt = list_to_integer(ChunkSize),
{Bt, ChunkSizeInt, nil, [{[], 0}]}.


build_add({Bt, ChunkSize, nil, Nodes}, {K, _}=KV) ->
% First key insertion
NewNodes = build_add(Bt, ChunkSize, kv_node, KV, Nodes),
{Bt, ChunkSize, {prev, K}, NewNodes};
build_add({Bt, ChunkSize, {prev,P}, Nodes}, {K, _}=KV) ->
% Each new key must be strictly greater than the
% previous key inserted.
case less(Bt, P, K) and not less(Bt, K, P) of
false -> throw({build_error, invalid_key_order});
_ -> ok
end,
NodeList = build_add(Bt, ChunkSize, kv_node, KV, Nodes),
{Bt, ChunkSize, {prev, K}, NodeList}.


build_add(_Bt, _ChunkSize, _NodeType, Entry, [{[], 0} | RestNodes]) ->
[{[Entry], erlang:external_size(Entry)} | RestNodes];
build_add(Bt, ChunkSize, kp_node, Entry, []) ->
build_add(Bt, ChunkSize, kp_node, Entry, [{[], 0}]);
build_add(Bt, ChunkSize, NodeType, Entry, [{NodeAcc0, Size0} | RestNodes]) ->
NodeAcc = [Entry | NodeAcc0],
Size = Size0 + erlang:external_size(Entry),
case Size > ChunkSize of
true ->
Node = lists:reverse(NodeAcc),
{LastKey, _} = Entry,
{ok, Ptr} = couch_file:append_term(Bt#btree.fd, {NodeType, Node}),
Red = reduce_node(Bt, NodeType, Node),
KP = {LastKey, {Ptr, Red}},
NewNodes = build_add(Bt, ChunkSize, kp_node, KP, RestNodes),
[{[], 0} | NewNodes];
false ->
[{NodeAcc, Size} | RestNodes]
end.


build_finish({Bt, _ChunkSize, _Prev, NodeList}) ->
{ok, Bt#btree{root=build_finish(Bt, kv_node, NodeList)}}.


build_finish(_Bt, _NodeType, [{[], _}]) ->
nil;
build_finish(Bt, _NodeType, [{[], _} | RestNodes]) ->
build_finish(Bt, kp_node, RestNodes);
build_finish(Bt, NodeType, [{NodeAcc, _} | RestNodes]) ->
Node = lists:reverse(NodeAcc),
{ok, Ptr} = couch_file:append_term(Bt#btree.fd, {NodeType, Node}),
Red = reduce_node(Bt, NodeType, Node),
case RestNodes of
[] ->
{Ptr, Red};
[{KPs, _Size} | RestRestNodes] ->
[{LastKey, _} | _Rest] = NodeAcc,
KP = {LastKey, {Ptr, Red}},
build_finish(Bt, kp_node, [{[KP | KPs], nil} | RestRestNodes])
end.

88 changes: 88 additions & 0 deletions apps/couch/test/etap/022-btree-copy.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -pa ./src/couchdb -sasl errlog_type error -boot start_sasl -noshell

% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.


path(FileName) ->
test_util:build_file(FileName).


main(_) ->
test_util:init_code_path(),
couch_config:start_link([]),
etap:plan(length(counts()) * 2),
case (catch test()) of
ok ->
etap:end_tests();
Other ->
etap:diag(io_lib:format("Test died abnormally:~n~p", [Other])),
timer:sleep(333),
etap:bail()
end,
ok.


test() ->
lists:foreach(fun(C) -> test_copy(C) end, counts()),
ok.


counts() ->
[
10, 20, 50, 100, 300, 500,
700, 811, 2333, 6666, 9999, 15003,
21477, 38888, 66069, 150123, 420789, 711321
].


reduce_fun() ->
fun
(reduce, KVs) -> length(KVs);
(rereduce, Reds) -> lists:sum(Reds)
end.


test_copy(NumItems) ->
{ok, SrcBt0} = open_btree("./apps/couch/test/etap/temp.022.1"),
{ok, SrcBt} = load_btree(SrcBt0, NumItems),
Opts = [create, overwrite],
{ok, Fd} = couch_file:open(path("./apps/couch/test/etap/temp.022.2"), Opts),
{ok, DstBt} = couch_btree:copy(SrcBt, Fd),
check_same(SrcBt, DstBt).


open_btree(Filename) ->
{ok, Fd} = couch_file:open(path(Filename), [create, overwrite]),
couch_btree:open(nil, Fd, [{reduce, reduce_fun()}]).


load_btree(Bt, N) when N < 1000 ->
KVs = [{I, I} || I <- lists:seq(1, N)],
couch_btree:add(Bt, KVs);
load_btree(Bt, N) ->
C = N - 1000,
KVs = [{I+C, I+C} || I <- lists:seq(1, 100)],
{ok, Bt1} = couch_btree:add(Bt, KVs),
load_btree(Bt1, C).


check_same(Src, Dst) ->
{_, SrcRed} = couch_btree:get_state(Src),
{_, DstRed} = couch_btree:get_state(Dst),
etap:is(DstRed, SrcRed, "Same reduction value in copied btree."),
{ok, _, SrcKVs} = couch_btree:foldl(Src, fun(KV, A) -> {ok,[KV|A]} end, []),
{ok, _, DstKVs} = couch_btree:foldl(Dst, fun(KV, A) -> {ok,[KV|A]} end, []),
etap:is(SrcKVs, DstKVs, "Same key value pairs in copied btree.").

0 comments on commit a17ed18

Please sign in to comment.