Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 305 lines (271 sloc) 10.76 kb
90f6ce8 @argv0 initial import
argv0 authored
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,
97231e0 Add vclock:increment variant that accepts a timestamp.
Jon Meredith authored
38 increment/2,increment/3,all_nodes/1,equal/2,prune/3,timestamp/0]).
90f6ce8 @argv0 initial import
argv0 authored
39
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
40 -ifdef(TEST).
90f6ce8 @argv0 initial import
argv0 authored
41 -include_lib("eunit/include/eunit.hrl").
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
42 -endif.
90f6ce8 @argv0 initial import
argv0 authored
43
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
44 -export_type([vclock/0, timestamp/0, vclock_node/0]).
45
46 -opaque vclock() :: [vc_entry()].
90f6ce8 @argv0 initial import
argv0 authored
47 % The timestamp is present but not used, in case a client wishes to inspect it.
48 -type vc_entry() :: {vclock_node(), {counter(), timestamp()}}.
49
50 % Nodes can have any term() as a name, but they must differ from each other.
51 -type vclock_node() :: term().
52 -type counter() :: integer().
53 -type timestamp() :: integer().
54
55 % @doc Create a brand new vclock.
56 -spec fresh() -> vclock().
57 fresh() ->
58 [].
59
60 % @doc Return true if Va is a direct descendant of Vb, else false -- remember, a vclock is its own descendant!
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
61 -spec descends(Va :: vclock()|[], Vb :: vclock()|[]) -> boolean().
90f6ce8 @argv0 initial import
argv0 authored
62 descends(_, []) ->
63 % all vclocks descend from the empty vclock
64 true;
65 descends(Va, Vb) ->
66 [{NodeB, {CtrB, _T}}|RestB] = Vb,
67 CtrA =
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
68 case lists:keyfind(NodeB, 1, Va) of
69 false -> false;
70 {_, {CA, _TSA}} -> CA
90f6ce8 @argv0 initial import
argv0 authored
71 end,
72 case CtrA of
73 false -> false;
74 _ ->
75 if
76 CtrA < CtrB ->
77 false;
78 true ->
79 descends(Va,RestB)
80 end
81 end.
82
83 % @doc Combine all VClocks in the input list into their least possible
84 % common descendant.
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
85 -spec merge(VClocks :: [vclock()]) -> vclock() | [].
90f6ce8 @argv0 initial import
argv0 authored
86 merge([]) -> [];
87 merge([SingleVclock]) -> SingleVclock;
88 merge([First|Rest]) -> merge(Rest, lists:keysort(1, First)).
89
90 merge([], NClock) -> NClock;
91 merge([AClock|VClocks],NClock) ->
92 merge(VClocks, merge(lists:keysort(1, AClock), NClock, [])).
93
94 merge([], [], AccClock) -> lists:reverse(AccClock);
95 merge([], [Left|Rest], AccClock) -> merge([], Rest, [Left|AccClock]);
96 merge(Left, [], AccClock) -> merge([], Left, AccClock);
97 merge(V=[{Node1,{Ctr1,TS1}}|VClock],
98 N=[{Node2,{Ctr2,TS2}}|NClock], AccClock) ->
99 if Node1 < Node2 ->
100 merge(VClock, N, [{Node1,{Ctr1,TS1}}|AccClock]);
101 Node1 > Node2 ->
102 merge(V, NClock, [{Node2,{Ctr2,TS2}}|AccClock]);
103 true ->
104 ({_Ctr,_TS} = C1) = if Ctr1 > Ctr2 -> {Ctr1,TS1};
105 true -> {Ctr2,TS2}
106 end,
107 merge(VClock, NClock, [{Node1,C1}|AccClock])
108 end.
109
110 % @doc Get the counter value in VClock set from Node.
111 -spec get_counter(Node :: vclock_node(), VClock :: vclock()) -> counter() | undefined.
112 get_counter(Node, VClock) ->
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
113 case lists:keyfind(Node, 1, VClock) of
114 {_, {Ctr, _TS}} -> Ctr;
115 false -> undefined
90f6ce8 @argv0 initial import
argv0 authored
116 end.
117
118 % @doc Get the timestamp value in a VClock set from Node.
119 -spec get_timestamp(Node :: vclock_node(), VClock :: vclock()) -> timestamp() | undefined.
120 get_timestamp(Node, VClock) ->
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
121 case lists:keyfind(Node, 1, VClock) of
122 {_, {_Ctr, TS}} -> TS;
123 false -> undefined
90f6ce8 @argv0 initial import
argv0 authored
124 end.
125
126 % @doc Increment VClock at Node.
127 -spec increment(Node :: vclock_node(), VClock :: vclock()) -> vclock().
128 increment(Node, VClock) ->
97231e0 Add vclock:increment variant that accepts a timestamp.
Jon Meredith authored
129 increment(Node, timestamp(), VClock).
130
131 % @doc Increment VClock at Node.
132 -spec increment(Node :: vclock_node(), IncTs :: timestamp(),
133 VClock :: vclock()) -> vclock().
134 increment(Node, IncTs, VClock) ->
90f6ce8 @argv0 initial import
argv0 authored
135 {{_Ctr, _TS}=C1,NewV} = case lists:keytake(Node, 1, VClock) of
136 false ->
97231e0 Add vclock:increment variant that accepts a timestamp.
Jon Meredith authored
137 {{1, IncTs}, VClock};
90f6ce8 @argv0 initial import
argv0 authored
138 {value, {_N, {C, _T}}, ModV} ->
97231e0 Add vclock:increment variant that accepts a timestamp.
Jon Meredith authored
139 {{C + 1, IncTs}, ModV}
90f6ce8 @argv0 initial import
argv0 authored
140 end,
141 [{Node,C1}|NewV].
142
97231e0 Add vclock:increment variant that accepts a timestamp.
Jon Meredith authored
143
90f6ce8 @argv0 initial import
argv0 authored
144 % @doc Return the list of all nodes that have ever incremented VClock.
145 -spec all_nodes(VClock :: vclock()) -> [vclock_node()].
146 all_nodes(VClock) ->
147 [X || {X,{_,_}} <- VClock].
148
97231e0 Add vclock:increment variant that accepts a timestamp.
Jon Meredith authored
149 % @doc Return a timestamp for a vector clock
150 -spec timestamp() -> timestamp().
90f6ce8 @argv0 initial import
argv0 authored
151 timestamp() ->
152 calendar:datetime_to_gregorian_seconds(erlang:universaltime()).
153
154 % @doc Compares two VClocks for equality.
155 % Not very fast.
156 -spec equal(VClockA :: vclock(), VClockB :: vclock()) -> boolean().
157 equal(VA,VB) ->
158 VSet1 = sets:from_list(VA),
159 VSet2 = sets:from_list(VB),
160 case sets:size(sets:subtract(VSet1,VSet2)) > 0 of
161 true -> false;
162 false ->
163 case sets:size(sets:subtract(VSet2,VSet1)) > 0 of
164 true -> false;
165 false -> true
166 end
167 end.
168
169 % @doc Possibly shrink the size of a vclock, depending on current age and size.
170 -spec prune(V::vclock(), Now::integer(), BucketProps::term()) -> vclock().
171 prune(V,Now,BucketProps) ->
724b951 @eriksoe vclock:prune(): In case of oldish vclock entries with identical times…
eriksoe authored
172 %% This sort need to be deterministic, to avoid spurious merge conflicts later.
173 %% We achieve this by using the node ID as secondary key.
174 SortV = lists:sort(fun({N1,{_,T1}},{N2,{_,T2}}) -> {T1,N1} < {T2,N2} end, V),
90f6ce8 @argv0 initial import
argv0 authored
175 prune_vclock1(SortV,Now,BucketProps).
176 % @private
177 prune_vclock1(V,Now,BProps) ->
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
178 case length(V) =< get_property(small_vclock, BProps) of
90f6ce8 @argv0 initial import
argv0 authored
179 true -> V;
180 false ->
181 {_,{_,HeadTime}} = hd(V),
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
182 case (Now - HeadTime) < get_property(young_vclock,BProps) of
90f6ce8 @argv0 initial import
argv0 authored
183 true -> V;
184 false -> prune_vclock1(V,Now,BProps,HeadTime)
185 end
186 end.
187 % @private
188 prune_vclock1(V,Now,BProps,HeadTime) ->
189 % has a precondition that V is longer than small and older than young
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
190 case length(V) > get_property(big_vclock,BProps) of
90f6ce8 @argv0 initial import
argv0 authored
191 true -> prune_vclock1(tl(V),Now,BProps);
192 false ->
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
193 case (Now - HeadTime) > get_property(old_vclock,BProps) of
90f6ce8 @argv0 initial import
argv0 authored
194 true -> prune_vclock1(tl(V),Now,BProps);
195 false -> V
196 end
197 end.
198
c4fe87f @eriksoe vclock: Replacing proplists:get_value() calls with far faster lists:k…
eriksoe authored
199 get_property(Key, PairList) ->
200 {_Key, Value} = lists:keyfind(Key, 1, PairList),
201 Value.
202
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
203 %% ===================================================================
204 %% EUnit tests
205 %% ===================================================================
206 -ifdef(TEST).
207
208 % @doc Serves as both a trivial test and some example code.
209 example_test() ->
210 A = vclock:fresh(),
211 B = vclock:fresh(),
212 A1 = vclock:increment(a, A),
213 B1 = vclock:increment(b, B),
214 true = vclock:descends(A1,A),
215 true = vclock:descends(B1,B),
216 false = vclock:descends(A1,B1),
217 A2 = vclock:increment(a, A1),
218 C = vclock:merge([A2, B1]),
219 C1 = vclock:increment(c, C),
220 true = vclock:descends(C1, A2),
221 true = vclock:descends(C1, B1),
222 false = vclock:descends(B1, C1),
223 false = vclock:descends(B1, A1),
224 ok.
225
90f6ce8 @argv0 initial import
argv0 authored
226 prune_small_test() ->
227 % vclock with less entries than small_vclock will be untouched
228 Now = riak_core_util:moment(),
229 OldTime = Now - 32000000,
230 SmallVC = [{<<"1">>, {1, OldTime}},
231 {<<"2">>, {2, OldTime}},
232 {<<"3">>, {3, OldTime}}],
233 Props = [{small_vclock,4}],
234 ?assertEqual(lists:sort(SmallVC), lists:sort(prune(SmallVC, Now, Props))).
235
236 prune_young_test() ->
237 % vclock with all entries younger than young_vclock will be untouched
238 Now = riak_core_util:moment(),
239 NewTime = Now - 1,
240 VC = [{<<"1">>, {1, NewTime}},
241 {<<"2">>, {2, NewTime}},
242 {<<"3">>, {3, NewTime}}],
243 Props = [{small_vclock,1},{young_vclock,1000}],
244 ?assertEqual(lists:sort(VC), lists:sort(prune(VC, Now, Props))).
245
246 prune_big_test() ->
247 % vclock not preserved by small or young will be pruned down to
248 % no larger than big_vclock entries
249 Now = riak_core_util:moment(),
250 NewTime = Now - 1000,
251 VC = [{<<"1">>, {1, NewTime}},
252 {<<"2">>, {2, NewTime}},
253 {<<"3">>, {3, NewTime}}],
254 Props = [{small_vclock,1},{young_vclock,1},
255 {big_vclock,2},{old_vclock,100000}],
256 ?assert(length(prune(VC, Now, Props)) =:= 2).
257
258 prune_old_test() ->
259 % vclock not preserved by small or young will be pruned down to
260 % no larger than big_vclock and no entries more than old_vclock ago
261 Now = riak_core_util:moment(),
262 NewTime = Now - 1000,
263 OldTime = Now - 100000,
264 VC = [{<<"1">>, {1, NewTime}},
265 {<<"2">>, {2, OldTime}},
266 {<<"3">>, {3, OldTime}}],
267 Props = [{small_vclock,1},{young_vclock,1},
268 {big_vclock,2},{old_vclock,10000}],
269 ?assert(length(prune(VC, Now, Props)) =:= 1).
270
7ce0ed9 @jonmeredith Added test for determinstic vclock pruning for nodes with same timest…
jonmeredith authored
271 prune_order_test() ->
272 % vclock with two nodes of the same timestamp will be pruned down
273 % to the same node
274 Now = riak_core_util:moment(),
275 OldTime = Now - 100000,
276 VC1 = [{<<"1">>, {1, OldTime}},
277 {<<"2">>, {2, OldTime}}],
278 VC2 = lists:reverse(VC1),
279 Props = [{small_vclock,1},{young_vclock,1},
280 {big_vclock,2},{old_vclock,10000}],
281 ?assertEqual(prune(VC1, Now, Props), prune(VC2, Now, Props)).
282
90f6ce8 @argv0 initial import
argv0 authored
283 accessor_test() ->
284 VC = [{<<"1">>, {1, 1}},
285 {<<"2">>, {2, 2}}],
286 ?assertEqual(1, get_counter(<<"1">>, VC)),
287 ?assertEqual(1, get_timestamp(<<"1">>, VC)),
288 ?assertEqual(2, get_counter(<<"2">>, VC)),
289 ?assertEqual(2, get_timestamp(<<"2">>, VC)),
290 ?assertEqual(undefined, get_counter(<<"3">>, VC)),
291 ?assertEqual(undefined, get_timestamp(<<"3">>, VC)),
292 ?assertEqual([<<"1">>, <<"2">>], all_nodes(VC)).
293
294 merge_test() ->
295 VC1 = [{<<"1">>, {1, 1}},
296 {<<"2">>, {2, 2}},
297 {<<"4">>, {4, 4}}],
298 VC2 = [{<<"3">>, {3, 3}},
299 {<<"4">>, {3, 3}}],
300 ?assertEqual([], merge(vclock:fresh())),
301 ?assertEqual([{<<"1">>,{1,1}},{<<"2">>,{2,2}},{<<"3">>,{3,3}},{<<"4">>,{4,4}}],
302 merge([VC1, VC2])).
ec82f3a @argv0 dialyzer: riak_core fixes
argv0 authored
303
304 -endif.
Something went wrong with that request. Please try again.