-
Notifications
You must be signed in to change notification settings - Fork 233
/
riak_kv_entropy_manager.erl
1156 lines (1042 loc) · 42.6 KB
/
riak_kv_entropy_manager.erl
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%% -------------------------------------------------------------------
%%
%% Copyright (c) 2012 Basho Technologies, Inc. All Rights Reserved.
%%
%% This file is provided to you 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.
%%
%% -------------------------------------------------------------------
-module(riak_kv_entropy_manager).
-behaviour(gen_server).
%% API
-export([start_link/0,
manual_exchange/1,
enabled/0,
enable/0,
disable/0,
set_mode/1,
set_debug/1,
cancel_exchange/1,
cancel_exchanges/0,
get_lock/1,
get_lock/2,
release_lock/1,
requeue_poke/1,
start_exchange_remote/3,
start_exchange_remote/4,
exchange_status/4,
expire_trees/0,
clear_trees/0,
get_version/0,
get_partition_version/1,
get_pending_version/0,
get_upgraded/0,
get_trees_version/0]).
-export([all_pairwise_exchanges/2]).
-export([throttle/0,
get_aae_throttle/0,
set_aae_throttle/1,
is_aae_throttle_enabled/0,
disable_aae_throttle/0,
enable_aae_throttle/0,
get_aae_throttle_limits/0,
set_aae_throttle_limits/1,
get_max_local_vnodeq/0]).
-export([multicall/5]). % for meck twiddle-testing
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-ifdef(TEST).
-export([query_and_set_aae_throttle/1]). % for eunit twiddle-testing
-export([make_state/0, get_last_throttle/1]). % for eunit twiddle-testing
-include_lib("eunit/include/eunit.hrl").
-endif.
-type index() :: non_neg_integer().
-type index_n() :: {index(), pos_integer()}.
-type vnode() :: {index(), node()}.
-type exchange() :: {index(), index(), index_n()}.
-type riak_core_ring() :: riak_core_ring:riak_core_ring().
-type version() :: legacy | non_neg_integer().
-type orddict(Key, Val) :: [{Key, Val}].
-record(state, {mode = automatic :: automatic | manual,
trees = [] :: orddict(index(), pid()),
tree_queue = [] :: orddict(index(), pid()),
trees_version = [] :: orddict(index(), version()),
locks = [] :: [{pid(), reference()}],
build_tokens = 0 :: non_neg_integer(),
exchange_queue = [] :: [exchange()],
exchanges = [] :: [{index(), reference(), pid()}],
vnode_status_pid = undefined :: 'undefined' | pid(),
last_throttle = undefined :: 'undefined' | non_neg_integer(),
version = legacy :: version(),
pending_version = legacy :: version()
}).
-type state() :: #state{}.
-define(DEFAULT_CONCURRENCY, 2).
-define(DEFAULT_BUILD_LIMIT, {1, 3600000}). %% Once per hour
-define(KV_ENTROPY_LOCK_TIMEOUT, app_helper:get_env(riak_kv, anti_entropy_lock_timeout, 10000)).
-define(AAE_THROTTLE_KEY, aae_throttle).
-define(DEFAULT_AAE_THROTTLE_LIMITS,
[{-1,0}, {200,10}, {500,50}, {750,250}, {900,1000}, {1100,5000}]).
-define(ETS, entropy_manager_ets).
-define(POKES_PER_TICK, 2).
-export_type([exchange/0]).
%%%===================================================================
%%% API
%%%===================================================================
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
%% @doc Acquire an exchange concurrency lock if available, and associate
%% the lock with the calling process.
-spec get_lock(any()) -> ok | max_concurrency.
get_lock(Type) ->
get_lock(Type, self()).
%% @doc Acquire an exchange concurrency lock if available, and associate
%% the lock with the provided pid.
-spec get_lock(any(), pid()) -> ok | max_concurrency.
get_lock(Type, Pid) ->
gen_server:call(?MODULE, {get_lock, Type, Pid}, ?KV_ENTROPY_LOCK_TIMEOUT).
-spec release_lock(pid()) -> ok.
release_lock(Pid) ->
gen_server:cast(?MODULE, {release_lock, Pid}).
%% @doc Acquire the necessary locks for an entropy exchange with the specified
%% remote vnode. The request is sent to the remote entropy manager which
%% will try to acquire a concurrency lock. If successful, the request is
%% then forwarded to the relevant index_hashtree to acquire a tree lock.
%% If both locks are acquired, the pid of the remote index_hashtree is
%% returned. This function assumes a legacy version of the hashtree
%% and is left over for support for mixed clusters with pre-2.2 nodes
-spec start_exchange_remote({index(), node()}, index_n(), pid())
-> {remote_exchange, pid()} |
{remote_exchange, anti_entropy_disabled} |
{remote_exchange, max_concurrency} |
{remote_exchange, not_built} |
{remote_exchange, already_locked} |
{remote_exchange, bad_version}.
start_exchange_remote(VNode, IndexN, FsmPid) ->
start_exchange_remote(VNode, IndexN, FsmPid, legacy).
-spec start_exchange_remote({index(), node()}, index_n(), pid(), version())
-> {remote_exchange, pid()} |
{remote_exchange, anti_entropy_disabled} |
{remote_exchange, max_concurrency} |
{remote_exchange, not_built} |
{remote_exchange, already_locked} |
{remote_exchange, bad_version}.
start_exchange_remote(_VNode={Index, Node}, IndexN, FsmPid, legacy) ->
gen_server:call({?MODULE, Node},
{start_exchange_remote, FsmPid, Index, IndexN},
infinity);
start_exchange_remote(_VNode={Index, Node}, IndexN, FsmPid, Version) ->
gen_server:call({?MODULE, Node},
{start_exchange_remote, FsmPid, Index, IndexN, Version},
infinity).
%% @doc Used by {@link riak_kv_index_hashtree} to requeue a poke on
%% build failure.
-spec requeue_poke(index()) -> ok.
requeue_poke(Index) ->
gen_server:cast(?MODULE, {requeue_poke, Index}).
%% @doc Used by {@link riak_kv_exchange_fsm} to inform the entropy
%% manager about the status of an exchange (ie. completed without
%% issue, failed, etc)
-spec exchange_status(vnode(), vnode(), index_n(), any()) -> ok.
exchange_status(LocalVN, RemoteVN, IndexN, Reply) ->
gen_server:cast(?MODULE,
{exchange_status,
self(), LocalVN, RemoteVN, IndexN, Reply}).
%% @doc Returns true of AAE is enabled, false otherwise.
-spec enabled() -> boolean().
enabled() ->
{Enabled, _} = settings(),
Enabled.
%% @doc Set AAE to either `automatic' or `manual' mode. In automatic mode, the
%% entropy manager triggers all necessary hashtree exchanges. In manual
%% mode, exchanges must be triggered using {@link manual_exchange/1}.
%% Regardless of exchange mode, the entropy manager will always ensure
%% local hashtrees are built and rebuilt as necessary.
-spec set_mode(automatic | manual) -> ok.
set_mode(Mode=automatic) ->
ok = gen_server:call(?MODULE, {set_mode, Mode}, infinity);
set_mode(Mode=manual) ->
ok = gen_server:call(?MODULE, {set_mode, Mode}, infinity).
%% @doc Toggle debug mode, which prints verbose AAE information to the console.
-spec set_debug(boolean()) -> ok.
set_debug(Enabled) ->
Modules = [riak_kv_index_hashtree,
riak_kv_entropy_manager,
riak_kv_exchange_fsm],
case Enabled of
true ->
[lager:trace_console([{module, Mod}]) || Mod <- Modules];
false ->
[begin
{ok, Trace} = lager:trace_console([{module, Mod}]),
lager:stop_trace(Trace)
end || Mod <- Modules]
end,
ok.
-spec enable() -> ok.
enable() ->
gen_server:call(?MODULE, enable, infinity).
-spec disable() -> ok.
disable() ->
gen_server:call(?MODULE, disable, infinity).
-spec expire_trees() -> ok.
expire_trees() ->
gen_server:cast(?MODULE, expire_trees).
-spec clear_trees() -> ok.
clear_trees() ->
gen_server:cast(?MODULE, clear_trees).
-spec get_version() -> version().
get_version() ->
case ets:lookup(?ETS, version) of
[] ->
legacy;
[{version, Version}] ->
Version
end.
-spec get_partition_version(index()) -> version().
get_partition_version(Index) ->
case ets:lookup(?ETS, Index) of
[] ->
legacy;
[{Index, Version}] ->
Version
end.
-spec get_pending_version() -> version().
get_pending_version() ->
case ets:lookup(?ETS, pending_version) of
[] ->
legacy;
[{pending_version, Version}] ->
Version
end.
-spec get_upgraded() -> boolean().
get_upgraded() ->
case {get_version(), get_pending_version()} of
{legacy, legacy} ->
false;
_ ->
true
end.
%% For testing to quickly verify tree versions match up with manager version
-spec get_trees_version() -> [{index(), version()}].
get_trees_version() ->
gen_server:call(?MODULE, get_trees_version, infinity).
%% @doc Manually trigger hashtree exchanges.
%% -- If an index is provided, trigger exchanges between the index and all
%% sibling indices for all index_n.
%% -- If both an index and index_n are provided, trigger exchanges between
%% the index and all sibling indices associated with the specified
%% index_n.
%% -- If an index, remote index, and index_n are provided, trigger an
%% exchange between the index and remote index for the specified
%% index_n.
-spec manual_exchange(index() |
{index(), index_n()} |
{index(), index(), index_n()}) -> ok.
manual_exchange(Exchange) ->
gen_server:call(?MODULE, {manual_exchange, Exchange}, infinity).
-spec cancel_exchange(index()) -> ok | undefined.
cancel_exchange(Index) ->
gen_server:call(?MODULE, {cancel_exchange, Index}, infinity).
-spec cancel_exchanges() -> [index()].
cancel_exchanges() ->
gen_server:call(?MODULE, cancel_exchanges, infinity).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
-spec init([]) -> {'ok',state()}.
init([]) ->
register_capabilities(),
riak_core_throttle:init(riak_kv,
?AAE_THROTTLE_KEY,
{aae_throttle_limits, ?DEFAULT_AAE_THROTTLE_LIMITS},
{aae_throttle_enabled, true}),
?ETS = ets:new(?ETS, [named_table, {read_concurrency, true}]),
schedule_tick(),
{_, Opts} = settings(),
Mode = case proplists:is_defined(manual, Opts) of
true ->
manual;
false ->
automatic
end,
set_debug(proplists:is_defined(debug, Opts)),
State = #state{mode=Mode,
trees=[],
tree_queue=[],
locks=[],
exchanges=[],
exchange_queue=[]},
State2 = reset_build_tokens(State),
schedule_reset_build_tokens(),
{ok, State2}.
register_capabilities() ->
riak_core_capability:register({riak_kv, object_hash_version},
[0, legacy],
legacy),
riak_core_capability:register({riak_kv, anti_entropy},
[enabled_v1, disabled],
disabled).
handle_call({set_mode, Mode}, _From, State=#state{mode=CurrentMode}) ->
State2 = case {CurrentMode, Mode} of
{automatic, manual} ->
%% Clear exchange queue when switching to manual mode
State#state{exchange_queue=[]};
_ ->
State
end,
{reply, ok, State2#state{mode=Mode}};
handle_call({manual_exchange, Exchange}, _From, State) ->
State2 = enqueue_exchange(Exchange, State),
{reply, ok, State2};
handle_call(enable, _From, State) ->
{_, Opts} = settings(),
application:set_env(riak_kv, anti_entropy, {on, Opts}),
{reply, ok, State};
handle_call(disable, _From, State) ->
{_, Opts} = settings(),
application:set_env(riak_kv, anti_entropy, {off, Opts}),
_ = [riak_kv_index_hashtree:stop(T) || {_,T} <- State#state.trees],
{reply, ok, State};
handle_call(get_trees_version, _From, State=#state{trees=Trees}) ->
VTrees = [{Idx, riak_kv_index_hashtree:get_version(Pid)} || {Idx, Pid} <- Trees],
{reply, VTrees, State};
handle_call({get_lock, Type, Pid}, _From, State) ->
{Reply, State2} = do_get_lock(Type, Pid, State),
{reply, Reply, State2};
%% To support compatibility with pre 2.2 nodes.
handle_call({start_exchange_remote, FsmPid, Index, IndexN}, From, State) ->
do_start_exchange_remote(FsmPid, Index, IndexN, legacy, From, State);
handle_call({start_exchange_remote, FsmPid, Index, IndexN, Version}, From, State) ->
do_start_exchange_remote(FsmPid, Index, IndexN, Version, From, State);
handle_call({cancel_exchange, Index}, _From, State) ->
case lists:keyfind(Index, 1, State#state.exchanges) of
false ->
{reply, undefined, State};
{Index, _Ref, Pid} ->
exit(Pid, kill),
{reply, ok, State}
end;
handle_call(cancel_exchanges, _From, State=#state{exchanges=Exchanges}) ->
Indices = [begin
exit(Pid, kill),
Index
end || {Index, _Ref, Pid} <- Exchanges],
{reply, Indices, State};
handle_call(_Request, _From, State) ->
{reply, ok, State}.
handle_cast({release_lock, Pid}, S) ->
S2 = maybe_release_lock(Pid, S),
{noreply, S2};
handle_cast({requeue_poke, Index}, State) ->
State2 = requeue_poke(Index, State),
{noreply, State2};
handle_cast({exchange_status, Pid, LocalVN, RemoteVN, IndexN, Reply}, State) ->
State2 = do_exchange_status(Pid, LocalVN, RemoteVN, IndexN, Reply, State),
{noreply, State2};
handle_cast(clear_trees, S) ->
clear_all_exchanges(S#state.exchanges),
clear_all_trees(S#state.trees),
{noreply, S};
handle_cast(expire_trees, S) ->
ok = expire_all_trees(S#state.trees),
{noreply, S};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(tick, State) ->
State1 = maybe_tick(State),
{noreply, State1};
handle_info(reset_build_tokens, State) ->
State2 = reset_build_tokens(State),
schedule_reset_build_tokens(),
{noreply, State2};
handle_info({{hashtree_pid, Index}, Reply}, State) ->
case Reply of
{ok, Pid} when is_pid(Pid) ->
State2 = add_hashtree_pid(Index, Pid, State),
{noreply, State2};
_ ->
{noreply, State}
end;
handle_info({'DOWN', _, _, Pid, Status}, #state{vnode_status_pid=Pid}=State) ->
case Status of
{result, _} = RES ->
State2 = query_and_set_aae_throttle3(RES, State#state{vnode_status_pid=undefined}),
{noreply, State2};
Else ->
lager:error("query_and_set_aae_throttle error: ~p",[Else]),
{noreply, State}
end;
handle_info({'DOWN', Ref, _, Obj, Status}, State) ->
State2 = maybe_release_lock(Ref, State),
State3 = maybe_clear_exchange(Ref, Status, State2),
State4 = maybe_clear_registered_tree(Obj, State3),
{noreply, State4};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
clear_all_exchanges(Exchanges) ->
[begin
exit(Pid, kill),
Index
end || {Index, _Ref, Pid} <- Exchanges].
clear_all_trees(Trees) ->
[riak_kv_index_hashtree:clear(TPid) || {_, TPid} <- Trees].
expire_all_trees(Trees) ->
_ = [riak_kv_index_hashtree:expire(TPid) || {_, TPid} <- Trees],
ok.
schedule_reset_build_tokens() ->
{_, Reset} = app_helper:get_env(riak_kv, anti_entropy_build_limit,
?DEFAULT_BUILD_LIMIT),
erlang:send_after(Reset, self(), reset_build_tokens).
reset_build_tokens(State) ->
{Tokens, _} = app_helper:get_env(riak_kv, anti_entropy_build_limit,
?DEFAULT_BUILD_LIMIT),
State#state{build_tokens=Tokens}.
-spec settings() -> {boolean(), proplists:proplist()}.
settings() ->
case app_helper:get_env(riak_kv, anti_entropy, {off, []}) of
{on, Opts} ->
{true, Opts};
{off, Opts} ->
{false, Opts};
X ->
lager:warning("Invalid setting for riak_kv/anti_entropy: ~p", [X]),
application:set_env(riak_kv, anti_entropy, {off, []}),
{false, []}
end.
-spec maybe_reload_hashtrees(riak_core_ring(), state()) -> state().
maybe_reload_hashtrees(Ring, State) ->
case lists:member(riak_kv, riak_core_node_watcher:services(node())) of
true ->
case riak_core_ring:check_lastgasp(Ring) of
true ->
State;
false ->
reload_hashtrees(Ring, State)
end;
false ->
State
end.
%% Determine the index_hashtree pid for each running primary vnode. This
%% function is called each tick to ensure that any newly spawned vnodes are
%% queried.
-spec reload_hashtrees(riak_core_ring(), state()) -> state().
reload_hashtrees(Ring, State=#state{trees=Trees}) ->
Indices = riak_core_ring:my_indices(Ring),
Existing = dict:from_list(Trees),
MissingIdx = [Idx || Idx <- Indices,
not dict:is_key(Idx, Existing)],
_ = [riak_kv_vnode:request_hashtree_pid(Idx) || Idx <- MissingIdx],
State.
add_hashtree_pid(Index, Pid, State) ->
add_hashtree_pid(enabled(), Index, Pid, State).
add_hashtree_pid(false, _Index, Pid, State) ->
riak_kv_index_hashtree:stop(Pid),
State;
add_hashtree_pid(true, Index, Pid, State=#state{trees=Trees, trees_version=VTrees}) ->
case orddict:find(Index, Trees) of
{ok, Pid} ->
%% Already know about this hashtree
State;
_ ->
monitor(process, Pid),
Version = riak_kv_index_hashtree:get_version(Pid),
Trees2 = orddict:store(Index, Pid, Trees),
VTrees2 = orddict:store(Index, Version, VTrees),
ets:insert(?ETS, {Index, Version}),
State2 = State#state{trees=Trees2, trees_version=VTrees2},
State3 = add_index_exchanges(Index, State2),
State4 = check_upgrade(State3),
State4
end.
-spec do_get_lock(any(),pid(),state())
-> {ok | max_concurrency | build_limit_reached, state()}.
do_get_lock(Type, Pid, State=#state{locks=Locks}) ->
Concurrency = app_helper:get_env(riak_kv,
anti_entropy_concurrency,
?DEFAULT_CONCURRENCY),
case length(Locks) >= Concurrency of
true ->
{max_concurrency, State};
false ->
case check_lock_type(Type, State) of
{ok, State2} ->
Ref = monitor(process, Pid),
State3 = State2#state{locks=[{Pid,Ref}|Locks]},
{ok, State3};
Error ->
{Error, State}
end
end.
-spec do_start_exchange_remote(pid(), index(), index_n(), version(), term(), state())
-> {reply, term(), state()} | {noreply, state()}.
do_start_exchange_remote(FsmPid, Index, IndexN, Version, From, State) ->
Enabled = enabled(),
TreeResult = orddict:find(Index, State#state.trees),
maybe_start_exchange_remote(Enabled, TreeResult, FsmPid, IndexN, Version, From, State).
-spec maybe_start_exchange_remote(Enabled::boolean(),
TreeResult::{ok, term()} | error,
FsmPid::pid(),
IndexN::index_n(),
Version::version(),
From::term(),
State::state()) ->
{noreply, state()} | {reply, term(), state()}.
maybe_start_exchange_remote(false, _, _FsmPid, _IndexN, _Version, _From, State) ->
{reply, {remote_exchange, anti_entropy_disabled}, State};
maybe_start_exchange_remote(_, error, _FsmPid, _IndexN, _Version, _From, State) ->
{reply, {remote_exchange, not_built}, State};
maybe_start_exchange_remote(true, {ok, Tree}, FsmPid, IndexN, Version, From, State) ->
case do_get_lock(exchange_remote, FsmPid, State) of
{ok, State2} ->
%% Concurrency lock acquired, now forward to index_hashtree
%% to acquire tree lock.
riak_kv_index_hashtree:start_exchange_remote(FsmPid, Version, From, IndexN, Tree),
{noreply, State2};
{Reply, State2} ->
{reply, {remote_exchange, Reply}, State2}
end.
-spec check_lock_type(any(), state()) -> build_limit_reached | {ok, state()}.
check_lock_type(Type, State) ->
case Type of
build->
do_get_build_token(State);
% upgrade ->
% do_get_build_token(State);
% Upgrade doesn't actually do any work, so don't spend a token on it
% this reduces the time a cluster spends in lock-down waiting for
% rebuilds to spread through the cluster, and the tokens can be spent
% building these upgraded backends.
_ ->
{ok, State}
end.
-spec do_get_build_token(state()) -> build_limit_reached | {ok, state()}.
do_get_build_token(State=#state{build_tokens=Tokens}) ->
if Tokens > 0 ->
{ok, State#state{build_tokens=Tokens-1}};
true ->
build_limit_reached
end.
-spec maybe_release_lock(reference(), state()) -> state().
maybe_release_lock(Ref, State) ->
Locks = lists:keydelete(Ref, 2, State#state.locks),
State#state{locks=Locks}.
-spec maybe_clear_exchange(reference(), term(), state()) -> state().
maybe_clear_exchange(Ref, Status, State) ->
case lists:keytake(Ref, 2, State#state.exchanges) of
false ->
State;
{value, {Idx,Ref,_Pid}, Exchanges} ->
lager:debug("Untracking exchange: ~p :: ~p", [Idx, Status]),
State#state{exchanges=Exchanges}
end.
-spec maybe_clear_registered_tree(pid(), state()) -> state().
maybe_clear_registered_tree(Pid, State) when is_pid(Pid) ->
case lists:keytake(Pid, 2, State#state.trees) of
false ->
State;
{value, {Index, Pid}, Trees} ->
ets:delete(?ETS, Index),
VTrees = orddict:erase(Index, State#state.trees_version),
State#state{trees=Trees, trees_version=VTrees}
end;
maybe_clear_registered_tree(_, State) ->
State.
-spec next_tree(state()) -> {pid(), state()}.
next_tree(#state{trees=[]}) ->
throw(no_trees_registered);
next_tree(State=#state{tree_queue=[], trees=Trees}) ->
State2 = State#state{tree_queue=Trees},
next_tree(State2);
next_tree(State=#state{tree_queue=Queue}) ->
[{_Index,Pid}|Rest] = Queue,
State2 = State#state{tree_queue=Rest},
{Pid, State2}.
-spec schedule_tick() -> ok.
schedule_tick() ->
%% Perform tick every 15 seconds
DefaultTick = 15000,
Tick = app_helper:get_env(riak_kv,
anti_entropy_tick,
DefaultTick),
erlang:send_after(Tick, ?MODULE, tick),
ok.
-spec maybe_tick(state()) -> state().
maybe_tick(State) ->
case enabled() of
true ->
case riak_core_capability:get({riak_kv, anti_entropy}, disabled) of
disabled ->
NextState = State;
enabled_v1 ->
NextState = tick(State)
end;
false ->
%% Ensure we do not have any running index_hashtrees, which can
%% happen when disabling anti-entropy on a live system.
_ = [riak_kv_index_hashtree:stop(T) || {_,T} <- State#state.trees],
NextState = State
end,
schedule_tick(),
NextState.
-spec tick(state()) -> state().
tick(State) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
State1 = query_and_set_aae_throttle(State),
State2 = maybe_reload_hashtrees(Ring, State1),
State3 = maybe_start_upgrade(Ring, State2),
State4 = lists:foldl(fun(_,S) ->
maybe_poke_tree(S)
end,
State3,
lists:seq(1, ?POKES_PER_TICK)),
State5 = maybe_exchange(Ring, State4),
State5.
-spec maybe_poke_tree(state()) -> state().
maybe_poke_tree(State=#state{trees=[]}) ->
State;
maybe_poke_tree(State) ->
{Tree, State2} = next_tree(State),
riak_kv_index_hashtree:poke(Tree),
State2.
-spec maybe_start_upgrade(riak_core_ring(),state()) -> state().
maybe_start_upgrade(Ring, State=#state{trees=Trees, version=legacy, pending_version=legacy}) ->
Indices = riak_core_ring:my_indices(Ring),
case riak_core_capability:get({riak_kv, object_hash_version}, legacy) of
0 when length(Trees) == length(Indices) ->
maybe_upgrade(State);
_ ->
State
end;
maybe_start_upgrade(_Ring, State) ->
State.
-spec maybe_upgrade(state()) -> state().
maybe_upgrade(State=#state{trees_version = []}) ->
%% No hashtrees have registered with the manager, skip upgrade check
State;
maybe_upgrade(State=#state{trees_version = VTrees}) ->
case [Idx || {Idx, legacy} <- VTrees] of
%% Upgrade is done already, set version in state
[] ->
ets:insert(?ETS, {version, 0}),
State#state{version=0};
%% No trees have been upgraded, check version
%% on other nodes to see if we should immediately start upgrade.
%% Otherwise wait for all local and remote exchanges to complete.
Trees when length(Trees) == length(VTrees) ->
check_remote_upgraded(State);
%% Upgrade already started, set pending_version
_ ->
lager:notice("Hashtree upgrade already in-process, setting pending_version to 0"),
ets:insert(?ETS, {pending_version, 0}),
State#state{pending_version=0}
end.
check_remote_upgraded(State) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
Nodes = riak_core_ring:all_members(Ring),
case lists:any(fun do_check_remote_upgraded/1, Nodes) of
true ->
lager:notice("Starting AAE hashtree upgrade"),
ets:insert(?ETS, {pending_version, 0}),
State#state{pending_version=0};
_ ->
check_exchanges_and_upgrade(State, Nodes)
end.
do_check_remote_upgraded(Node) ->
case riak_core_util:safe_rpc(Node, riak_kv_entropy_manager, get_upgraded, [], 10000) of
Result when is_boolean(Result) ->
Result;
{badrpc, _Reason} ->
false;
_ ->
false
end.
-spec check_exchanges_and_upgrade(state(), list()) -> state().
check_exchanges_and_upgrade(State, Nodes) ->
case riak_kv_entropy_info:all_sibling_exchanges_complete() of
true ->
%% Now check nodes who havent reported success in the ETS table
case check_all_remote_exchanges_complete(Nodes) of
true ->
lager:notice("Starting AAE hashtree upgrade"),
ets:insert(?ETS, {pending_version, 0}),
State#state{pending_version=0};
_ ->
State
end;
_ ->
State
end.
-spec check_all_remote_exchanges_complete(list()) -> boolean().
check_all_remote_exchanges_complete(Nodes) ->
lists:all(fun maybe_check_and_record_remote_exchange/1, Nodes).
-spec maybe_check_and_record_remote_exchange(node()) -> boolean().
maybe_check_and_record_remote_exchange(Node) ->
case ets:lookup(?ETS, Node) of
[{Node, true}] ->
true;
_ ->
Result = check_remote_exchange(Node),
ets:insert(?ETS, {Node, Result}),
Result
end.
-spec check_remote_exchange(node()) -> boolean().
check_remote_exchange(Node) ->
case riak_core_util:safe_rpc(Node, riak_kv_entropy_info, all_sibling_exchanges_complete, [], 10000) of
Result when is_boolean(Result) ->
Result;
{badrpc, _Reason} ->
false;
_ ->
false
end.
-spec check_upgrade(state()) -> state().
check_upgrade(State=#state{pending_version=legacy}) ->
State;
check_upgrade(State=#state{pending_version=PendingVersion,trees_version=VTrees}) ->
%% Verify we have all partitions registered with a hashtree, version
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
Indices = riak_core_ring:my_indices(Ring),
MissingIdx = [Idx || Idx <- Indices,
not orddict:is_key(Idx, VTrees)],
case MissingIdx of
[] ->
case [Idx || {Idx, V} <- VTrees, V == PendingVersion] of
[] ->
State;
Trees when length(Trees) == length(VTrees) ->
lager:notice("Local AAE hashtrees have completed upgrade to version: ~p",[PendingVersion]),
ets:insert(?ETS, {version, PendingVersion}),
ets:insert(?ETS, {pending_version, legacy}),
State#state{version=PendingVersion, pending_version=legacy};
_Trees ->
State
end;
_ ->
State
end.
%%%===================================================================
%%% Exchanging
%%%===================================================================
-spec do_exchange_status(pid(), vnode(), vnode(), index_n(), any(), state()) -> state().
do_exchange_status(_Pid, LocalVN, RemoteVN, IndexN, Reply, State) ->
{LocalIdx, _} = LocalVN,
{RemoteIdx, RemoteNode} = RemoteVN,
case Reply of
ok ->
State;
{remote, anti_entropy_disabled} ->
lager:warning("Active anti-entropy is disabled on ~p", [RemoteNode]),
State;
_ ->
State2 = requeue_exchange(LocalIdx, RemoteIdx, IndexN, State),
State2
end.
-spec enqueue_exchange(index() |
{index(), index_n()} |
{index(), index(), index_n()}, state()) -> state().
enqueue_exchange(E={Index, _RemoteIdx, _IndexN}, State) ->
%% Verify that the exchange is valid
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
Exchanges = all_pairwise_exchanges(Index, Ring),
case lists:member(E, Exchanges) of
true ->
enqueue_exchanges([E], State);
false ->
State
end;
enqueue_exchange({Index, IndexN}, State) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
Exchanges = all_pairwise_exchanges(Index, Ring),
Exchanges2 = [Exchange || Exchange={_, _, IdxN} <- Exchanges,
IdxN =:= IndexN],
enqueue_exchanges(Exchanges2, State);
enqueue_exchange(Index, State) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
Exchanges = all_pairwise_exchanges(Index, Ring),
enqueue_exchanges(Exchanges, State).
-spec enqueue_exchanges([exchange()], state()) -> state().
enqueue_exchanges(Exchanges, State) ->
EQ = prune_exchanges(State#state.exchange_queue ++ Exchanges),
State#state{exchange_queue=EQ}.
-spec start_exchange(vnode(),
{index(), index_n()},
riak_core_ring(),
state()) -> {any(), state()}.
start_exchange(LocalVN, {RemoteIdx, IndexN}, Ring, State) ->
%% in rare cases, when the ring is resized, there may be an
%% exchange enqueued for an index that no longer exists. catch
%% the case here and move on
try riak_core_ring:index_owner(Ring, RemoteIdx) of
Owner ->
Nodes = lists:usort([node(), Owner]),
DownNodes = Nodes -- riak_core_node_watcher:nodes(riak_kv),
case DownNodes of
[] ->
RemoteVN = {RemoteIdx, Owner},
start_exchange(LocalVN, RemoteVN, IndexN, Ring, State);
_ ->
{{riak_kv_down, DownNodes}, State}
end
catch
error:{badmatch,_} ->
lager:warning("ignoring exchange to non-existent index: ~p", [RemoteIdx]),
{ok, State}
end.
start_exchange(LocalVN, RemoteVN, IndexN, Ring, State) ->
{LocalIdx, _} = LocalVN,
{RemoteIdx, _} = RemoteVN,
case riak_core_ring:vnode_type(Ring, LocalIdx) of
primary ->
case orddict:find(LocalIdx, State#state.trees) of
error ->
%% The local vnode has not yet registered it's
%% index_hashtree. Likewise, the vnode may not even
%% be running (eg. after a crash). Send request to
%% the vnode to trigger on-demand start and requeue
%% exchange.
riak_kv_vnode:request_hashtree_pid(LocalIdx),
State2 = requeue_exchange(LocalIdx, RemoteIdx, IndexN, State),
{not_built, State2};
{ok, Tree} ->
case riak_kv_exchange_fsm:start(LocalVN, RemoteVN,
IndexN, Tree, self()) of
{ok, FsmPid} ->
Ref = monitor(process, FsmPid),
Exchanges = State#state.exchanges,
Exchanges2 = [{LocalIdx, Ref, FsmPid} | Exchanges],
{ok, State#state{exchanges=Exchanges2}};
{error, Reason} ->
{Reason, State}
end
end;
_ ->
%% No longer owner of this partition or partition is
%% part or larger future ring, ignore exchange
{not_responsible, State}
end.
-spec all_pairwise_exchanges(index(), riak_core_ring())
-> [exchange()].
all_pairwise_exchanges(Index, Ring) ->
LocalIndexN = riak_kv_util:responsible_preflists(Index, Ring),
Sibs = riak_kv_util:preflist_siblings(Index),
lists:flatmap(
fun(RemoteIdx) ->
RemoteIndexN = riak_kv_util:responsible_preflists(RemoteIdx, Ring),
SharedIndexN = ordsets:intersection(ordsets:from_list(LocalIndexN),
ordsets:from_list(RemoteIndexN)),
[{Index, RemoteIdx, IndexN} || IndexN <- SharedIndexN]
end, Sibs).
-spec all_exchanges(node(), riak_core_ring(), state())
-> [exchange()].
all_exchanges(_Node, Ring, #state{trees=Trees}) ->
Indices = orddict:fetch_keys(Trees),
lists:flatmap(fun(Index) ->
all_pairwise_exchanges(Index, Ring)
end, Indices).
-spec add_index_exchanges(index(), state()) -> state().
add_index_exchanges(_Index, State) when State#state.mode == manual ->
State;
add_index_exchanges(Index, State) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
Exchanges = all_pairwise_exchanges(Index, Ring),
EQ = State#state.exchange_queue ++ Exchanges,
EQ2 = prune_exchanges(EQ),
State#state{exchange_queue=EQ2}.
-spec prune_exchanges([exchange()])
-> [exchange()].
prune_exchanges(Exchanges) ->
L = [if A < B ->
{A, B, IndexN};
true ->
{B, A, IndexN}
end || {A, B, IndexN} <- Exchanges],
lists:usort(L).
-spec already_exchanging(index() ,state()) -> boolean().
already_exchanging(Index, #state{exchanges=E}) ->
case lists:keyfind(Index, 1, E) of
false ->
false;
{Index,_,_} ->
true
end.
-spec maybe_exchange(riak_core_ring(), state()) -> state().
maybe_exchange(Ring, State) ->
case next_exchange(Ring, State) of
{none, State2} ->
State2;
{NextExchange, State2} ->
{LocalIdx, RemoteIdx, IndexN} = NextExchange,
case already_exchanging(LocalIdx, State) of
true ->
requeue_exchange(LocalIdx, RemoteIdx, IndexN, State2);
false ->
LocalVN = {LocalIdx, node()},
{R, State3} = start_exchange(LocalVN,
{RemoteIdx, IndexN},
Ring,
State2),
lager:info("Attempt to start exchange between ~w and ~w"
++ " resulted in ~w",
[IndexN, RemoteIdx, R]),
State3
end
end.
-spec next_exchange(riak_core_ring(), state()) -> {'none' | exchange(), state()}.
next_exchange(_Ring, State=#state{exchange_queue=[], trees=[]}) ->
{none, State};