summaryrefslogtreecommitdiff
path: root/src/db.erl
blob: 0b9e9a27ffbc1b00d984349761df62f9583928c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
%%% Copyright (c) 2014-2015, NORDUnet A/S.
%%% See LICENSE for licensing information.

-module(db).
-behaviour(gen_server).

%% API.
-export([start_link/0, stop/0]).
-export([create_size_table/0]).
-export([add/2, add_entryhash/2, set_treesize/1, size/0]).
-export([add_index_nosync_noreverse/2]).
-export([verifiedsize/0, set_verifiedsize/1]).
-export([sendsth_verified/0, set_sendsth_verified/2]).
-export([get_by_index/1, get_by_indices/3, get_by_leaf_hash/1]).
-export([get_by_entry_hash/1, entry_for_leafhash/1, leafhash_for_index/1]).
-export([leafhash_for_indices/2, indexsize/0]).
-export([indexforhash_nosync/2, indexforhash_dosync/0, index_sync/0]).
%% gen_server callbacks.
-export([init/1, handle_call/3, terminate/2, handle_cast/2, handle_info/2,
         code_change/3]).

-import(stacktrace, [call/2]).
-include_lib("stdlib/include/qlc.hrl").
-include("db.hrl").

-define(DB_SIZE_TABLE, db_size).

size() ->
    [{_, Size}] = ets:lookup(?DB_SIZE_TABLE, db_size),
    Size.

verifiedsize() ->
    binary_to_integer(atomic:readfile(verifiedsize_path())).

sendsth_verified() ->
    case atomic:readfile(sendsth_verified_path()) of
        noentry ->
            -1;
        Contents ->
            {struct, PropList} = mochijson2:decode(Contents),
            Index = proplists:get_value(<<"index">>, PropList),
            HashHex = proplists:get_value(<<"hash">>, PropList),
            Hash = mochihex:to_bin(binary_to_list(HashHex)),
            HashFromDB = leafhash_for_index(Index),
            case Hash of
                HashFromDB ->
                    Index;
                _ ->
                    lager:error("~p corrupt: contained ~p:~p, but real hash is ~p", [sendsth_verified_path(), Index, Hash, HashFromDB]),
                    -1
            end
    end.

indexsize() ->
    index:indexsize(index_path()).

init(_Args) ->
    {ok, []}.

create_size_table() ->
    case ets:info(?DB_SIZE_TABLE) of
	undefined ->
	    ok;
	_ ->
	    ets:delete(?DB_SIZE_TABLE)
    end,
    ets:new(?DB_SIZE_TABLE, [set, public, named_table]).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

stop() ->
    call(?MODULE, stop).

%%%%%%%%%%%%%%%%%%%%
%% Public API.

-spec add(binary(), binary()) -> ok.
add(LeafHash, Data) ->
    lager:debug("add leafhash ~s", [mochihex:to_hex(LeafHash)]),
    ok = perm:addvalue(entry_db, LeafHash, Data),
    perm:commit(entry_db),
    lager:debug("leafhash ~s added", [mochihex:to_hex(LeafHash)]),
    ok.

-spec add_entryhash(binary(), binary()) -> ok | differ.
add_entryhash(LeafHash, EntryHash) ->
    perm:addvalue(entryhash_db, EntryHash, LeafHash).

-spec add_index_nosync_noreverse(binary(), non_neg_integer()) -> ok.
add_index_nosync_noreverse(LeafHash, Index) ->
    call(?MODULE, {add_index_nosync_noreverse, {LeafHash, Index}}).

-spec set_treesize(non_neg_integer()) -> ok.
set_treesize(Size) ->
    true = ets:insert(?DB_SIZE_TABLE, {db_size, Size}),
    ok.

-spec set_verifiedsize(non_neg_integer()) -> ok.
set_verifiedsize(Size) ->
    ok = atomic:replacefile(verifiedsize_path(), integer_to_binary(Size)).

