-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathrabbit_khepri.erl
More file actions
2197 lines (1970 loc) · 80.3 KB
/
rabbit_khepri.erl
File metadata and controls
2197 lines (1970 loc) · 80.3 KB
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
%% This Source Code Form is subject to the terms of the Mozilla Public
%% License, v. 2.0. If a copy of the MPL was not distributed with this
%% file, You can obtain one at https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2023-2025 Broadcom. All Rights Reserved. The term “Broadcom”
%% refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
%% @doc Khepri database uses wrapper.
%%
%% This module has three purposes:
%%
%% <ol>
%% <li>It provides a wrapper API on top of the regular Khepri API. The main
%% goal of this wrapper is to make sure the correct store identifier is being
%% used.</li>
%% <li>It is responsible for managing the Khepri database and clustering.</li>
%% <li>It provides functions to help with the transition from Mnesia to
%% Khepri.</li>
%% </ol>
%%
%% == Khepri API wrapper ==
%%
%% Most Khepri regular functions are wrapped by this module, but not all of
%% them. The reason is that the missing functions were not used so far. Feel
%% free to add another wrapper when the need arises.
%%
%% See <a href="https://rabbitmq.github.io/khepri/">Khepri's documentation</a>
%% to learn how to use its API.
%%
%%
%% == Transition from Mnesia to Khepri ==
%%
%% Until Mnesia code is removed, RabbitMQ should support both databases and
%% allow to migrate data from Mnesia to Khepri at runtime. The `khepri_db'
%% feature flag, its associated callback functions and the
%% `khepri_mnesia_migration' application take care of the one-time migration.
%%
%% To make database reads and writes work before, during and after the
%% migration, one can use the following functions:
%% <ul>
%% <li>{@link is_enabled/0}, {@link is_enabled/1}</li>
%% <li>{@link get_feature_state/0}, {@link get_feature_state/1}</li>
%% <li>{@link handle_fallback/1}</li>
%% </ul>
%%
%% {@link is_enabled/0} and {@link is_enabled/1} query the state of the
%% `khepri_db' feature flag state and return `true' if Khepri is the active
%% database or `false' if Mnesia is the active one. Furthermore, it will block
%% during the migration.
%%
%% {@link get_feature_state/0} and {@link get_feature_state/1} query the same
%% feature flag state. However, they do not block during the migration and
%% return `enabled' if Khepri is active, `disabled' if Mnesia is active, or
%% `state_changing' if RabbitMQ is between these two states.
%%
%% Finally {@link handle_fallback/1}, is a helper that takes two anonymous
%% functions: one for Mnesia and one for Khepri. If Khepri is already enabled,
%% its associated anonymous function is executed. Otherwise, the Mnesia one is
%% executed. If the migration runs concurrently, whether it started before or
%% during the execution of the Mnesia-specific anonymous function, {@link
%% handle_fallback/1} will watch for "no exists" table exceptions from Mnesia
%% and will retry the Mnesia function or run the Khepri function accordingly.
%% The Mnesia function must be idempotent because it can be executed multiple
%% times.
%%
%% Which function to use then?
%%
%% If you want to read from or write to one or more Mnesia tables or the
%% Khepri store, you should use {@link handle_fallback/1}:
%% <pre>
%% rabbit_khepri:handle_fallback(
%% #{mnesia => fun() -> do_something_with_mnesia_tables() end,
%% khepri => fun() -> do_something_with_khepri_store() end).
%% </pre>
%%
%% However, if you call into Mnesia but that doesn't involve reading or
%% writing to tables (e.g. querying the cluster status), you need to use
%% {@link is_enabled/0} or {@link get_feature_state/0}, depending on whether
%% you want to block or not. Most of the time, you want the call to block to
%% not have to deal with the intermediate state. For example:
%% <pre>
%% case rabbit_khepri:is_enabled() of
%% true -> do_something_with_khepri();
%% false -> do_something_with_mnesia()
%% end.
%% </pre>
-module(rabbit_khepri).
-feature(maybe_expr, enable).
-include_lib("kernel/include/logger.hrl").
-include_lib("stdlib/include/assert.hrl").
-include_lib("khepri/include/khepri.hrl").
-include_lib("rabbit_common/include/logging.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
-include("include/rabbit_khepri.hrl").
%% Initialisation.
-export([setup/0,
setup/1,
init/1,
reset/0,
dir/0,
get_ra_cluster_name/0,
get_store_id/0,
root_path/0,
info/0]).
%% Clustering.
-export([can_join_cluster/1,
add_member/2,
do_join/1, %% Internal RPC from this module.
remove_member/1,
members/0,
locally_known_members/0,
nodes/0,
locally_known_nodes/0,
check_cluster_consistency/0,
node_info/0, %% Internal RPC from this module.
cluster_status_from_khepri/0,
transfer_leadership/1]).
%% CLI command support.
-export([force_shrink_member_to_current_member/0,
status/0,
cli_cluster_status/0]).
%% "Proxy" functions to Khepri query/update API.
-export([is_empty/0,
get/1, get/2,
adv_get/1, adv_get/2,
get_many/1, get_many/2,
adv_get_many/1, adv_get_many/2,
exists/1, exists/2,
count/1, count/2,
fold/3, fold/4,
foreach/2, foreach/3,
map/2, map/3,
filter/2, filter/3,
put/2, put/3,
adv_put/2, adv_put/3,
create/2, create/3,
adv_create/2, adv_create/3,
update/2, update/3,
adv_update/2, adv_update/3,
delete/1, delete/2,
adv_delete/1, adv_delete/2,
clear_payload/1, clear_payload/2,
transaction/1, transaction/2, transaction/3,
fence/1,
handle_async_ret/1,
delete_or_fail/1]).
%% Used during migration to join the standalone Khepri nodes and form the
%% equivalent cluster
-export([khepri_db_migration_enable/1,
khepri_db_migration_post_enable/1,
enable_feature_flag/1,
is_enabled/0, is_enabled/1,
get_feature_state/0, get_feature_state/1,
handle_fallback/1]).
%% Called remotely to handle unregistration of old projections.
-export([supports_rabbit_khepri_topic_trie_v2/0,
supports_rabbit_khepri_topic_trie_version/0]).
-ifdef(TEST).
-export([register_projections/0,
force_metadata_store/1,
clear_forced_metadata_store/0]).
-endif.
-type timeout_error() :: khepri:error(timeout).
%% Commands like 'put'/'delete' etc. might time out in Khepri. It might take
%% the leader longer to apply the command and reply to the caller than the
%% configured timeout. This error is easy to reproduce - a cluster which is
%% only running a minority of nodes will consistently return `{error, timeout}`
%% for commands until the cluster majority can be re-established. Commands
%% returning `{error, timeout}` are a likely (but not certain) indicator that
%% the node which submitted the command is running in a minority.
-export_type([timeout_error/0]).
-compile({no_auto_import, [get/1, get/2, nodes/0]}).
-define(RA_SYSTEM, coordination).
-define(RA_CLUSTER_NAME, rabbitmq_metadata).
-define(RA_FRIENDLY_NAME, "RabbitMQ metadata store").
-define(STORE_ID, ?RA_CLUSTER_NAME).
-define(MIGRATION_ID, <<"rabbitmq_metadata">>).
%% By default we should try to reply from the cluster member that makes a
%% request to change the store. Projections are immediately consistent on the
%% node that issues the reply effect and eventually consistent everywhere else.
%% There isn't a performance penalty for replying from the local node and if
%% the local node isn't a part of the cluster, the reply will come from the
%% leader instead.
-define(DEFAULT_COMMAND_OPTIONS, #{reply_from => local}).
%% Mnesia tables to migrate and cleanup.
%%
%% This table order is important. For instance, user permissions depend on
%% both vhosts and users to exist in the metadata store.
%%
%% Channel and connection tracking are core features with difference: tables
%% cannot be predeclared as they include the node name
-rabbit_mnesia_tables_to_khepri_db(
[
{rabbit_vhost, rabbit_db_vhost_m2k_converter},
{rabbit_user, rabbit_db_user_m2k_converter},
{rabbit_user_permission, rabbit_db_user_m2k_converter},
{rabbit_topic_permission, rabbit_db_user_m2k_converter},
{rabbit_runtime_parameters, rabbit_db_rtparams_m2k_converter},
{rabbit_queue, rabbit_db_queue_m2k_converter},
{rabbit_exchange, rabbit_db_exchange_m2k_converter},
{rabbit_exchange_serial, rabbit_db_exchange_m2k_converter},
{rabbit_route, rabbit_db_binding_m2k_converter},
{rabbit_node_maintenance_states, rabbit_db_maintenance_m2k_converter},
{mirrored_sup_childspec, rabbit_db_msup_m2k_converter},
rabbit_durable_queue,
rabbit_durable_exchange,
rabbit_durable_route,
rabbit_semi_durable_route,
rabbit_reverse_route,
rabbit_index_route
]).
%% -------------------------------------------------------------------
%% Khepri integration initialisation.
%% -------------------------------------------------------------------
-spec setup() -> ok | no_return().
%% @doc Starts the local Khepri store.
%%
%% @see setup/1.
setup() ->
setup(rabbit_prelaunch:get_context()).
-spec setup(Context) -> ok | no_return() when
Context :: map().
%% @doc Starts the local Khepri store.
%%
%% Before starting the Khepri store, it ensures that the underlying Ra system
%% we want to use is also running.
%%
%% This function is idempotent whether the Khepri store is started for the
%% first time or it is restarted.
%%
%% This function blocks until a leader is elected.
%%
%% The Khepri application must be running.
%%
%% If it fails to start the Khepri store or if it reaches a timeout waiting for
%% a leader, this function exits.
setup(_Context) ->
?LOG_DEBUG("Starting Khepri-based " ?RA_FRIENDLY_NAME),
ok = ensure_ra_system_started(),
Timeout = application:get_env(rabbit, khepri_default_timeout, 30000),
ok = application:set_env(
[{khepri, [{default_timeout, Timeout},
{default_store_id, ?STORE_ID},
{default_ra_system, ?RA_SYSTEM}]}],
[{persistent, true}]),
RaServerConfig = #{cluster_name => ?RA_CLUSTER_NAME,
metrics_labels => #{ra_system => ?RA_SYSTEM,
module => ?MODULE},
friendly_name => ?RA_FRIENDLY_NAME},
case khepri:start(?RA_SYSTEM, RaServerConfig) of
{ok, ?STORE_ID} ->
RetryTimeout = retry_timeout(),
case khepri_cluster:wait_for_leader(?STORE_ID, RetryTimeout) of
ok ->
?LOG_DEBUG(
"Khepri-based " ?RA_FRIENDLY_NAME " ready",
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
ok;
{error, timeout} ->
exit(timeout_waiting_for_leader);
{error, _} = Error ->
exit(Error)
end;
{error, _} = Error ->
exit(Error)
end.
ensure_ra_system_started() ->
{ok, _} = application:ensure_all_started(khepri),
ok = rabbit_ra_systems:ensure_ra_system_started(?RA_SYSTEM).
retry_timeout() ->
case application:get_env(rabbit, khepri_leader_wait_retry_timeout) of
{ok, T} when is_integer(T) andalso T >= 0 -> T;
undefined -> 300_000
end.
-spec init(IsVirgin) -> Ret when
IsVirgin :: boolean(),
Ret :: ok | timeout_error().
%% @doc Ensures the store has caught up with the cluster.
%%
%% In addition to making sure the local Khepri store is on the same page as the
%% leader, it initialises the Khepri projections if this node is virgin.
%%
%% Finally, it requests the deletion of transient queues on this node.
init(IsVirgin) ->
case members() of
[] ->
timer:sleep(1000),
init(IsVirgin);
Members ->
?LOG_NOTICE(
"Found the following metadata store members: ~p", [Members],
#{domain => ?RMQLOG_DOMAIN_DB}),
maybe
ok ?= await_replication(),
?LOG_DEBUG(
"local Khepri-based " ?RA_FRIENDLY_NAME " member is caught "
"up to the Raft cluster leader", [],
#{domain => ?RMQLOG_DOMAIN_DB}),
ok ?= register_projections(),
%% Delete transient queues on init.
%% Note that we also do this in the
%% `rabbit_amqqueue:on_node_down/1' callback. We must try this
%% deletion during init because the cluster may have been in a
%% minority when this node went down. We wait for a majority
%% while registering projections above though so this deletion
%% is likely to succeed.
rabbit_amqqueue:delete_transient_queues_on_node(node())
end
end.
await_replication() ->
Timeout = retry_timeout(),
?LOG_DEBUG(
"Khepri-based " ?RA_FRIENDLY_NAME " waiting to catch up on replication "
"to the Raft cluster leader. Waiting for ~tb ms",
[Timeout],
#{domain => ?RMQLOG_DOMAIN_DB}),
fence(Timeout).
-spec reset() -> ok | no_return().
%% @doc Reset and stops the local Khepri store.
%%
%% This function first ensures that the local Khepri store is running.
%%
%% Then it resets the store. This includes removing it from its cluster if
%% any, and deleting all tree nodes.
%%
%% Finally, it stops the store and deteles files on disk.
%%
%% The Khepri application is left running.
%%
%% RabbitMQ must be stopped on this Erlang node. This functions throws an
%% exception if it is called while RabbitMQ is still running.
%%
%% @private
reset() ->
case rabbit:is_running() of
false ->
%% Rabbit should be stopped, but Khepri needs to be running.
%% Restart it.
ok = setup(),
ok = khepri_cluster:reset(?RA_CLUSTER_NAME),
ok = khepri:stop(?RA_CLUSTER_NAME),
_ = file:delete(rabbit_guid:filename()),
ok;
true ->
throw({error, rabbitmq_unexpectedly_running})
end.
-spec dir() -> Dir when
Dir :: file:filename_all().
%% @doc Returns the Khepri store directory.
%%
%% This corresponds to the underlying Ra system's directory.
dir() ->
DataDir = rabbit_mnesia:dir(),
StoreDir = filename:join(DataDir, atom_to_list(?STORE_ID)),
StoreDir.
-spec get_ra_cluster_name() -> RaClusterName when
RaClusterName :: ra:cluster_name().
%% @doc Returns the Ra cluster name.
get_ra_cluster_name() ->
?RA_CLUSTER_NAME.
-spec get_store_id() -> StoreId when
StoreId :: khepri:store_id().
%% @doc Returns the Khepri store identifier.
get_store_id() ->
?STORE_ID.
-spec root_path() -> RootPath when
RootPath :: khepri_path:path().
%% @doc Returns the path where RabbitMQ stores every metadata.
%%
%% This path must be prepended to all paths used by RabbitMQ subsystems.
root_path() ->
?RABBITMQ_KHEPRI_ROOT_PATH.
info() ->
ok = setup(),
khepri:info(?STORE_ID).
%% -------------------------------------------------------------------
%% Clustering.
%% -------------------------------------------------------------------
-spec can_join_cluster(DiscoveryNode) -> Ret when
DiscoveryNode :: node(),
Ret :: {ok, ClusterNodes} | {error, any()},
ClusterNodes :: [node()].
%% @doc Indicates if this node can join `DiscoveryNode' cluster.
%%
%% At the level of Khepri, it is always possible to join a remote cluster for
%% now. Therefore this function only queries the list of members in
%% `DiscoveryNode' cluster and returns it.
%%
%% @returns an `ok' tuple with the list of members in `DiscoveryNode' cluster,
%% or an error tuple.
%%
%% @private
can_join_cluster(DiscoveryNode) when is_atom(DiscoveryNode) ->
ThisNode = node(),
try
ClusterNodes0 = erpc:call(
DiscoveryNode,
?MODULE, locally_known_nodes, []),
ClusterNodes1 = ClusterNodes0 -- [ThisNode],
{ok, ClusterNodes1}
catch
_:Reason ->
{error, Reason}
end.
-spec add_member(JoiningNode, JoinedNode | JoinedCluster) -> Ret when
JoiningNode :: node(),
JoinedNode :: node(),
JoinedCluster :: [node()],
Ret :: ok | {error, any()}.
%% @doc Adds `JoiningNode' to `JoinedNode''s cluster.
%%
%% If a list of nodes is passed as `JoinedCluster', this function will pick
%% this node if it is part of the list and the Khepri store is running, or the
%% first node in the list that runs the Khepri store.
%%
%% The actual join code runs on the node that wants to join a cluster.
%% Therefore, if `JoiningNode' is this node, the code runs locally. Otherwise,
%% this function does an RPC call to execute the remote function.
%%
%% @private
add_member(JoiningNode, JoinedNode)
when JoiningNode =:= node() andalso is_atom(JoinedNode) ->
Ret = do_join(JoinedNode),
post_add_member(JoiningNode, JoinedNode, Ret);
add_member(JoiningNode, JoinedNode) when is_atom(JoinedNode) ->
Ret = rabbit_misc:rpc_call(
JoiningNode, ?MODULE, do_join, [JoinedNode]),
post_add_member(JoiningNode, JoinedNode, Ret);
add_member(JoiningNode, [_ | _] = Cluster) ->
case pick_node_in_cluster(Cluster) of
{ok, JoinedNode} ->
?LOG_INFO(
"Khepri clustering: Attempt to add node ~p to cluster ~0p "
"through node ~p",
[JoiningNode, Cluster, JoinedNode],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
%% Recurse with a single node taken in the `Cluster' list.
add_member(JoiningNode, JoinedNode);
{error, _} = Error ->
Error
end.
pick_node_in_cluster([_ | _] = Cluster) ->
RunningNodes = lists:filter(
fun(Node) ->
try
erpc:call(
Node,
khepri_cluster, is_store_running,
[?STORE_ID])
catch
_:_ ->
false
end
end, Cluster),
case RunningNodes of
[_ | _] ->
ThisNode = node(),
SelectedNode = case lists:member(ThisNode, RunningNodes) of
true -> ThisNode;
false -> hd(RunningNodes)
end,
{ok, SelectedNode};
[] ->
{error, {no_nodes_to_cluster_with, Cluster}}
end.
-spec do_join(RemoteNode) -> Ret when
RemoteNode :: node(),
Ret :: ok | {error, any()}.
%% @doc Adds this node to `RemoteNode''s cluster.
%%
%% Before adding this node to the remote node's cluster, this function call
%% {@link setup/0} to ensure the Khepri store is running.
%%
%% It also pings the remote node to make sure it is reachable.
%%
%% If RabbitMQ is still running on the Erlang node, it will put it in
%% maintenance before proceeding. It will resume RabbitMQ after the join (or if
%% the join fails).
%%
%% @private
do_join(RemoteNode) when RemoteNode =/= node() ->
ThisNode = node(),
?LOG_DEBUG(
"Khepri clustering: Trying to add this node (~p) to cluster \"~s\" "
"through node ~p",
[ThisNode, ?RA_CLUSTER_NAME, RemoteNode],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
%% Ensure the local Khepri store is running before we can reset it. It
%% could be stopped if RabbitMQ is not running for instance.
ok = setup(),
%% Ensure the remote node is reachable before we add it.
case net_adm:ping(RemoteNode) of
pong ->
%% We verify the cluster membership before adding `ThisNode' to
%% `RemoteNode''s cluster. We do it mostly to keep the same
%% behavior as what we do with Mnesia. Otherwise, the interest is
%% limited given the check and the actual join are not atomic.
?LOG_DEBUG(
"Adding this node (~p) to Khepri cluster \"~s\" through "
"node ~p",
[ThisNode, ?RA_CLUSTER_NAME, RemoteNode],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
%% If the remote node to add is running RabbitMQ, we need to put it
%% in maintenance mode at least. We remember that state to revive
%% the node only if it was fully running before this code.
IsRunning = rabbit:is_running(ThisNode),
AlreadyBeingDrained =
rabbit_maintenance:is_being_drained_consistent_read(ThisNode),
NeedToRevive = IsRunning andalso not AlreadyBeingDrained,
maybe_drain_node(IsRunning),
%% Joining a cluster includes a reset of the local Khepri store.
Ret = khepri_cluster:join(?RA_CLUSTER_NAME, RemoteNode),
%% Revive the remote node if it was running and not under
%% maintenance before we changed the cluster membership.
maybe_revive_node(NeedToRevive),
Ret;
pang ->
{error, {node_unreachable, RemoteNode}}
end.
maybe_drain_node(true) ->
ok = rabbit_maintenance:drain();
maybe_drain_node(false) ->
ok.
maybe_revive_node(true) ->
ok = rabbit_maintenance:revive();
maybe_revive_node(false) ->
ok.
post_add_member(JoiningNode, JoinedNode, ok) ->
?LOG_INFO(
"Khepri clustering: Node ~p successfully added to cluster \"~s\" "
"through node ~p",
[JoiningNode, ?RA_CLUSTER_NAME, JoinedNode],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
ok;
post_add_member(JoiningNode, JoinedNode, Error) ->
?LOG_INFO(
"Khepri clustering: Failed to add node ~p to cluster \"~s\" "
"through ~p: ~p",
[JoiningNode, ?RA_CLUSTER_NAME, JoinedNode, Error],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
Error.
-spec remove_member(NodeToRemove) -> ok when
NodeToRemove :: node().
%% @doc Removes `NodeToRemove' from its cluster.
%%
%% This function runs on the node calling it.
%%
%% If `NodeToRemove' is reachable, this function calls the regular {@link
%% khepri_cluster:reset/1} on `NodeToRemove'. If it is unreachable, this
%% function call Ra on this node to remove the remote member.
%%
%% @private
remove_member(Node) ->
retry_khepri_op(fun() -> do_remove_member(Node) end, 60).
-spec do_remove_member(NodeToRemove) -> Ret when
NodeToRemove :: node(),
Ret :: ok | {error, any()}.
%% @private
do_remove_member(NodeToRemove) when NodeToRemove =/= node() ->
?LOG_DEBUG(
"Trying to remove node ~s from Khepri cluster \"~s\" on node ~s",
[NodeToRemove, ?RA_CLUSTER_NAME, node()],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
%% Check if the node is part of the cluster. We query the local Ra server
%% only, in case the cluster can't elect a leader right now.
CurrentNodes = locally_known_nodes(),
case lists:member(NodeToRemove, CurrentNodes) of
true ->
%% Ensure the remote node is reachable before we remove it.
case net_adm:ping(NodeToRemove) of
pong ->
remove_reachable_member(NodeToRemove);
pang ->
remove_down_member(NodeToRemove)
end;
false ->
?LOG_INFO(
"Asked to remove node ~s from Khepri cluster \"~s\" but not "
"member of it: ~p",
[NodeToRemove, ?RA_CLUSTER_NAME, lists:sort(CurrentNodes)],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
rabbit_mnesia:e(not_a_cluster_node)
end.
remove_reachable_member(NodeToRemove) ->
?LOG_DEBUG(
"Removing remote node ~s from Khepri cluster \"~s\"",
[NodeToRemove, ?RA_CLUSTER_NAME],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
%% We need the Khepri store to run on the node to remove, to be
%% able to reset it.
ok = rabbit_misc:rpc_call(
NodeToRemove, ?MODULE, setup, []),
Ret = rabbit_misc:rpc_call(
NodeToRemove, khepri_cluster, reset, [?RA_CLUSTER_NAME]),
case Ret of
ok ->
rabbit_amqqueue:forget_all(NodeToRemove),
?LOG_DEBUG(
"Node ~s removed from Khepri cluster \"~s\"",
[NodeToRemove, ?RA_CLUSTER_NAME],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
ok;
{error, _} = Error ->
?LOG_ERROR(
"Failed to remove remote node ~s from Khepri "
"cluster \"~s\": ~p",
[NodeToRemove, ?RA_CLUSTER_NAME, Error],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
Error
end.
remove_down_member(NodeToRemove) ->
ServerRef = khepri_cluster:node_to_member(?STORE_ID, node()),
ServerId = khepri_cluster:node_to_member(?STORE_ID, NodeToRemove),
Timeout = khepri_app:get_default_timeout(),
Ret = ra:remove_member(ServerRef, ServerId, Timeout),
case Ret of
{ok, _, _} ->
rabbit_amqqueue:forget_all(NodeToRemove),
?LOG_DEBUG(
"Node ~s removed from Khepri cluster \"~s\"",
[NodeToRemove, ?RA_CLUSTER_NAME],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
ok;
{error, Reason} = Error ->
?LOG_ERROR(
"Failed to remove remote down node ~s from Khepri "
"cluster \"~s\": ~p",
[NodeToRemove, ?RA_CLUSTER_NAME, Reason],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
Error;
{timeout, _LeaderId} ->
?LOG_ERROR(
"Failed to remove remote down node ~s from Khepri "
"cluster \"~s\" due to timeout",
[NodeToRemove, ?RA_CLUSTER_NAME],
#{domain => ?RMQLOG_DOMAIN_GLOBAL}),
{error, timeout}
end.
retry_khepri_op(Fun, 0) ->
Fun();
retry_khepri_op(Fun, N) ->
case Fun() of
{error, {no_more_servers_to_try, Reasons}} = Err ->
case lists:member({error,cluster_change_not_permitted}, Reasons) of
true ->
timer:sleep(1000),
retry_khepri_op(Fun, N - 1);
false ->
Err
end;
{error, cluster_change_not_permitted} ->
timer:sleep(1000),
retry_khepri_op(Fun, N - 1);
Any ->
Any
end.
-spec members() -> Members when
Members :: [ra:server_id()].
%% @doc Returns the list of Ra server identifiers that are part of the
%% cluster.
%%
%% The membership is as it is known to the Ra leader in the cluster.
%%
%% The returned list is empty if there was an error.
members() ->
case khepri_cluster:members(?RA_CLUSTER_NAME) of
{ok, Members} -> Members;
{error, _Reason} -> []
end.
-spec locally_known_members() -> Members when
Members :: [ra:server_id()].
%% @doc Returns the list of Ra server identifiers that are part of the
%% cluster.
%%
%% The membership is as it is known to the local Ra server and may be
%% inconsistent compared to the "official" membership as seen by the Ra
%% leader.
%%
%% The returned list is empty if there was an error.
locally_known_members() ->
case khepri_cluster:members(?RA_CLUSTER_NAME, #{favor => low_latency}) of
{ok, Members} -> Members;
{error, _Reason} -> []
end.
-spec nodes() -> Nodes when
Nodes :: [node()].
%% @doc Returns the list of Erlang nodes that are part of the cluster.
%%
%% The membership is as it is known to the Ra leader in the cluster.
%%
%% The returned list is empty if there was an error.
nodes() ->
case khepri_cluster:nodes(?RA_CLUSTER_NAME) of
{ok, Nodes} -> Nodes;
{error, _Reason} -> []
end.
-spec locally_known_nodes() -> Nodes when
Nodes :: [node()].
%% @doc Returns the list of Erlang node that are part of the cluster.
%%
%% The membership is as it is known to the local Ra server and may be
%% inconsistent compared to the "official" membership as seen by the Ra
%% leader.
%%
%% The returned list is empty if there was an error.
locally_known_nodes() ->
case khepri_cluster:nodes(?RA_CLUSTER_NAME, #{favor => low_latency}) of
{ok, Nodes} -> Nodes;
{error, _Reason} -> []
end.
-spec check_cluster_consistency() -> Ret when
Ret :: ok | {error, any()}.
%% @doc Performs various checks to validate that this node is healthy at the
%% metadata store level.
%%
%% @private
check_cluster_consistency() ->
%% We want to find 0 or 1 consistent nodes.
ReachableNodes = rabbit_nodes:list_reachable(),
case lists:foldl(
fun (Node, {error, _}) -> check_cluster_consistency(Node, true);
(_Node, {ok, Status}) -> {ok, Status}
end, {error, not_found}, nodes_excl_me(ReachableNodes))
of
{ok, {RemoteAllNodes, _Running}} ->
case ordsets:is_subset(ordsets:from_list(ReachableNodes),
ordsets:from_list(RemoteAllNodes)) of
true ->
ok;
false ->
%% We delete the schema here since we think we are
%% clustered with nodes that are no longer in the
%% cluster and there is no other way to remove
%% them from our schema. On the other hand, we are
%% sure that there is another online node that we
%% can use to sync the tables with. There is a
%% race here: if between this check and the
%% `init_db' invocation the cluster gets
%% disbanded, we're left with a node with no
%% mnesia data that will try to connect to offline
%% nodes.
%% TODO delete schema in khepri ???
ok
end;
{error, not_found} ->
ok;
{error, _} = E ->
E
end.
-spec check_cluster_consistency(Node, CheckNodesConsistency) -> Ret when
Node :: node(),
CheckNodesConsistency :: boolean(),
Ret :: {ok, Status} | {error, any()},
Status :: {All, Running},
All :: [node()],
Running :: [node()].
%% @private
check_cluster_consistency(Node, CheckNodesConsistency) ->
case (catch remote_node_info(Node)) of
{badrpc, _Reason} ->
{error, not_found};
{'EXIT', {badarg, _Reason}} ->
{error, not_found};
{_OTP, _Rabbit, {error, _Reason}} ->
{error, not_found};
{_OTP, _Rabbit, {ok, Status}} when CheckNodesConsistency ->
case rabbit_db_cluster:check_compatibility(Node) of
ok ->
case check_nodes_consistency(Node, Status) of
ok -> {ok, Status};
Error -> Error
end;
Error ->
Error
end;
{_OTP, _Rabbit, {ok, Status}} ->
{ok, Status}
end.
-spec remote_node_info(Node) -> Info when
Node :: node(),
Info :: {OtpVersion, RabbitMQVersion, ClusterStatus},
OtpVersion :: string(),
RabbitMQVersion :: string(),
ClusterStatus :: {ok, {All, Running}} | {error, any()},
All :: [node()],
Running :: [node()].
%% @private
remote_node_info(Node) ->
rpc:call(Node, ?MODULE, node_info, []).
-spec node_info() -> Info when
Info :: {OtpVersion, RabbitMQVersion, ClusterStatus},
OtpVersion :: string(),
RabbitMQVersion :: string(),
ClusterStatus :: {ok, {All, Running}} | {error, khepri_not_running},
All :: [node()],
Running :: [node()].
%% @private
node_info() ->
{rabbit_misc:otp_release(),
rabbit_misc:version(),
cluster_status_from_khepri()}.
check_nodes_consistency(Node, {RemoteAllNodes, _RemoteRunningNodes}) ->
case me_in_nodes(RemoteAllNodes) of
true ->
ok;
false ->
{error, {inconsistent_cluster,
format_inconsistent_cluster_message(node(), Node)}}
end.
format_inconsistent_cluster_message(Thinker, Dissident) ->
rabbit_misc:format("Khepri: node ~tp thinks it's clustered "
"with node ~tp, but ~tp disagrees",
[Thinker, Dissident, Dissident]).
nodes_excl_me(Nodes) -> Nodes -- [node()].
me_in_nodes(Nodes) -> lists:member(node(), Nodes).
-spec cluster_status_from_khepri() -> ClusterStatus when
ClusterStatus :: {ok, {All, Running}} | {error, khepri_not_running},
All :: [node()],
Running :: [node()].
%% @private
cluster_status_from_khepri() ->
try
_ = get_ra_key_metrics(node()),
All = locally_known_nodes(),
Running = lists:filter(
fun(N) ->
rabbit_nodes:is_running(N)
end, All),
{ok, {All, Running}}
catch
_:_ ->
{error, khepri_not_running}
end.
-spec transfer_leadership(Candidates) -> Ret when
Candidates :: [node()],
Ret :: {ok, Result} | {error, any()},
Result :: node() | undefined.
%% @private
transfer_leadership([]) ->
?LOG_WARNING(
"Skipping leadership transfer of metadata store: no candidate "
"(online, not under maintenance) nodes to transfer to!",
#{domain => ?RMQLOG_DOMAIN_DB}),
{error, no_candidates};
transfer_leadership(TransferCandidates) ->
case get_feature_state() of
enabled ->
do_transfer_leadership(TransferCandidates);
_ ->
?LOG_INFO(
"Skipping leadership transfer of metadata store: Khepri "
"is not enabled",
#{domain => ?RMQLOG_DOMAIN_DB}),
{error, khepri_not_enabled}
end.
do_transfer_leadership([]) ->
?LOG_WARNING(
"Khepri clustering: failed to transfer leadership, no more "
"candidates available",
#{domain => ?RMQLOG_DOMAIN_DB}),
{error, not_migrated};
do_transfer_leadership([Destination | TransferCandidates]) ->
?LOG_INFO(
"Khepri clustering: transferring leadership to node ~p",
[Destination],
#{domain => ?RMQLOG_DOMAIN_DB}),
case ra_leaderboard:lookup_leader(?STORE_ID) of
{Name, Node} = Id when Node == node() ->
Timeout = khepri_app:get_default_timeout(),
case ra:transfer_leadership(Id, {Name, Destination}) of
ok ->
case ra:members(Id, Timeout) of
{_, _, {_, NewNode}} ->
?LOG_INFO(
"Khepri clustering: successfully "
"transferred leadership to node ~p",
[Destination],
#{domain => ?RMQLOG_DOMAIN_DB}),
{ok, NewNode};
{timeout, _} ->
?LOG_WARNING(
"Khepri clustering: maybe failed to transfer "
"leadership to node ~p, members query has "
"timed out",
[Destination],
#{domain => ?RMQLOG_DOMAIN_DB}),
{error, not_migrated}
end;
already_leader ->
?LOG_INFO(
"Khepri clustering: successfully transferred "
"leadership to node ~p, already the leader",
[Destination],