-
Notifications
You must be signed in to change notification settings - Fork 155
/
leo_storage_mq.erl
968 lines (889 loc) · 38.6 KB
/
leo_storage_mq.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
%%====================================================================
%%
%% LeoFS Storage
%%
%% Copyright (c) 2012-2017 Rakuten, Inc.
%%
%% 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.
%%
%% -------------------------------------------------------------------
%% LeoFS Storage - MQ Client
%% @doc
%% @end
%%====================================================================
-module(leo_storage_mq).
-behaviour(leo_mq_behaviour).
-include("leo_storage.hrl").
-include_lib("leo_commons/include/leo_commons.hrl").
-include_lib("leo_logger/include/leo_logger.hrl").
-include_lib("leo_mq/include/leo_mq.hrl").
-include_lib("leo_object_storage/include/leo_object_storage.hrl").
-include_lib("leo_redundant_manager/include/leo_redundant_manager.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([start/1, start/2,
publish/2, publish/3, publish/4, publish/5, publish/6]).
-export([init/0, handle_call/1, handle_call/3]).
-define(SLASH, "/").
-define(MSG_PATH_PER_OBJECT, "1").
-define(MSG_PATH_SYNC_VNODE_ID, "2").
-define(MSG_PATH_REBALANCE, "3").
-define(MSG_PATH_ASYNC_DELETION, "4").
-define(MSG_PATH_RECOVERY_NODE, "5").
-define(MSG_PATH_SYNC_OBJ_WITH_DC, "6").
-define(MSG_PATH_COMP_META_WITH_DC, "7").
-define(MSG_PATH_DEL_DIR, "8").
%%--------------------------------------------------------------------
%% API
%%--------------------------------------------------------------------
%% @doc create queues and launch mq-servers.
-spec(start(RootPath) ->
ok | {error, any()} when RootPath::binary()).
start(RootPath) ->
start(leo_storage_sup, RootPath).
-spec(start(RefSup, RootPath) ->
ok | {error, any()} when RefSup::pid(),
RootPath::binary()).
start(RefSup, RootPath) ->
%% launch mq-sup under storage-sup
RefMqSup =
case whereis(leo_mq_sup) of
undefined ->
ChildSpec = {leo_mq_sup,
{leo_mq_sup, start_link, []},
permanent, 2000, supervisor, [leo_mq_sup]},
{ok, Pid} = supervisor:start_child(RefSup, ChildSpec),
Pid;
Pid ->
Pid
end,
%% launch queue-processes
RootPath_1 =
case (string:len(RootPath) == string:rstr(RootPath, ?SLASH)) of
true -> RootPath;
false -> RootPath ++ ?SLASH
end,
?TBL_REBALANCE_COUNTER = ets:new(?TBL_REBALANCE_COUNTER,
[named_table, public, {read_concurrency, true}]),
start_1([{?QUEUE_ID_PER_OBJECT, ?MSG_PATH_PER_OBJECT},
{?QUEUE_ID_SYNC_BY_VNODE_ID, ?MSG_PATH_SYNC_VNODE_ID},
{?QUEUE_ID_REBALANCE, ?MSG_PATH_REBALANCE},
{?QUEUE_ID_ASYNC_DELETION, ?MSG_PATH_ASYNC_DELETION},
{?QUEUE_ID_RECOVERY_NODE, ?MSG_PATH_RECOVERY_NODE},
{?QUEUE_ID_SYNC_OBJ_WITH_DC, ?MSG_PATH_SYNC_OBJ_WITH_DC},
{?QUEUE_ID_COMP_META_WITH_DC, ?MSG_PATH_COMP_META_WITH_DC},
{?QUEUE_ID_DEL_DIR, ?MSG_PATH_DEL_DIR}
], RefMqSup, RootPath_1).
%% @private
start_1([],_,_) ->
ok;
start_1([{Id, Path}|Rest], Sup, Root) ->
leo_mq_api:new(Sup, Id, [{?MQ_PROP_MOD, ?MODULE},
{?MQ_PROP_FUN, ?MQ_SUBSCRIBE_FUN},
{?MQ_PROP_ROOT_PATH, Root ++ Path},
{?MQ_PROP_DB_NAME, ?env_mq_backend_db()},
{?MQ_PROP_DB_PROCS, ?env_num_of_mq_procs()},
{?MQ_PROP_CNS_PROCS_PER_DB, 1},
{?MQ_PROP_BATCH_MSGS_MAX, ?env_mq_num_of_batch_process_max()},
{?MQ_PROP_BATCH_MSGS_REG, ?env_mq_num_of_batch_process_reg()},
{?MQ_PROP_INTERVAL_MAX, ?env_mq_interval_between_batch_procs_max()},
{?MQ_PROP_INTERVAL_REG, ?env_mq_interval_between_batch_procs_reg()}
]),
start_1(Rest, Sup, Root).
%% @doc Input a message into the queue.
-spec(publish(queue_id(), atom()|binary()) ->
ok | {error, any()}).
publish(?QUEUE_ID_RECOVERY_NODE = Id, Node) ->
KeyBin = term_to_binary(Node),
MsgBin = term_to_binary(
#recovery_node_message{id = leo_date:clock(),
node = Node,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MsgBin);
publish(?QUEUE_ID_DEL_DIR = Id, {bulk_insert, Dirs}) ->
[publish(Id, erlang:node(), D) || D <- Dirs],
ok;
publish(?QUEUE_ID_DEL_DIR = Id, Dir) ->
case leo_redundant_manager_api:get_members() of
{ok, RetL} ->
[publish(Id, N, Dir)
|| #member{node = N} <- RetL],
ok;
_ ->
timer:sleep(timer:seconds(5)),
publish(Id, Dir)
end;
publish(_,_) ->
{error, badarg}.
-spec(publish(queue_id(), any(), any()) ->
ok | {error, any()}).
publish(?QUEUE_ID_SYNC_BY_VNODE_ID = Id, VNodeId, Node) ->
KeyBin = term_to_binary({VNodeId, Node}),
MessageBin = term_to_binary(
#sync_unit_of_vnode_message{id = leo_date:clock(),
vnode_id = VNodeId,
node = Node,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(?QUEUE_ID_ASYNC_DELETION = Id, AddrId, Key) ->
KeyBin = term_to_binary({AddrId, Key}),
MessageBin = term_to_binary(
#async_deletion_message{id = leo_date:clock(),
addr_id = AddrId,
key = Key,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(?QUEUE_ID_SYNC_OBJ_WITH_DC, AddrId, Key) ->
publish(?QUEUE_ID_SYNC_OBJ_WITH_DC, undefined, AddrId, Key);
publish(?QUEUE_ID_COMP_META_WITH_DC = Id, ClusterId, AddrAndKeyList) ->
KeyBin = term_to_binary(ClusterId),
MessageBin = term_to_binary(
#comparison_metadata_with_dc{id = leo_date:clock(),
cluster_id = ClusterId,
list_of_addrid_and_key = AddrAndKeyList,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(?QUEUE_ID_DEL_DIR = Id, Node, Dir) ->
KeyBin = term_to_binary({Node, Dir}),
MsgBin = term_to_binary(
#delete_dir{id = leo_date:clock(),
dir = Dir,
node = Node,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MsgBin);
publish(_,_,_) ->
{error, badarg}.
-spec(publish(queue_id(), any(), any(), any()) ->
ok | {error, any()}).
publish(?QUEUE_ID_PER_OBJECT = Id, AddrId, Key, ErrorType) ->
KeyBin = term_to_binary({ErrorType, Key}),
MessageBin = term_to_binary(
#?MSG_INCONSISTENT_DATA{id = leo_date:clock(),
type = ErrorType,
addr_id = AddrId,
key = Key,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(?QUEUE_ID_SYNC_OBJ_WITH_DC = Id, ClusterId, AddrId, Key) ->
KeyBin = term_to_binary({ClusterId, AddrId, Key}),
MessageBin = term_to_binary(
#inconsistent_data_with_dc{id = leo_date:clock(),
cluster_id = ClusterId,
addr_id = AddrId,
key = Key,
del = 0,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(_,_,_,_) ->
{error, badarg}.
-spec(publish(queue_id(), any(), any(), any(), any()) ->
ok | {error, any()}).
publish(?QUEUE_ID_REBALANCE = Id, Node, VNodeId, AddrId, Key) ->
Hash = erlang:crc32(term_to_binary({Node, AddrId, Key})),
KeyBin = term_to_binary({Hash, Node, AddrId, Key}),
MessageBin = term_to_binary(
#rebalance_message{id = leo_date:clock(),
vnode_id = VNodeId,
addr_id = AddrId,
key = Key,
node = Node,
timestamp = leo_date:now()}),
Table = ?TBL_REBALANCE_COUNTER,
case ets_lookup(Table, VNodeId) of
{ok, 0} ->
ets:insert(Table, {VNodeId, 0});
_Other ->
void
end,
ok = increment_counter(Table, VNodeId),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(?QUEUE_ID_SYNC_OBJ_WITH_DC = Id, ClusterId, AddrId, Key, Del) ->
KeyBin = term_to_binary({ClusterId, AddrId, Key}),
MessageBin = term_to_binary(
#inconsistent_data_with_dc{id = leo_date:clock(),
cluster_id = ClusterId,
addr_id = AddrId,
key = Key,
del = Del,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(_,_,_,_,_) ->
{error, badarg}.
publish(?QUEUE_ID_PER_OBJECT = Id, AddrId, Key, SyncNode, IsForceSync, ErrorType) ->
KeyBin = term_to_binary({ErrorType, Key}),
MessageBin = term_to_binary(
#?MSG_INCONSISTENT_DATA{id = leo_date:clock(),
type = ErrorType,
addr_id = AddrId,
key = Key,
sync_node = SyncNode,
is_force_sync = IsForceSync,
timestamp = leo_date:now()}),
leo_mq_api:publish(Id, KeyBin, MessageBin);
publish(_,_,_,_,_,_) ->
{error, badarg}.
%% -------------------------------------------------------------------
%% Callbacks
%% -------------------------------------------------------------------
%% @doc Initializer
-spec(init() -> ok | {error, any()}).
init() ->
ok.
%% @doc Subscribe a message from the queue.
%% @private
-spec(handle_call({consume, any() | queue_id() , any() | binary()}) ->
ok | {error, any()}).
handle_call({consume, ?QUEUE_ID_PER_OBJECT, MessageBin}) ->
case catch binary_to_term(MessageBin) of
{'EXIT',_} ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_PER_OBJECT},
{cause, invalid_data_format}]),
ok;
Term ->
case ?transform_inconsistent_data_message(Term) of
{ok, #?MSG_INCONSISTENT_DATA{addr_id = AddrId,
key = Key,
%% type = ErrorType,
sync_node = SyncNode,
is_force_sync = true}} when SyncNode /= undefined ->
send_object_to_remote_node(SyncNode, AddrId, Key);
{ok, #?MSG_INCONSISTENT_DATA{addr_id = AddrId,
key = Key,
type = _ErrorType}} ->
case correct_redundancies(Key) of
ok ->
ok;
{error, Cause = not_found} ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_PER_OBJECT},
{addr_id, AddrId},
{key, Key}, {cause, Cause}]),
ok;
{error, Cause} ->
?debug("handle_call/1 - consume",
[{addr_id, AddrId},
{key, Key}, {cause, Cause}]),
{error, Cause}
end;
{error,_Error} ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_PER_OBJECT},
{cause, invalid_data_format}]),
ok
end
end;
handle_call({consume, ?QUEUE_ID_SYNC_BY_VNODE_ID, MessageBin}) ->
case catch binary_to_term(MessageBin) of
#sync_unit_of_vnode_message{vnode_id = ToVNodeId,
node = Node} ->
{ok, Res} = leo_redundant_manager_api:range_of_vnodes(ToVNodeId),
{ok, {CurRingHash, _PrevRingHash}} =
leo_redundant_manager_api:checksum(?CHECKSUM_RING),
ok = sync_vnodes(Node, CurRingHash, Res),
notify_rebalance_message_to_manager(ToVNodeId);
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_SYNC_BY_VNODE_ID},
{cause, invalid_data_format}]),
ok
end;
handle_call({consume, ?QUEUE_ID_REBALANCE, MessageBin}) ->
case catch binary_to_term(MessageBin) of
#rebalance_message{} = Msg ->
rebalance_1(Msg);
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_REBALANCE},
{cause, invalid_data_format}]),
ok
end;
handle_call({consume, ?QUEUE_ID_ASYNC_DELETION, MessageBin}) ->
case catch binary_to_term(MessageBin) of
#async_deletion_message{addr_id = AddrId,
key = Key} ->
case catch leo_storage_handler_object:delete(
#?OBJECT{addr_id = AddrId,
key = Key,
clock = leo_date:clock(),
timestamp = leo_date:now(),
del = ?DEL_TRUE
}, 0, false, leo_mq) of
ok ->
ok;
{_, Cause} ->
{error, Cause}
end;
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_ASYNC_DELETION},
{cause, invalid_data_format}]),
ok
end;
handle_call({consume, ?QUEUE_ID_RECOVERY_NODE, MessageBin}) ->
case catch binary_to_term(MessageBin) of
#recovery_node_message{node = Node} ->
recover_node(Node);
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_RECOVERY_NODE},
{cause, invalid_data_format}]),
ok
end;
handle_call({consume, ?QUEUE_ID_SYNC_OBJ_WITH_DC, MessageBin}) ->
case catch binary_to_term(MessageBin) of
#inconsistent_data_with_dc{} = Msg ->
fix_consistency_between_clusters(Msg);
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_SYNC_OBJ_WITH_DC},
{cause, invalid_data_format}]),
ok
end;
handle_call({consume, ?QUEUE_ID_COMP_META_WITH_DC, MessageBin}) ->
case catch binary_to_term(MessageBin) of
#comparison_metadata_with_dc{cluster_id = ClusterId,
list_of_addrid_and_key = AddrAndKeyList} ->
%% @doc - condition: if state of a remote-cluster is not 'running',
%% then this queue is removed
case leo_mdcr_tbl_cluster_stat:find_by_cluster_id(ClusterId) of
{ok, #?CLUSTER_STAT{state = ?STATE_RUNNING}} ->
%% re-compare metadatas
leo_storage_handle_sync:send_addrid_and_key_to_remote(
ClusterId, AddrAndKeyList);
_ ->
ok
end;
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_COMP_META_WITH_DC},
{cause, invalid_data_format}]),
ok
end;
handle_call({consume, ?QUEUE_ID_DEL_DIR, MessageBin}) ->
case catch binary_to_term(MessageBin) of
%% A destination node is NOT specified
#delete_dir{dir = ParentDir,
node = undefined} ->
publish(?QUEUE_ID_DEL_DIR, ParentDir);
%% A destination node is specified
#delete_dir{dir = ParentDir,
node = Node} ->
Ref = make_ref(),
case leo_storage_handler_object:delete_objects_under_dir(
[Node], Ref, [ParentDir]) of
{ok, Ref} ->
ok;
_Other ->
ok
end;
_ ->
?warn("handle_call/1 - consume",
[{qid, ?QUEUE_ID_DEL_DIR},
{cause, invalid_data_format}]),
ok
end;
handle_call(_) ->
ok.
handle_call(_,_,_) ->
ok.
%%--------------------------------------------------------------------
%% INNTERNAL FUNCTIONS-1
%%--------------------------------------------------------------------
%% @doc synchronize by vnode-id.
%% @private
-spec(recover_node(Node) ->
ok when Node::node()).
recover_node(Node) ->
Callback = recover_node_callback(Node),
_ = leo_object_storage_api:fetch_by_addr_id(0, Callback),
ok.
%% @private
-spec(recover_node_callback(Node) ->
any() when Node::node()).
recover_node_callback(Node) ->
fun(K, V, Acc) ->
Metadata_1 = binary_to_term(V),
Metadata_2 = leo_object_storage_transformer:transform_metadata(Metadata_1),
#?METADATA{addr_id = AddrId} = Metadata_2,
%% Retrieve redundant-nodes from the redundant-manager(RING),
%% then if the recovery-target-node and "this node"
%% are included in retrieved redundant-nodes, "the file" will be recovered
%% by the MQ.
case leo_redundant_manager_api:get_redundancies_by_addr_id(put, AddrId) of
{ok, #redundancies{nodes = Redundancies}} ->
RedundantNodes = [N || #redundant_node{node = N} <- Redundancies],
ok = recover_node_callback_1(AddrId, K, Node, RedundantNodes),
Acc;
_Other ->
Acc
end
end.
%% @private
recover_node_callback_1(_,_,_,[]) ->
ok;
recover_node_callback_1(AddrId, Key, Node, RedundantNodes) ->
case lists:member(Node, RedundantNodes) of
true ->
case lists:delete(Node, RedundantNodes) of
[] ->
ok;
RedundantNodes_1 ->
recover_node_callback_2(RedundantNodes_1, AddrId, Key, Node)
end;
false ->
ok
end.
%% @private
recover_node_callback_2([],_AddrId,_Key,_FixedNode) ->
ok;
recover_node_callback_2([SrcNode|Rest], AddrId, Key, FixedNode) ->
case leo_misc:node_existence(SrcNode, ?DEF_REQ_TIMEOUT) of
true when SrcNode == erlang:node() ->
?MODULE:publish(?QUEUE_ID_PER_OBJECT,
AddrId, Key, FixedNode, true,
?ERR_TYPE_RECOVER_DATA);
true ->
case leo_redundant_manager_api:get_member_by_node(SrcNode) of
{ok, #member{state = ?STATE_RUNNING}} ->
ok;
_ ->
recover_node_callback_2(Rest, AddrId, Key, FixedNode)
end;
false ->
recover_node_callback_2(Rest, AddrId, Key, FixedNode)
end.
%% @doc Send object to a remote-node
%% @private
send_object_to_remote_node(Node, AddrId, Key) ->
Ref = make_ref(),
case leo_storage_handler_object:get({Ref, Key}) of
{ok, Ref, Metadata, Bin} ->
case rpc:call(Node, leo_sync_local_cluster, store,
[Metadata, Bin], ?DEF_REQ_TIMEOUT) of
ok ->
ok;
{error, inconsistent_obj} ->
?MODULE:publish(?QUEUE_ID_PER_OBJECT,
AddrId, Key, ?ERR_TYPE_RECOVER_DATA);
_ ->
?MODULE:publish(?QUEUE_ID_PER_OBJECT, AddrId, Key,
Node, true, ?ERR_TYPE_RECOVER_DATA)
end;
{error, Ref, Cause} ->
{error, Cause};
_Other ->
{error, invalid_response}
end.
%% @doc synchronize by vnode-id.
%% @private
-spec(sync_vnodes(Node, RingHash, ListOfFromToAddrId) ->
ok when Node::node(),
RingHash::integer(),
FromAddrId::integer(),
ToAddrId::integer(),
ListOfFromToAddrId::[{FromAddrId, ToAddrId}]).
sync_vnodes(_, _, []) ->
ok;
sync_vnodes(Node, RingHash, [{FromAddrId, ToAddrId}|T]) ->
Callback = sync_vnodes_callback(Node, FromAddrId, ToAddrId),
catch leo_object_storage_api:fetch_by_addr_id(FromAddrId, Callback),
catch notify_message_to_manager(?env_manager_nodes(leo_storage), ToAddrId, erlang:node()),
sync_vnodes(Node, RingHash, T).
%% @private
-spec(sync_vnodes_callback(Node, FromAddrId, ToAddrId) ->
any() when Node::node(),
FromAddrId::integer(),
ToAddrId::integer()).
sync_vnodes_callback(Node, FromAddrId, ToAddrId)->
fun(_K, V, Acc) ->
%% Note: An object of copy is NOT equal current ring-hash.
%% Then a message in the rebalance-queue.
#?METADATA{addr_id = AddrId,
key = Key} = binary_to_term(V),
case (AddrId >= FromAddrId andalso
AddrId =< ToAddrId) of
true ->
case catch leo_redundant_manager_api:get_redundancies_by_key(Key) of
{'EXIT',_Cause} ->
Acc;
{ok, #redundancies{nodes = Redundancies}} ->
Nodes = [N || #redundant_node{node = N} <- Redundancies],
case lists:member(Node, Nodes) of
true ->
publish(?QUEUE_ID_REBALANCE, Node,
ToAddrId, AddrId, Key),
Acc;
false ->
Acc
end,
Acc;
_ ->
Acc
end;
false ->
Acc
end
end.
%% @doc Remove a node from redundancies
%% @private
-spec(delete_node_from_redundancies(Redundancies, Node, AccRedundancies) ->
{ok, AccRedundancies} when Redundancies::[#redundant_node{}],
Node::node(),
AccRedundancies::[#redundant_node{}]).
delete_node_from_redundancies([],_,Acc) ->
{ok, lists:reverse(Acc)};
delete_node_from_redundancies([#redundant_node{node = Node}|Rest], Node, Acc) ->
delete_node_from_redundancies(Rest, Node, Acc);
delete_node_from_redundancies([RedundantNode|Rest], Node, Acc) ->
delete_node_from_redundancies(Rest, Node, [RedundantNode|Acc]).
%% @doc Find a node from redundancies
%% @private
-spec(find_node_from_redundancies(Redundancies, Node) ->
Ret when Redundancies::[#redundant_node{}],
Node::node(),
Ret::boolean()).
find_node_from_redundancies([],_) ->
false;
find_node_from_redundancies([#redundant_node{node = Node}|_], Node) ->
true;
find_node_from_redundancies([_|Rest], Node) ->
find_node_from_redundancies(Rest, Node).
%% @doc Notify a message to manager node(s)
%% @private
-spec(notify_message_to_manager(ManagerNodes, VNodeId, Node) ->
ok | {error, Cause} when ManagerNodes::[node()],
VNodeId::integer(),
Node::node(),
Cause::any()).
notify_message_to_manager([],_VNodeId,_Node) ->
{error, 'fail_notification'};
notify_message_to_manager([Manager|T], VNodeId, Node) ->
Res = case rpc:call(list_to_atom(Manager), leo_manager_api, notify,
[synchronized, VNodeId, Node], ?DEF_REQ_TIMEOUT) of
ok ->
ok;
{_, Cause} ->
?warn("notify_message_to_manager/3",
[{vnode_id, VNodeId},
{node, Node}, {cause, Cause}]),
{error, Cause};
timeout = Cause ->
{error, Cause}
end,
case Res of
ok ->
ok;
_Error ->
notify_message_to_manager(T, VNodeId, Node)
end.
%% @doc correct_redundancies/1 - first.
%% @private
-spec(correct_redundancies(Key) ->
ok | {error, Cause} when Key::binary(),
Cause::any()).
correct_redundancies(Key) ->
case leo_redundant_manager_api:get_redundancies_by_key(Key) of
{ok, #redundancies{nodes = Redundancies,
id = AddrId}} ->
correct_redundancies_1(Key, AddrId, Redundancies, [], []);
{error, Cause} ->
?warn("correct_redundancies/1",
[{key, Key}, {cause, Cause}]),
{error, ?ERROR_COULD_NOT_GET_REDUNDANCY}
end.
%% @doc correct_redundancies_1/5 - next.
%% @private
-spec(correct_redundancies_1(binary(), integer(), list(), list(), list()) ->
ok | {error, any()}).
correct_redundancies_1(_Key,_AddrId, [], [], _ErrorNodes) ->
{error, not_found};
correct_redundancies_1(_Key,_AddrId, [], Metadatas, ErrorNodes) ->
correct_redundancies_2(Metadatas, ErrorNodes);
correct_redundancies_1(Key, AddrId, [#redundant_node{node = Node}|T], Metadatas, ErrorNodes) ->
%% NOTE:
%% If remote-node status is NOT 'running',
%% this function cannot operate 'rpc-call'.
case leo_redundant_manager_api:get_member_by_node(Node) of
{ok, #member{state = ?STATE_RUNNING}} ->
%% Retrieve a metadata from remote-node
%% invoke head with NO retry option
RPCKey = rpc:async_call(Node, leo_storage_handler_object,
head, [AddrId, Key, false]),
case rpc:nb_yield(RPCKey, ?DEF_REQ_TIMEOUT) of
{value, {ok, Metadata}} ->
correct_redundancies_1(Key, AddrId, T,
[{Node, Metadata}|Metadatas], ErrorNodes);
_Error ->
correct_redundancies_1(Key, AddrId, T,
Metadatas, [Node|ErrorNodes])
end;
{ok, #member{state = ?STATE_DETACHED}} ->
correct_redundancies_1(Key, AddrId, T, Metadatas, ErrorNodes);
_Other ->
correct_redundancies_1(Key, AddrId, T, Metadatas, [Node|ErrorNodes])
end.
%% @doc correct_redundancies_2/3
%% @private
-spec(correct_redundancies_2(ListOfMetadatas, ErrorNodes) ->
ok | {error, any()} when ListOfMetadatas::[#?METADATA{}],
ErrorNodes::[any()]).
correct_redundancies_2(ListOfMetadatas, ErrorNodes) ->
%% Retrieve latest metadata of an object to fix its inconsistency
H = case (erlang:length(ListOfMetadatas) == 1) of
true ->
erlang:hd(ListOfMetadatas);
false ->
MaxClock = lists:max([M#?METADATA.clock
|| {_,M} <- ListOfMetadatas]),
{_,RetL} = lists:foldl(
fun({_,#?METADATA{clock = Clock}} = M,
{MaxClock_1, Acc}) when Clock == MaxClock_1 ->
{MaxClock_1, [M|Acc]};
(_, {MaxClock_1, Acc}) ->
{MaxClock_1, Acc}
end, {MaxClock, []}, ListOfMetadatas),
erlang:hd(RetL)
end,
{_, Metadata} = H,
%% If 'metadata' contains 'num_of_replicas > 0',
%% it is adopted instead of the local 'number of replicas'
{_Dest, CorrectNodes, InconsistentNodes} =
lists:foldl(
fun({Node,_Metadata}, {{DestNode,_Metadata} = Dest, C, R}) when Node =:= DestNode ->
{Dest, [Node|C], R};
({Node, #?METADATA{clock = Clock}},
{{DestNode, #?METADATA{clock = DestClock}} = Dest, C, R}) when Node =/= DestNode,
Clock =:= DestClock ->
{Dest, [Node|C], R};
({Node, #?METADATA{clock = Clock}},
{{DestNode, #?METADATA{clock = DestClock}} = Dest, C, R}) when Node =/= DestNode,
Clock =/= DestClock ->
{Dest, C, [Node|R]}
end, {H, [], []}, ListOfMetadatas),
correct_redundancies_3(ErrorNodes ++ InconsistentNodes, CorrectNodes, Metadata).
%% @doc correct_redundancies_3/4 - last.
%% @private
-spec(correct_redundancies_3(list(), list(), #?METADATA{}) ->
ok | {error, any()}).
correct_redundancies_3([], _, _) ->
ok;
correct_redundancies_3(_, [], _) ->
{error, 'not_fix_inconsistency'};
correct_redundancies_3(InconsistentNodes, [Node|_] = NodeL, Metadata) ->
RPCKey = rpc:async_call(Node, leo_storage_api, synchronize,
[InconsistentNodes, Metadata]),
Ret = case rpc:nb_yield(RPCKey, ?DEF_REQ_TIMEOUT) of
{value, ok} ->
ok;
{value, {error, Cause}} ->
{error, Cause};
{value, not_found = Cause} ->
{error, Cause};
{value, {badrpc = Cause, _}} ->
{error, Cause};
timeout = Cause->
{error, Cause}
end,
correct_redundancies_4(Ret, InconsistentNodes, NodeL, Metadata).
%% @private
correct_redundancies_4(ok,_InconsistentNodes,_NodeL,_Metadata) ->
ok;
correct_redundancies_4({error, eof},_InconsistentNodes,_NodeL, Metadata) ->
case (Metadata#?METADATA.dsize == 0) of
true ->
Obj = leo_object_storage_transformer:metadata_to_object(<<>>, Metadata),
case leo_storage_handler_object:put(Obj, 0) of
{ok,_} ->
ok;
Error ->
Error
end;
false ->
?error("correct_redundancies_4/4",
[{metadata, Metadata},
{cause, 'broken_object'}]),
ok
end;
correct_redundancies_4({error, not_found = Why},_InconsistentNodes, [Node|_Rest], Metadata) ->
?warn("correct_redundancies_4/4",
[{node, Node},
{metadata, Metadata}, {cause, Why}]),
ok;
correct_redundancies_4({error, Why}, InconsistentNodes, [Node|Rest], Metadata) ->
?debug("correct_redundancies_4/4",
[{inconsistent_nodes, InconsistentNodes},
{node, Node}, {metadata, Metadata}, {cause, Why}]),
correct_redundancies_3(InconsistentNodes, Rest, Metadata).
%% @doc Relocate an object because of executed "rebalance"
%% NOTE:
%% If remote-node status is NOT 'running',
%% this function cannot operate 'copy'.
%% @private
rebalance_1(#rebalance_message{node = Node,
vnode_id = VNodeId,
addr_id = AddrId,
key = Key} = Msg) ->
case leo_redundant_manager_api:get_member_by_node(Node) of
{ok, #member{state = ?STATE_RUNNING}} ->
ok = decrement_counter(?TBL_REBALANCE_COUNTER, VNodeId),
case leo_redundant_manager_api:get_redundancies_by_key(Key) of
{ok, #redundancies{nodes = Redundancies}} ->
Ret = delete_node_from_redundancies(Redundancies, Node, []),
rebalance_2(Ret, Msg);
_ ->
ok = publish(?QUEUE_ID_PER_OBJECT,
AddrId, Key, ?ERR_TYPE_REPLICATE_DATA),
{error, ?ERROR_COULD_NOT_GET_REDUNDANCY}
end;
{error, Cause} ->
?warn("rebalance_1/1",
[{node, Node}, {addr_id, AddrId},
{key, Key}, {cause, Cause}]),
ok = publish(?QUEUE_ID_PER_OBJECT,
AddrId, Key, ?ERR_TYPE_REPLICATE_DATA),
{error, inactive}
end.
%% @private
rebalance_2({ok,[]},_) ->
ok;
rebalance_2({ok, Redundancies}, #rebalance_message{node = Node,
addr_id = AddrId,
key = Key}) ->
Redundancies_1 = get_redundancies_with_replicas(
AddrId, Key, Redundancies),
case find_node_from_redundancies(Redundancies_1, erlang:node()) of
true ->
case lists:filter(
fun(#redundant_node{node = RedundantNode}) ->
Node == RedundantNode
end, Redundancies_1) of
[] ->
?MODULE:publish(?QUEUE_ID_PER_OBJECT,
AddrId, Key, ?ERR_TYPE_RECOVER_DATA);
_ ->
send_object_to_remote_node(Node, AddrId, Key)
end;
false ->
?warn("rebalance_2/2",
[{node, Node}, {addr_id, AddrId},
{key, Key}, {cause, 'node_not_found'}]),
publish(?QUEUE_ID_PER_OBJECT,
AddrId, Key, ?ERR_TYPE_REPLICATE_DATA)
end.
%% @doc Retrieve redundancies with a number of replicas
%% @private
get_redundancies_with_replicas(AddrId, Key, Redundancies) ->
%% Retrieve redundancies with a number of replicas
case leo_object_storage_api:head({AddrId, Key}) of
{ok, MetaBin} ->
case binary_to_term(MetaBin) of
#?METADATA{num_of_replicas = 0} ->
Redundancies;
#?METADATA{num_of_replicas = NumOfReplicas} ->
lists:sublist(Redundancies, NumOfReplicas)
end;
_ ->
Redundancies
end.
%% @doc Notify a rebalance-progress messages to manager.
%% - Retrieve # of published messages for rebalance,
%% after notify a message to manager.
%%
-spec(notify_rebalance_message_to_manager(integer()) ->
ok | {error, any()}).
notify_rebalance_message_to_manager(VNodeId) ->
case ets_lookup(?TBL_REBALANCE_COUNTER, VNodeId) of
{ok, NumOfMessages} ->
Fun = fun(_Manager, true) ->
void;
(Manager0, false = Res) ->
Manager1 = case is_atom(Manager0) of
true -> Manager0;
false -> list_to_atom(Manager0)
end,
case catch rpc:call(Manager1, leo_manager_api, notify,
[rebalance, VNodeId,
erlang:node(), NumOfMessages],
?DEF_REQ_TIMEOUT) of
ok ->
true;
{_, Cause} ->
?error("notify_rebalance_message_to_manager/1",
[{manager, Manager1},
{vnode_id, VNodeId}, {cause, Cause}]),
Res;
timeout ->
Res
end
end,
lists:foldl(Fun, false, ?env_manager_nodes(leo_storage)),
ok;
Error ->
Error
end.
%% @doc Fix consistency of an object between a local-cluster and remote-cluster(s)
%% @private
fix_consistency_between_clusters(#inconsistent_data_with_dc{
addr_id = AddrId,
key = Key,
del = ?DEL_FALSE}) ->
case leo_storage_handler_object:get(AddrId, Key, -1) of
{ok, Metadata, Bin} ->
Object = leo_object_storage_transformer:metadata_to_object(Metadata),
leo_sync_remote_cluster:defer_stack(Object#?OBJECT{data = Bin});
_ ->
ok
end;
fix_consistency_between_clusters(#inconsistent_data_with_dc{
cluster_id = ClusterId,
addr_id = AddrId,
key = Key,
del = ?DEL_TRUE}) ->
Metadata = #?METADATA{cluster_id = ClusterId,
addr_id = AddrId,
key = Key,
dsize = 0,
del = ?DEL_FALSE},
Object = leo_object_storage_transformer:metadata_to_object(Metadata),
leo_sync_remote_cluster:stack(Object#?OBJECT{data = <<>>}).
%%--------------------------------------------------------------------
%% INNTERNAL FUNCTIONS-2
%%--------------------------------------------------------------------
%% @doc Lookup rebalance counter
%% @private
-spec(ets_lookup(Table, Key) ->
{ok, Value} | {error, Cause} when Table::atom(),
Key::binary(),
Value::integer(),
Cause::any()).
ets_lookup(Table, Key) ->
case catch ets:lookup(Table, Key) of
[] ->
{ok, 0};
[{_Key, Value}] ->
{ok, Value};
{'EXIT', Cause} ->
{error, Cause}
end.
%% @doc Increment rebalance counter
%% @private
increment_counter(Table, Key) ->
catch ets:update_counter(Table, Key, 1),
ok.
%% @doc Decrement rebalance counter
%% @private
decrement_counter(Table, Key) ->
catch ets:update_counter(Table, Key, -1),
ok.