Skip to content
This repository
Newer
Older
100644 270 lines (244 sloc) 9.565 kb
90f6ce85 » argv0
2010-07-21 initial import
1 %% -------------------------------------------------------------------
2 %%
3 %% riak_core: Core Riak Application
4 %%
5 %% Copyright (c) 2007-2010 Basho Technologies, Inc. All Rights Reserved.
6 %%
7 %% This file is provided to you under the Apache License,
8 %% Version 2.0 (the "License"); you may not use this file
9 %% except in compliance with the License. You may obtain
10 %% a copy of the License at
11 %%
12 %% http://www.apache.org/licenses/LICENSE-2.0
13 %%
14 %% Unless required by applicable law or agreed to in writing,
15 %% software distributed under the License is distributed on an
16 %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 %% KIND, either express or implied. See the License for the
18 %% specific language governing permissions and limitations
19 %% under the License.
20 %%
21 %% -------------------------------------------------------------------
22
23 %% @doc A simple Erlang implementation of vector clocks as inspired by Lamport logical clocks.
24 %%
25 %% @reference Leslie Lamport (1978). "Time, clocks, and the ordering of events
26 %% in a distributed system". Communications of the ACM 21 (7): 558-565.
27 %%
28 %% @reference Friedemann Mattern (1988). "Virtual Time and Global States of
29 %% Distributed Systems". Workshop on Parallel and Distributed Algorithms:
30 %% pp. 215-226
31
32 -module(vclock).
33
34 -author('Justin Sheehy <justin@basho.com>').
35 -author('Andy Gross <andy@basho.com>').
36
37 -export([fresh/0,descends/2,merge/1,get_counter/2,get_timestamp/2,
38 increment/2,all_nodes/1,equal/2,prune/3]).
39
40 -include_lib("eunit/include/eunit.hrl").
41
42 -type vclock() :: [vc_entry()].
43 % The timestamp is present but not used, in case a client wishes to inspect it.
44 -type vc_entry() :: {vclock_node(), {counter(), timestamp()}}.
45
46 % Nodes can have any term() as a name, but they must differ from each other.
47 -type vclock_node() :: term().
48 -type counter() :: integer().
49 -type timestamp() :: integer().
50
51 % @doc Create a brand new vclock.
52 -spec fresh() -> vclock().
53 fresh() ->
54 [].
55
56 %% @todo Use common_test or other good test framework, and write more tests.
57 %
58 % @doc Serves as both a trivial test and some example code.
59 example_test() ->
60 A = vclock:fresh(),
61 B = vclock:fresh(),
62 A1 = vclock:increment(a, A),
63 B1 = vclock:increment(b, B),
64 true = vclock:descends(A1,A),
65 true = vclock:descends(B1,B),
66 false = vclock:descends(A1,B1),
67 A2 = vclock:increment(a, A1),
68 C = vclock:merge([A2, B1]),
69 C1 = vclock:increment(c, C),
70 true = vclock:descends(C1, A2),
71 true = vclock:descends(C1, B1),
72 false = vclock:descends(B1, C1),
73 false = vclock:descends(B1, A1),
74 ok.
75
76 % @doc Return true if Va is a direct descendant of Vb, else false -- remember, a vclock is its own descendant!
77 -spec descends(Va :: vclock(), Vb :: vclock()) -> boolean().
78 descends(_, []) ->
79 % all vclocks descend from the empty vclock
80 true;
81 descends(Va, Vb) ->
82 [{NodeB, {CtrB, _T}}|RestB] = Vb,
83 CtrA =
84 case proplists:get_value(NodeB, Va) of
85 undefined ->
86 false;
87 {CA, _TSA} -> CA
88 end,
89 case CtrA of
90 false -> false;
91 _ ->
92 if
93 CtrA < CtrB ->
94 false;
95 true ->
96 descends(Va,RestB)
97 end
98 end.
99
100 % @doc Combine all VClocks in the input list into their least possible
101 % common descendant.
102 -spec merge(VClocks :: [vclock()]) -> vclock().
103 merge([]) -> [];
104 merge([SingleVclock]) -> SingleVclock;
105 merge([First|Rest]) -> merge(Rest, lists:keysort(1, First)).
106
107 merge([], NClock) -> NClock;
108 merge([AClock|VClocks],NClock) ->
109 merge(VClocks, merge(lists:keysort(1, AClock), NClock, [])).
110
111 merge([], [], AccClock) -> lists:reverse(AccClock);
112 merge([], [Left|Rest], AccClock) -> merge([], Rest, [Left|AccClock]);
113 merge(Left, [], AccClock) -> merge([], Left, AccClock);
114 merge(V=[{Node1,{Ctr1,TS1}}|VClock],
115 N=[{Node2,{Ctr2,TS2}}|NClock], AccClock) ->
116 if Node1 < Node2 ->
117 merge(VClock, N, [{Node1,{Ctr1,TS1}}|AccClock]);
118 Node1 > Node2 ->
119 merge(V, NClock, [{Node2,{Ctr2,TS2}}|AccClock]);
120 true ->
121 ({_Ctr,_TS} = C1) = if Ctr1 > Ctr2 -> {Ctr1,TS1};
122 true -> {Ctr2,TS2}
123 end,
124 merge(VClock, NClock, [{Node1,C1}|AccClock])
125 end.
126
127 % @doc Get the counter value in VClock set from Node.
128 -spec get_counter(Node :: vclock_node(), VClock :: vclock()) -> counter() | undefined.
129 get_counter(Node, VClock) ->
130 case proplists:get_value(Node, VClock) of
131 {Ctr, _TS} -> Ctr;
132 undefined -> undefined
133 end.
134
135 % @doc Get the timestamp value in a VClock set from Node.
136 -spec get_timestamp(Node :: vclock_node(), VClock :: vclock()) -> timestamp() | undefined.
137 get_timestamp(Node, VClock) ->
138 case proplists:get_value(Node, VClock) of
139 {_Ctr, TS} -> TS;
140 undefined -> undefined
141 end.
142
143 % @doc Increment VClock at Node.
144 -spec increment(Node :: vclock_node(), VClock :: vclock()) -> vclock().
145 increment(Node, VClock) ->
146 {{_Ctr, _TS}=C1,NewV} = case lists:keytake(Node, 1, VClock) of
147 false ->
148 {{1, timestamp()}, VClock};
149 {value, {_N, {C, _T}}, ModV} ->
150 {{C + 1, timestamp()}, ModV}
151 end,
152 [{Node,C1}|NewV].
153
154 % @doc Return the list of all nodes that have ever incremented VClock.
155 -spec all_nodes(VClock :: vclock()) -> [vclock_node()].
156 all_nodes(VClock) ->
157 [X || {X,{_,_}} <- VClock].
158
159 % @private
160 timestamp() ->
161 calendar:datetime_to_gregorian_seconds(erlang:universaltime()).
162
163 % @doc Compares two VClocks for equality.
164 % Not very fast.
165 -spec equal(VClockA :: vclock(), VClockB :: vclock()) -> boolean().
166 equal(VA,VB) ->
167 VSet1 = sets:from_list(VA),
168 VSet2 = sets:from_list(VB),
169 case sets:size(sets:subtract(VSet1,VSet2)) > 0 of
170 true -> false;
171 false ->
172 case sets:size(sets:subtract(VSet2,VSet1)) > 0 of
173 true -> false;
174 false -> true
175 end
176 end.
177
178 % @doc Possibly shrink the size of a vclock, depending on current age and size.
179 -spec prune(V::vclock(), Now::integer(), BucketProps::term()) -> vclock().
180 prune(V,Now,BucketProps) ->
181 SortV = lists:sort(fun({_,{_,A}},{_,{_,B}}) -> A < B end, V),
182 prune_vclock1(SortV,Now,BucketProps).
183 % @private
184 prune_vclock1(V,Now,BProps) ->
185 case length(V) =< proplists:get_value(small_vclock,BProps) of
186 true -> V;
187 false ->
188 {_,{_,HeadTime}} = hd(V),
189 case (Now - HeadTime) < proplists:get_value(young_vclock,BProps) of
190 true -> V;
191 false -> prune_vclock1(V,Now,BProps,HeadTime)
192 end
193 end.
194 % @private
195 prune_vclock1(V,Now,BProps,HeadTime) ->
196 % has a precondition that V is longer than small and older than young
197 case length(V) > proplists:get_value(big_vclock,BProps) of
198 true -> prune_vclock1(tl(V),Now,BProps);
199 false ->
200 case (Now - HeadTime) > proplists:get_value(old_vclock,BProps) of
201 true -> prune_vclock1(tl(V),Now,BProps);
202 false -> V
203 end
204 end.
205
206 prune_small_test() ->
207 % vclock with less entries than small_vclock will be untouched
208 Now = riak_core_util:moment(),
209 OldTime = Now - 32000000,
210 SmallVC = [{<<"1">>, {1, OldTime}},
211 {<<"2">>, {2, OldTime}},
212 {<<"3">>, {3, OldTime}}],
213 Props = [{small_vclock,4}],
214 ?assertEqual(lists:sort(SmallVC), lists:sort(prune(SmallVC, Now, Props))).
215
216 prune_young_test() ->
217 % vclock with all entries younger than young_vclock will be untouched
218 Now = riak_core_util:moment(),
219 NewTime = Now - 1,
220 VC = [{<<"1">>, {1, NewTime}},
221 {<<"2">>, {2, NewTime}},
222 {<<"3">>, {3, NewTime}}],
223 Props = [{small_vclock,1},{young_vclock,1000}],
224 ?assertEqual(lists:sort(VC), lists:sort(prune(VC, Now, Props))).
225
226 prune_big_test() ->
227 % vclock not preserved by small or young will be pruned down to
228 % no larger than big_vclock entries
229 Now = riak_core_util:moment(),
230 NewTime = Now - 1000,
231 VC = [{<<"1">>, {1, NewTime}},
232 {<<"2">>, {2, NewTime}},
233 {<<"3">>, {3, NewTime}}],
234 Props = [{small_vclock,1},{young_vclock,1},
235 {big_vclock,2},{old_vclock,100000}],
236 ?assert(length(prune(VC, Now, Props)) =:= 2).
237
238 prune_old_test() ->
239 % vclock not preserved by small or young will be pruned down to
240 % no larger than big_vclock and no entries more than old_vclock ago
241 Now = riak_core_util:moment(),
242 NewTime = Now - 1000,
243 OldTime = Now - 100000,
244 VC = [{<<"1">>, {1, NewTime}},
245 {<<"2">>, {2, OldTime}},
246 {<<"3">>, {3, OldTime}}],
247 Props = [{small_vclock,1},{young_vclock,1},
248 {big_vclock,2},{old_vclock,10000}],
249 ?assert(length(prune(VC, Now, Props)) =:= 1).
250
251 accessor_test() ->
252 VC = [{<<"1">>, {1, 1}},
253 {<<"2">>, {2, 2}}],
254 ?assertEqual(1, get_counter(<<"1">>, VC)),
255 ?assertEqual(1, get_timestamp(<<"1">>, VC)),
256 ?assertEqual(2, get_counter(<<"2">>, VC)),
257 ?assertEqual(2, get_timestamp(<<"2">>, VC)),
258 ?assertEqual(undefined, get_counter(<<"3">>, VC)),
259 ?assertEqual(undefined, get_timestamp(<<"3">>, VC)),
260 ?assertEqual([<<"1">>, <<"2">>], all_nodes(VC)).
261
262 merge_test() ->
263 VC1 = [{<<"1">>, {1, 1}},
264 {<<"2">>, {2, 2}},
265 {<<"4">>, {4, 4}}],
266 VC2 = [{<<"3">>, {3, 3}},
267 {<<"4">>, {3, 3}}],
268 ?assertEqual([], merge(vclock:fresh())),
269 ?assertEqual([{<<"1">>,{1,1}},{<<"2">>,{2,2}},{<<"3">>,{3,3}},{<<"4">>,{4,4}}],
270 merge([VC1, VC2])).
Something went wrong with that request. Please try again.