-spec set_sendsth_verified(non_neg_integer(), binary()) -> ok.
set_sendsth_verified(Index, Hash) ->
    Contents = mochijson2:encode(
                 {[{index, Index},
                   {hash, list_to_binary(mochihex:to_hex(Hash))}
                  ]}),
    ok = atomic:replacefile(sendsth_verified_path(), Contents).

-spec get_by_indices(integer(), integer(), {sorted, true|false}) ->
                            [{non_neg_integer(), binary(), notfetched}].
get_by_indices(Start, End, {sorted, _Sorted}) ->
    get_by_indices_helper(Start, End).

-spec get_by_index(non_neg_integer()) ->
                          {non_neg_integer(), binary(), noentry | binary()}.
get_by_index(Index) ->
    LeafHash = leafhash_for_index(Index),
    Entry = entry_for_leafhash(LeafHash),
    {Index, LeafHash, Entry}.

-spec get_by_leaf_hash(binary()) -> notfound |
                                    {non_neg_integer(), binary(), binary()}.
get_by_leaf_hash(LeafHash) ->
    case entry_for_leafhash(LeafHash) of
        noentry ->
            notfound;
        Entry ->
            case index_for_leafhash(LeafHash) of
                noentry ->
                        notfound;
                Index ->
                    {Index, LeafHash, Entry}
            end
    end.

-spec get_by_entry_hash(binary()) -> notfound | {notfetched, binary(), binary()}.
get_by_entry_hash(EntryHash) ->
    case leafhash_for_entryhash(EntryHash) of
        noentry ->
            notfound;
        LeafHash ->
	    case entry_for_leafhash(LeafHash) of
	        noentry ->
		    notfound;
		Entry ->
                    %% Don't fetch index, isn't used and might not exist
                    {notfetched, LeafHash, Entry}
            end
    end.

%%%%%%%%%%%%%%%%%%%%
%% gen_server callbacks.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

terminate(_Reason, _State) ->
    io:format("~p terminating~n", [?MODULE]),
    ok.

%%%%%%%%%%%%%%%%%%%%
%% The meat.

% Table for Index -> Leaf hash
index_path() ->
    {ok, Value} = application:get_env(plop, index_path),
    Value.

% File that stores the number of verified entries
verifiedsize_path() ->
    {ok, Value} = application:get_env(plop, verifiedsize_path),
    Value.

% File that stores how far sendsth has verified entries
sendsth_verified_path() ->
    {ok, Value} = application:get_env(plop, sendsth_verified_path),
    Value.

entry_for_leafhash(LeafHash) ->
    perm:getvalue(entry_db, LeafHash).

index_for_leafhash(LeafHash) ->
    case perm:getvalue(indexforhash_db, LeafHash) of
        noentry ->
            noentry;
        Index ->
            binary_to_integer(Index)
    end.

leafhash_for_index(Index) ->
    index:get(index_path(), Index).

leafhash_for_indices(Start, End) ->
    index:getrange(index_path(), Start, End).

leafhash_for_entryhash(EntryHash) ->
    perm:getvalue(entryhash_db, EntryHash).

get_by_indices_helper(Start, _End) when Start < 0 ->
    [];
get_by_indices_helper(Start, End) ->
    EndBound = min(End, indexsize() - 1),
    case Start =< EndBound of
        true ->
            lists:map(fun ({LeafHash, Index}) ->
                              {Index, LeafHash, notfetched}
                      end, lists:zip(leafhash_for_indices(Start, EndBound),
                                     lists:seq(Start, EndBound)));
        false ->
            []
    end.

handle_call(stop, _From, State) ->
    {stop, normal, stopped, State};

handle_call({add_index_nosync_noreverse, {LeafHash, Index}}, _From, State) ->
    ok = index:add_nosync(index_path(), Index, LeafHash),
    {reply, ok, State}.

indexforhash_nosync(LeafHash, Index) ->
    ok = perm:addvalue(indexforhash_db,
                       LeafHash, integer_to_binary(Index)),
    ok.

indexforhash_dosync() ->
    perm:commit(indexforhash_db, 300000),
    ok.

index_sync() ->
    Basepath = index_path(),
    ok = util:fsync([Basepath, filename:dirname(Basepath)]),
    ok.