-
Notifications
You must be signed in to change notification settings - Fork 391
/
riak_core_claimant.erl
1648 lines (1464 loc) · 61.9 KB
/
riak_core_claimant.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_core_claimant).
-behaviour(gen_server).
-include("riak_core_bucket_type.hrl").
%% API
-export([start_link/0]).
-export([leave_member/1,
remove_member/1,
force_replace/2,
replace/2,
resize_ring/1,
abort_resize/0,
plan/0,
commit/0,
clear/0,
ring_changed/2,
pending_close/2,
create_bucket_type/2,
update_bucket_type/2,
bucket_type_status/1,
activate_bucket_type/1,
get_bucket_type/2,
get_bucket_type/3,
bucket_type_iterator/0,
set_node_location/2,
update_v4_solutions/1,
update_v4_cache/1]).
-export([reassign_indices/1]). % helpers for claim sim
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include_lib("kernel/include/logger.hrl").
-type action() :: leave
| remove
| {replace, node()}
| {force_replace, node()}
| {set_location, string()}.
-type riak_core_ring() :: riak_core_ring:riak_core_ring().
%% A tuple representing a given cluster transition:
%% {Ring, NewRing} where NewRing = f(Ring)
-type ring_transition() :: {riak_core_ring(), riak_core_ring()}.
-type v4_solution() ::
{{binring_solve|binring_update,
{binary()|pos_integer(),
list(non_neg_integer()),
#{location := pos_integer(), node := pos_integer()}}},
binary()}.
-export_type([v4_solution/0]).
-record(state, {
last_ring_id,
%% The set of staged cluster changes
changes :: [{node(), action()}],
%% Ring computed during the last planning stage based on
%% applying a set of staged cluster changes. When commiting
%% changes, the computed ring must match the previous planned
%% ring to be allowed.
next_ring :: riak_core_ring()|undefined,
%% Random number seed passed to remove_node to ensure the
%% current randomized remove algorithm is deterministic
%% between plan and commit phases
seed}).
-define(ROUT(S,A),ok).
%%-define(ROUT(S,A),?debugFmt(S,A)).
%%-define(ROUT(S,A),io:format(S,A)).
%%%===================================================================
%%% API
%%%===================================================================
-ifdef(TEST).
-export([stop/0]).
stop() ->
gen_server:call(claimant(), stop).
-endif.
%% @doc Spawn and register the riak_core_claimant server
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
%% @doc Determine how the cluster will be affected by the staged changes,
%% returning the set of pending changes as well as a list of ring
%% modifications that correspond to each resulting cluster transition
%% (eg. the initial transition that applies the staged changes, and
%% any additional transitions triggered by later rebalancing).
-spec plan() -> {error, term()} | {ok, [action()], [ring_transition()]}.
plan() ->
gen_server:call(claimant(), plan, infinity).
%% @doc Commit the set of staged cluster changes, returning true on success.
%% A commit is only allowed to succeed if the ring is ready and if the
%% current set of changes matches those computed by the most recent
%% call to plan/0.
-spec commit() -> ok | {error, term()} | error.
commit() ->
gen_server:call(claimant(), commit, infinity).
-spec update_v4_solutions(v4_solution()) -> ok.
update_v4_solutions(V4Solution) ->
gen_server:cast(?MODULE, {update_v4_solutions, V4Solution}).
%% @doc Stage a request for `Node' to leave the cluster. If committed, `Node'
%% will handoff all of its data to other nodes in the cluster and then
%% shutdown.
leave_member(Node) ->
stage(Node, leave).
%% @doc Stage a request for `Node' to be forcefully removed from the cluster.
%% If committed, all partitions owned by `Node' will immediately be
%% re-assigned to other nodes. No data on `Node' will be transfered to
%% other nodes, and all replicas on `Node' will be lost.
remove_member(Node) ->
stage(Node, remove).
%% @doc Stage a request for `Node' to be replaced by `NewNode'. If committed,
%% `Node' will handoff all of its data to `NewNode' and then shutdown.
%% The current implementation requires `NewNode' to be a fresh node that
%% is joining the cluster and does not yet own any partitions of its own.
replace(Node, NewNode) ->
stage(Node, {replace, NewNode}).
%% @doc Stage a request for `Node' to be forcefully replaced by `NewNode'.
%% If committed, all partitions owned by `Node' will immediately be
%% re-assigned to `NewNode'. No data on `Node' will be transfered,
%% and all replicas on `Node' will be lost. The current implementation
%% requires `NewNode' to be a fresh node that is joining the cluster
%% and does not yet own any partitions of its own.
force_replace(Node, NewNode) ->
stage(Node, {force_replace, NewNode}).
%% @doc Stage a request to resize the ring. If committed, all nodes
%% will participate in resizing operation. Unlike other operations,
%% the new ring is not installed until all transfers have completed.
%% During that time requests continue to be routed to the old ring.
%% After completion, the new ring is installed and data is safely
%% removed from partitons no longer owner by a node or present
%% in the ring.
-spec resize_ring(integer()) -> ok | {error, atom()}.
resize_ring(NewRingSize) ->
%% use the node making the request. it will be ignored
stage(node(), {resize, NewRingSize}).
-spec abort_resize() -> ok | {error, atom()}.
abort_resize() ->
stage(node(), abort_resize).
-spec pending_close(riak_core_ring(), any()) -> ok.
pending_close(Ring, RingID) ->
gen_server:call(?MODULE, {pending_close, Ring, RingID}).
%% @doc Stage a request to set a new location for the given node.
-spec set_node_location(node(), string()) -> ok | {error, atom()}.
set_node_location(Node, Location) ->
stage(Node, {set_location, Location}).
%% @doc Clear the current set of staged transfers
clear() ->
gen_server:call(claimant(), clear, infinity).
%% @doc This function is called as part of the ring reconciliation logic
%% triggered by the gossip subsystem. This is only called on the one
%% node that is currently the claimant. This function is the top-level
%% entry point to the claimant logic that orchestrates cluster state
%% transitions. The current code path:
%% riak_core_gossip:reconcile/2
%% --> riak_core_ring:ring_changed/2
%% -----> riak_core_ring:internal_ring_changed/2
%% --------> riak_core_claimant:ring_changed/2
ring_changed(Node, Ring) ->
internal_ring_changed(Node, Ring).
%% @see riak_core_bucket_type:create/2
-spec create_bucket_type(riak_core_bucket_type:bucket_type(), [{atom(), any()}]) ->
ok | {error, term()}.
create_bucket_type(BucketType, Props) ->
gen_server:call(claimant(), {create_bucket_type, BucketType, Props}, infinity).
%% @see riak_core_bucket_type:status/1
-spec bucket_type_status(riak_core_bucket_type:bucket_type()) ->
undefined | created | ready | active.
bucket_type_status(BucketType) ->
gen_server:call(claimant(), {bucket_type_status, BucketType}, infinity).
%% @see riak_core_bucket_type:activate/1
-spec activate_bucket_type(riak_core_bucket_type:bucket_type()) ->
ok | {error, undefined | not_ready}.
activate_bucket_type(BucketType) ->
gen_server:call(claimant(), {activate_bucket_type, BucketType}, infinity).
%% @doc Lookup the properties for `BucketType'. If there are no properties or
%% the type is inactive, the given `Default' value is returned.
-spec get_bucket_type(riak_core_bucket_type:bucket_type(), X) -> [{atom(), any()}] | X.
get_bucket_type(BucketType, Default) ->
get_bucket_type(BucketType, Default, true).
%% @doc Lookup the properties for `BucketType'. If there are no properties or
%% the type is inactive and `RequireActive' is `true', the given `Default' value is
%% returned.
-spec get_bucket_type(riak_core_bucket_type:bucket_type(), X, boolean()) ->
[{atom(), any()}] | X.
get_bucket_type(BucketType, Default, RequireActive) ->
%% we resolve w/ last-write-wins because conflicts only occur
%% during creation when the claimant is changed and create on a
%% new claimant happens before the original propogates. In this
%% case we want the newest create. Updates can also result in
%% conflicts so we choose the most recent as well.
case riak_core_metadata:get(?BUCKET_TYPE_PREFIX, BucketType,
[{default, Default}]) of
Default -> Default;
Props -> maybe_filter_inactive_type(RequireActive, Default, Props)
end.
%% @see riak_core_bucket_type:update/2
-spec update_bucket_type(riak_core_bucket_type:bucket_type(), [{atom(), any()}]) ->
ok | {error, term()}.
update_bucket_type(BucketType, Props) ->
gen_server:call(claimant(), {update_bucket_type, BucketType, Props}).
%% @see riak_core_bucket_type:iterator/0
-spec bucket_type_iterator() -> riak_core_metadata:iterator().
bucket_type_iterator() ->
riak_core_metadata:iterator(?BUCKET_TYPE_PREFIX, [{default, undefined},
{resolver, fun riak_core_bucket_props:resolve/2}]).
-spec update_v4_cache(v4_solution()) -> ok.
update_v4_cache(V4Solution) ->
Cache =
case get(v4_solutions) of
RetrievedCache when is_list(RetrievedCache) ->
RetrievedCache;
_ ->
[]
end,
put(v4_solutions, lists:ukeysort(1, [V4Solution|Cache])).
%%%===================================================================
%%% Claim sim helpers until refactor
%%%===================================================================
reassign_indices(CState) ->
reassign_indices(CState, [], seed(), fun no_log/2).
%%%===================================================================
%%% Internal API helpers
%%%===================================================================
stage(Node, Action) ->
gen_server:call(claimant(), {stage, Node, Action}, infinity).
claimant() ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
{?MODULE, riak_core_ring:claimant(Ring)}.
maybe_filter_inactive_type(false, _Default, Props) ->
Props;
maybe_filter_inactive_type(true, Default, Props) ->
case type_active(Props) of
true -> Props;
false -> Default
end.
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([]) ->
schedule_tick(),
{ok, #state{changes=[], seed=seed()}}.
handle_call(clear, _From, State) ->
State2 = clear_staged(State),
{reply, ok, State2};
handle_call({stage, Node, Action}, _From, State) ->
{ok, Ring} = riak_core_ring_manager:get_raw_ring(),
{Reply, State2} = maybe_stage(Node, Action, Ring, State),
{reply, Reply, State2};
handle_call(plan, _From, State) ->
{ok, Ring} = riak_core_ring_manager:get_raw_ring(),
case riak_core_ring:ring_ready(Ring) of
false ->
Reply = {error, ring_not_ready},
{reply, Reply, State};
true ->
{Reply, State2} = generate_plan(Ring, State),
{reply, Reply, State2}
end;
handle_call(commit, _From, State) ->
{Reply, State2} = commit_staged(State),
{reply, Reply, State2};
handle_call({create_bucket_type, BucketType, Props0}, _From, State) ->
Existing = get_bucket_type(BucketType, undefined, false),
case can_create_type(BucketType, Existing, Props0) of
{ok, Props} ->
InactiveProps = lists:keystore(active, 1, Props, {active, false}),
ClaimedProps = lists:keystore(claimant, 1, InactiveProps, {claimant, node()}),
riak_core_metadata:put(?BUCKET_TYPE_PREFIX, BucketType, ClaimedProps),
{reply, ok, State};
Error ->
{reply, Error, State}
end;
handle_call({update_bucket_type, BucketType, Props0}, _From, State) ->
Existing = get_bucket_type(BucketType, [], false),
case can_update_type(BucketType, Existing, Props0) of
{ok, Props} ->
MergedProps = riak_core_bucket_props:merge(Props, Existing),
riak_core_metadata:put(?BUCKET_TYPE_PREFIX, BucketType, MergedProps),
{reply, ok, State};
Error ->
{reply, Error, State}
end;
handle_call({bucket_type_status, BucketType}, _From, State) ->
Existing = get_bucket_type(BucketType, undefined, false),
Reply = get_type_status(BucketType, Existing),
{reply, Reply, State};
handle_call({activate_bucket_type, BucketType}, _From, State) ->
Existing = get_bucket_type(BucketType, undefined, false),
Status = get_type_status(BucketType, Existing),
Reply = maybe_activate_type(BucketType, Status, Existing),
{reply, Reply, State};
handle_call({pending_close, Ring, RingID}, _From, State) ->
State2 = tick(Ring, RingID, State),
{reply, ok, State2};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({update_v4_solutions, V4Solution}, State) ->
update_v4_cache(V4Solution),
ok = riak_core_ring_manager:update_v4_solutions(V4Solution),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(tick, State) ->
State2 = tick(none, riak_core_ring_manager:get_ring_id(), State),
{noreply, State2};
handle_info(reset_ring_id, State) ->
State2 = State#state{last_ring_id=undefined},
{noreply, State2};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
%% @private
%% @doc Verify that a cluster change request is valid and add it to
%% the list of staged changes.
maybe_stage(Node, Action, Ring, State=#state{changes=Changes}) ->
case valid_request(Node, Action, Changes, Ring) of
true ->
Changes2 = orddict:store(Node, Action, Changes),
Changes3 = filter_changes(Changes2, Ring),
State2 = State#state{changes=Changes3},
{ok, State2};
Error ->
{Error, State}
end.
%% @private
%% @doc Determine how the staged set of cluster changes will affect
%% the cluster. See {@link plan/0} for additional details.
generate_plan(Ring, State=#state{changes=Changes}) ->
Changes2 = filter_changes(Changes, Ring),
Joining = [{Node, join} || Node <- riak_core_ring:members(Ring, [joining])],
AllChanges = lists:ukeysort(1, Changes2 ++ Joining),
State2 = State#state{changes=Changes2},
generate_plan(AllChanges, Ring, State2).
generate_plan([], _, State) ->
%% There are no changes to apply
{{ok, [], []}, State};
generate_plan(Changes, Ring, State=#state{seed=Seed}) ->
case compute_all_next_rings(Changes, Seed, Ring) of
{error, invalid_resize_claim} ->
{{error, invalid_resize_claim}, State};
{ok, NextRings} ->
{_, NextRing} = hd(NextRings),
State2 = State#state{next_ring=NextRing},
Reply = {ok, Changes, NextRings},
{Reply, State2}
end.
%% @private
%% @doc Commit the set of staged cluster changes. See {@link commit/0}
%% for additional details.
commit_staged(State=#state{next_ring=undefined}) ->
{{error, nothing_planned}, State};
commit_staged(State) ->
case maybe_commit_staged(State) of
{ok, _} ->
State2 = State#state{next_ring=undefined,
changes=[],
seed=seed()},
{ok, State2};
not_changed ->
{error, State};
{not_changed, Reason} ->
{{error, Reason}, State}
end.
%% @private
maybe_commit_staged(State) ->
riak_core_ring_manager:ring_trans(fun maybe_commit_staged/2, State).
%% @private
maybe_commit_staged(Ring, State=#state{changes=Changes, seed=Seed}) ->
Changes2 = filter_changes(Changes, Ring),
case compute_next_ring(Changes2, Seed, Ring) of
{error, invalid_resize_claim} ->
{ignore, invalid_resize_claim};
{ok, NextRing} ->
maybe_commit_staged(Ring, NextRing, State)
end.
%% @private
maybe_commit_staged(Ring, NextRing, #state{next_ring=PlannedRing}) ->
Claimant = riak_core_ring:claimant(Ring),
IsReady = riak_core_ring:ring_ready(Ring),
IsClaimant = (Claimant == node()),
IsSamePlan = same_plan(PlannedRing, NextRing),
case {IsReady, IsClaimant, IsSamePlan} of
{false, _, _} ->
{ignore, ring_not_ready};
{_, false, _} ->
ignore;
{_, _, false} ->
{ignore, plan_changed};
_ ->
NewRing1 = riak_core_ring:increment_vclock(Claimant, NextRing),
{new_ring, NewRing1}
end.
%% @private
%% @doc Clear the current set of staged transfers. Since `joining' nodes
%% are determined based on the node's actual state, rather than a
%% staged action, the only way to clear pending joins is to remove
%% the `joining' nodes from the cluster. Used by the public API
%% call {@link clear/0}.
clear_staged(State) ->
remove_joining_nodes(),
State#state{changes=[], seed=seed()}.
%% @private
remove_joining_nodes() ->
riak_core_ring_manager:ring_trans(fun remove_joining_nodes/2, ok).
%% @private
remove_joining_nodes(Ring, _) ->
Claimant = riak_core_ring:claimant(Ring),
IsClaimant = (Claimant == node()),
Joining = riak_core_ring:members(Ring, [joining]),
AreJoining = (Joining /= []),
case IsClaimant and AreJoining of
false ->
ignore;
true ->
NewRing = remove_joining_nodes_from_ring(Claimant, Joining, Ring),
{new_ring, NewRing}
end.
%% @private
remove_joining_nodes_from_ring(Claimant, Joining, Ring) ->
NewRing =
lists:foldl(fun(Node, RingAcc) ->
riak_core_ring:set_member(Claimant, RingAcc, Node,
invalid, same_vclock)
end, Ring, Joining),
NewRing2 = riak_core_ring:increment_vclock(Claimant, NewRing),
NewRing2.
%% @private
valid_request(Node, Action, Changes, Ring) ->
case Action of
leave ->
valid_leave_request(Node, Ring);
remove ->
valid_remove_request(Node, Ring);
{replace, NewNode} ->
valid_replace_request(Node, NewNode, Changes, Ring);
{force_replace, NewNode} ->
valid_force_replace_request(Node, NewNode, Changes, Ring);
{resize, NewRingSize} ->
valid_resize_request(NewRingSize, Changes, Ring);
abort_resize ->
valid_resize_abort_request(Ring);
{set_location, Location} ->
valid_set_location_request(Location, Node, Ring)
end.
%% @private
valid_leave_request(Node, Ring) ->
case {riak_core_ring:all_members(Ring),
riak_core_ring:member_status(Ring, Node)} of
{_, invalid} ->
{error, not_member};
{[Node], _} ->
{error, only_member};
{_, valid} ->
true;
{_, joining} ->
true;
{_, _} ->
{error, already_leaving}
end.
%% @private
valid_remove_request(Node, Ring) ->
IsClaimant = (Node == riak_core_ring:claimant(Ring)),
case {IsClaimant,
riak_core_ring:all_members(Ring),
riak_core_ring:member_status(Ring, Node)} of
{true, _, _} ->
{error, is_claimant};
{_, _, invalid} ->
{error, not_member};
{_, [Node], _} ->
{error, only_member};
_ ->
true
end.
%% @private
valid_replace_request(Node, NewNode, Changes, Ring) ->
AlreadyReplacement = lists:member(NewNode, existing_replacements(Changes)),
NewJoining =
(riak_core_ring:member_status(Ring, NewNode) == joining)
and (not orddict:is_key(NewNode, Changes)),
case {riak_core_ring:member_status(Ring, Node),
AlreadyReplacement,
NewJoining} of
{invalid, _, _} ->
{error, not_member};
{leaving, _, _} ->
{error, already_leaving};
{_, true, _} ->
{error, already_replacement};
{_, _, false} ->
{error, invalid_replacement};
_ ->
true
end.
%% @private
valid_force_replace_request(Node, NewNode, Changes, Ring) ->
IsClaimant = (Node == riak_core_ring:claimant(Ring)),
AlreadyReplacement = lists:member(NewNode, existing_replacements(Changes)),
NewJoining =
(riak_core_ring:member_status(Ring, NewNode) == joining)
and (not orddict:is_key(NewNode, Changes)),
case {IsClaimant,
riak_core_ring:member_status(Ring, Node),
AlreadyReplacement,
NewJoining} of
{true, _, _, _} ->
{error, is_claimant};
{_, invalid, _, _} ->
{error, not_member};
{_, _, true, _} ->
{error, already_replacement};
{_, _, _, false} ->
{error, invalid_replacement};
_ ->
true
end.
%% @private
%% restrictions preventing resize along with other operations are temporary
valid_resize_request(NewRingSize, [], Ring) ->
Capable = riak_core_capability:get({riak_core, resizable_ring}, false),
IsResizing = riak_core_ring:num_partitions(Ring) =/= NewRingSize,
%% NOTE/TODO: the checks below are a stop-gap measure to limit the changes
%% made by the introduction of ring resizing. future implementation
%% should allow applications to register with some flag indicating support
%% for dynamic ring, if all registered applications support it
%% the cluster is capable. core knowing about search/kv is :(
ControlRunning = app_helper:get_env(riak_control, enabled, false),
SearchRunning = app_helper:get_env(riak_search, enabled, false),
NodeCount = length(riak_core_ring:all_members(Ring)),
Changes = length(riak_core_ring:pending_changes(Ring)) > 0,
case {ControlRunning, SearchRunning, Capable, IsResizing, NodeCount, Changes} of
{false, false, true, true, N, false} when N > 1 -> true;
{true, _, _, _, _, _} -> {error, control_running};
{_, true, _, _, _, _} -> {error, search_running};
{_, _, false, _, _, _} -> {error, not_capable};
{_, _, _, false, _, _} -> {error, same_size};
{_, _, _, _, 1, _} -> {error, single_node};
{_, _, _, _, _, true} -> {error, pending_changes}
end.
valid_resize_abort_request(Ring) ->
IsResizing = riak_core_ring:is_resizing(Ring),
IsPostResize = riak_core_ring:is_post_resize(Ring),
case IsResizing andalso not IsPostResize of
true -> true;
false -> {error, not_resizing}
end.
%% @private
%% Validating node member status
valid_set_location_request(_Location, Node, Ring) ->
case riak_core_ring:member_status(Ring, Node) of
valid ->
true;
joining ->
true;
invalid ->
{error, not_member};
_ ->
true
end.
%% @private
%% @doc Filter out any staged changes that are no longer valid. Changes
%% can become invalid based on other staged changes, or by cluster
%% changes that bypass the staging system.
filter_changes(Changes, Ring) ->
orddict:filter(fun(Node, Change) ->
filter_changes_pred(Node, Change, Changes, Ring)
end, Changes).
%% @private
filter_changes_pred(Node, {Change, NewNode}, Changes, Ring)
when (Change == replace) or (Change == force_replace) ->
IsMember = (riak_core_ring:member_status(Ring, Node) /= invalid),
IsJoining = (riak_core_ring:member_status(Ring, NewNode) == joining),
NotChanging = (not orddict:is_key(NewNode, Changes)),
IsMember and IsJoining and NotChanging;
filter_changes_pred(Node, _, _, Ring) ->
IsMember = (riak_core_ring:member_status(Ring, Node) /= invalid),
IsMember.
%% @private
existing_replacements(Changes) ->
[Node || {_, {Change, Node}} <- Changes,
(Change == replace) or (Change == force_replace)].
%% @private
%% Determine if two rings have logically equal cluster state
same_plan(RingA, RingB) ->
(riak_core_ring:all_member_status(RingA) == riak_core_ring:all_member_status(RingB)) andalso
(riak_core_ring:all_owners(RingA) == riak_core_ring:all_owners(RingB)) andalso
(riak_core_ring:pending_changes(RingA) == riak_core_ring:pending_changes(RingB)).
schedule_tick() ->
Tick = app_helper:get_env(riak_core, claimant_tick, 10000),
erlang:send_after(Tick, ?MODULE, tick).
tick(PreFetchRing, RingID, State=#state{last_ring_id=LastID}) ->
maybe_enable_ensembles(),
case RingID of
LastID ->
schedule_tick(),
State;
RingID ->
Ring =
case PreFetchRing of
none ->
{ok, Ring0} = riak_core_ring_manager:get_raw_ring(),
Ring0;
PreFetchRing ->
PreFetchRing
end,
case riak_core_ring:check_lastgasp(Ring) of
true ->
?LOG_INFO("Ingoring fresh ring as shutting down"),
ok;
false ->
maybe_bootstrap_root_ensemble(Ring),
maybe_force_ring_update(Ring),
schedule_tick()
end,
State#state{last_ring_id=RingID}
end.
maybe_force_ring_update(Ring) ->
IsClaimant = (riak_core_ring:claimant(Ring) == node()),
IsReady = riak_core_ring:ring_ready(Ring),
%% Do not force if we have any joining nodes unless any of them are
%% auto-joining nodes. Otherwise, we will force update continuously.
JoinBlock = (are_joining_nodes(Ring)
andalso (auto_joining_nodes(Ring) == [])),
case IsClaimant and IsReady and (not JoinBlock) of
true ->
do_maybe_force_ring_update(Ring);
false ->
ok
end.
do_maybe_force_ring_update(Ring) ->
case compute_next_ring([], seed(), Ring) of
{ok, NextRing} ->
case same_plan(Ring, NextRing) of
false ->
?LOG_WARNING("Forcing update of stalled ring"),
riak_core_ring_manager:force_update();
true ->
ok
end;
_ ->
ok
end.
%% @private
can_create_type(BucketType, undefined, Props) ->
riak_core_bucket_props:validate(create, {BucketType, undefined}, undefined, Props);
can_create_type(BucketType, Existing, Props) ->
Active = type_active(Existing),
Claimed = node() =:= type_claimant(Existing),
case {Active, Claimed} of
%% if type is not active and this claimant has claimed it
%% then we can re-create the type.
{false, true} -> riak_core_bucket_props:validate(create, {BucketType, undefined},
Existing, Props);
{true, _} -> {error, already_active};
{_, false} -> {error, not_claimed}
end.
%% @private
can_update_type(_BucketType, undefined, _Props) ->
{error, undefined};
can_update_type(BucketType, Existing, Props) ->
case type_active(Existing) of
true -> riak_core_bucket_props:validate(update, {BucketType, undefined},
Existing, Props);
false -> {error, not_active}
end.
%% @private
get_type_status(_BucketType, undefined) ->
undefined;
get_type_status(BucketType, Props) ->
case type_active(Props) of
true -> active;
false -> get_remote_type_status(BucketType, Props)
end.
%% @private
get_remote_type_status(BucketType, Props) ->
{ok, R} = riak_core_ring_manager:get_my_ring(),
Members = riak_core_ring:all_members(R),
{AllProps, BadNodes} = rpc:multicall(lists:delete(node(), Members),
riak_core_metadata,
get, [?BUCKET_TYPE_PREFIX, BucketType, [{default, []}]]),
SortedProps = lists:ukeysort(1, Props),
%% P may be a {badrpc, ...} in addition to a list of properties when there are older nodes involved
DiffProps = [P || P <- AllProps, (not is_list(P) orelse lists:ukeysort(1, P) =/= SortedProps)],
case {DiffProps, BadNodes} of
{[], []} -> ready;
%% unreachable nodes may or may not have correct value, so we assume they dont
{_, _} -> created
end.
%% @private
maybe_activate_type(_BucketType, undefined, _Props) ->
{error, undefined};
maybe_activate_type(_BucketType, created, _Props) ->
{error, not_ready};
maybe_activate_type(_BucketType, active, _Props) ->
ok;
maybe_activate_type(BucketType, ready, Props) ->
ActiveProps = lists:keystore(active, 1, Props, {active, true}),
riak_core_metadata:put(?BUCKET_TYPE_PREFIX, BucketType, ActiveProps).
%% @private
type_active(Props) ->
{active, true} =:= lists:keyfind(active, 1, Props).
%% @private
type_claimant(Props) ->
case lists:keyfind(claimant, 1, Props) of
{claimant, Claimant} -> Claimant;
false -> undefined
end.
%% The consensus subsystem must be enabled by exactly one node in a cluster
%% via a call to riak_ensemble_manager:enable(). We accomplished this by
%% having the claimant be that one node. Likewise, we require that the cluster
%% includes at least three nodes before we enable consensus. This prevents the
%% claimant in a 1-node cluster from enabling consensus before being joined to
%% another cluster.
maybe_enable_ensembles() ->
Desired = riak_core_sup:ensembles_enabled(),
Enabled = riak_ensemble_manager:enabled(),
case Enabled of
Desired ->
ok;
_ ->
{ok, Ring} = riak_core_ring_manager:get_raw_ring(),
IsReady = riak_core_ring:ring_ready(Ring),
IsClaimant = (riak_core_ring:claimant(Ring) == node()),
EnoughNodes = (length(riak_core_ring:ready_members(Ring)) >= 3),
case IsReady and IsClaimant and EnoughNodes of
true ->
enable_ensembles(Ring);
false ->
ok
end
end.
%% We need to avoid a race where the current claimant enables consensus right
%% before going offline and being replaced by a new claimant. It could be
%% argued that this corner case is not important since changing the claimant
%% requires the user manually marking the current claimant as down. But, it's
%% better to be safe and handle things correctly.
%%
%% To solve this issue, the claimant first marks itself as the "ensemble
%% singleton" in the ring metadata. Once the ring has converged, the claimant
%% see that it previously marked itself as the singleton and will proceed to
%% enable the consensus subsystem. If the claimant goes offline after marking
%% itself the singleton, but before enabling consensus, then future claimants
%% will be unable to enable consensus. Consensus will be enabled once the
%% previous claimant comes back online.
%%
enable_ensembles(Ring) ->
Node = node(),
case ensemble_singleton(Ring) of
undefined ->
become_ensemble_singleton();
Node ->
%% Ring update is required after enabling consensus to ensure
%% that ensembles are properly bootstrapped.
riak_ensemble_manager:enable(),
riak_core_ring_manager:force_update(),
?LOG_INFO("Activated consensus subsystem for cluster");
_ ->
ok
end.
ensemble_singleton(Ring) ->
case riak_core_ring:get_meta('$ensemble_singleton', Ring) of
undefined ->
undefined;
{ok, Node} ->
Members = riak_core_ring:all_members(Ring),
case lists:member(Node, Members) of
true ->
Node;
false ->
undefined
end
end.
become_ensemble_singleton() ->
_ = riak_core_ring_manager:ring_trans(fun become_ensemble_singleton_trans/2,
undefined),
ok.
become_ensemble_singleton_trans(Ring, _) ->
IsClaimant = (riak_core_ring:claimant(Ring) == node()),
NoSingleton = (ensemble_singleton(Ring) =:= undefined),
case IsClaimant and NoSingleton of
true ->
Ring2 = riak_core_ring:update_meta('$ensemble_singleton', node(), Ring),
{new_ring, Ring2};
false ->
ignore
end.
maybe_bootstrap_root_ensemble(Ring) ->
IsEnabled = riak_ensemble_manager:enabled(),
IsClaimant = (riak_core_ring:claimant(Ring) == node()),
IsReady = riak_core_ring:ring_ready(Ring),
case IsEnabled and IsClaimant and IsReady of
true ->
bootstrap_root_ensemble(Ring);
false ->
ok
end.
bootstrap_root_ensemble(Ring) ->
bootstrap_members(Ring),
ok.
bootstrap_members(Ring) ->
Name = riak_core_ring:cluster_name(Ring),
Members = riak_core_ring:ready_members(Ring),
RootMembers = riak_ensemble_manager:get_members(root),
Known = riak_ensemble_manager:cluster(),
Need = Members -- Known,
L = [riak_core_util:proxy_spawn(
fun() -> riak_ensemble_manager:join(node(), Member) end
) || Member <- Need, Member =/= node()],
_ = maybe_reset_ring_id(L),
RootNodes = [Node || {_, Node} <- RootMembers],
RootAdd = Members -- RootNodes,
RootDel = RootNodes -- Members,
Res = [riak_core_util:proxy_spawn(
fun() -> riak_ensemble_manager:remove(node(), N) end
) || N <- RootDel, N =/= node()],
_ = maybe_reset_ring_id(Res),
Changes =
[{add, {Name, Node}} || Node <- RootAdd] ++
[{del, {Name, Node}} || Node <- RootDel],
case Changes of
[] ->
ok;
_ ->
Self = self(),
spawn_link(fun() ->
async_bootstrap_members(Self, Changes)
end),
ok
end.
async_bootstrap_members(Claimant, Changes) ->
RootLeader = riak_ensemble_manager:rleader_pid(),
case riak_ensemble_peer:update_members(RootLeader, Changes, 10000) of
ok ->
ok;
_ ->
reset_ring_id(Claimant),
ok
end.
maybe_reset_ring_id(Results) ->
Failed = [R || R <- Results, R =/= ok],
(Failed =:= []) orelse reset_ring_id(self()).
%% Reset last_ring_id, ensuring future tick re-examines the ring even if the
%% ring has not changed.
reset_ring_id(Pid) ->
Pid ! reset_ring_id.
%% =========================================================================
%% Claimant rebalance/reassign logic
%% =========================================================================
%% @private
compute_all_next_rings(Changes, Seed, Ring) ->
compute_all_next_rings(Changes, Seed, Ring, []).
%% @private
compute_all_next_rings(Changes, Seed, Ring, Acc) ->
case compute_next_ring(Changes, Seed, Ring) of
{error, invalid_resize_claim}=Err ->
Err;