-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathrabbit_variable_queue.erl
2430 lines (2203 loc) · 109 KB
/
rabbit_variable_queue.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
%% 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) 2007-2025 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(rabbit_variable_queue).
-export([init/3, terminate/2, delete_and_terminate/2, delete_crashed/1,
purge/1, purge_acks/1,
publish/5, publish_delivered/4,
discard/3, drain_confirmed/1,
dropwhile/2, fetchwhile/4, fetch/2, drop/2, ack/2, requeue/2,
ackfold/4, fold/3, len/1, is_empty/1, depth/1,
update_rates/1, needs_timeout/1, timeout/1,
handle_pre_hibernate/1, resume/1, msg_rates/1,
info/2, invoke/3, is_duplicate/2, set_queue_mode/2,
set_queue_version/2, zip_msgs_and_acks/4]).
-export([start/2, stop/1]).
%% This function is used by rabbit_classic_queue_index_v2
%% to convert v1 queues to v2 after an upgrade to 4.0.
-export([convert_from_v1_to_v2_loop/8]).
%% exported for testing only
-export([start_msg_store/3, stop_msg_store/1, init/5]).
-include("mc.hrl").
-include_lib("stdlib/include/qlc.hrl").
-define(QUEUE_MIGRATION_BATCH_SIZE, 100).
-define(EMPTY_START_FUN_STATE, {fun (ok) -> finished end, ok}).
%%----------------------------------------------------------------------------
%% Messages, their metadata and their position in the queue (SeqId),
%% can be in memory or on disk, or both. Persistent messages in
%% durable queues are always written to disk when they arrive.
%% Transient messages as well as persistent messages in non-durable
%% queues may be kept only in memory.
%%
%% The number of messages kept in memory is dependent on the consume
%% rate of the queue. At a minimum 1 message is kept (necessary because
%% we often need to check the expiration at the head of the queue) and
%% at a maximum the semi-arbitrary number 2048.
%%
%% Messages are never written back to disk after they have been read
%% into memory. Instead the queue is designed to avoid keeping too
%% much to begin with.
%%
%% Messages are persisted using a queue index and a message store.
%% A few different scenarios may play out depending on the message
%% size:
%%
%% - size < qi_msgs_embed_below: the metadata
%% is stored in rabbit_classic_queue_index_v2, while the content
%% is stored in the per-queue rabbit_classic_queue_store_v2
%%
%% - size >= qi_msgs_embed_below: the metadata
%% is stored in rabbit_classic_queue_index_v2, while the content
%% is stored in the per-vhost shared rabbit_msg_store
%%
%% When messages must be read from disk, message bodies will
%% also be read from disk except if the message is stored
%% in the per-vhost shared rabbit_msg_store. In that case
%% the message gets read before it needs to be sent to the
%% consumer. Messages are read from rabbit_msg_store one
%% at a time currently.
%%
%% The queue also keeps track of messages that were delivered
%% but for which the ack has not been received. Pending acks
%% are currently kept in memory although the message may be
%% on disk.
%%
%% Messages being requeued are returned to their position in
%% the queue using their SeqId value.
%%
%% In order to try to achieve as fast a start-up as possible, if a
%% clean shutdown occurs, we try to save out state to disk to reduce
%% work on startup. In rabbit_msg_store this takes the form of the
%% index_module's state, plus the file_summary ets table, and client
%% refs. In the VQ, this takes the form of the count of persistent
%% messages in the queue and references into the msg_stores. The
%% queue index adds to these terms the details of its segments and
%% stores the terms in the queue directory.
%%
%% Two rabbit_msg_store(s) are used. One is created for persistent messages
%% to durable queues that must survive restarts, and the other is used
%% for all other messages that just happen to need to be written to
%% disk. On start up we can therefore nuke the transient message
%% store, and be sure that the messages in the persistent store are
%% all that we need.
%%
%% The references to the msg_stores are there so that the msg_store
%% knows to only trust its saved state if all of the queues it was
%% previously talking to come up cleanly. Likewise, the queues
%% themselves (especially indexes) skip work in init if all the queues
%% and msg_store were shutdown cleanly. This gives both good speed
%% improvements and also robustness so that if anything possibly went
%% wrong in shutdown (or there was subsequent manual tampering), all
%% messages and queues that can be recovered are recovered, safely.
%%
%% To delete transient messages lazily, the variable_queue, on
%% startup, stores the next_seq_id reported by the queue_index as the
%% transient_threshold. From that point on, whenever it's reading a
%% message off disk via the queue_index, if the seq_id is below this
%% threshold and the message is transient then it drops the message
%% (the message itself won't exist on disk because it would have been
%% stored in the transient msg_store which would have had its saved
%% state nuked on startup). This avoids the expensive operation of
%% scanning the entire queue on startup in order to delete transient
%% messages that were written to disk.
%%
%% The queue is keeping track of delivers via the
%% next_deliver_seq_id variable. This variable gets increased
%% with every (first-time) delivery. When delivering messages
%% the seq_id of the message is checked against this variable
%% to determine whether the message is a redelivery. The variable
%% is stored in the queue terms on graceful shutdown. On dirty
%% recovery the variable becomes the seq_id of the most recent
%% message in the queue (effectively marking all messages as
%% delivered, like the v1 index was doing).
%%
%% Previous versions of classic queues had a much more complex
%% way of working. Messages were categorized into four groups,
%% and remnants of these terms remain in the code at the time
%% of writing:
%%
%% alpha: this is a message where both the message itself, and its
%% position within the queue are held in RAM
%%
%% beta: this is a message where the message itself is only held on
%% disk (if persisted to the message store) but its position
%% within the queue is held in RAM.
%%
%% gamma: this is a message where the message itself is only held on
%% disk, but its position is both in RAM and on disk.
%%
%% delta: this is a collection of messages, represented by a single
%% term, where the messages and their position are only held on
%% disk.
%%
%% Messages may have been stored in q1, q2, delta, q3 or q4 depending
%% on their location in the queue. The current version of classic
%% queues only use delta (on-disk, for the tail of the queue) or
%% q3 (in-memory, head of the queue). Messages used to move from
%% q1 -> q2 -> delta -> q3 -> q4 (and sometimes q3 -> delta or
%% q4 -> delta to reduce memory use). Now messages only move
%% from delta to q3. Full details on the old mechanisms can be
%% found in previous versions of this file (such as the 3.11 version).
%%
%% In the current version of classic queues, there is no distinction
%% between default and lazy queues. The current behavior is close to
%% lazy queues, except we avoid some write to disks when queues are
%% empty.
%%----------------------------------------------------------------------------
-behaviour(rabbit_backing_queue).
-record(vqstate,
{ q1, %% Unused.
q2, %% Unused.
delta,
q3,
q4, %% Unused.
next_seq_id,
%% seq_id() of first undelivered message
%% everything before this seq_id() was delivered at least once
next_deliver_seq_id,
ram_pending_ack, %% msgs still in RAM
disk_pending_ack, %% msgs in store, paged out
qi_pending_ack, %% Unused.
index_mod, %% Unused.
index_state,
store_state,
msg_store_clients,
durable,
transient_threshold,
qi_embed_msgs_below,
len, %% w/o unacked @todo No longer needed, is delta+q3.
bytes, %% w/o unacked
unacked_bytes,
persistent_count, %% w unacked
persistent_bytes, %% w unacked
delta_transient_bytes, %%
target_ram_count,
ram_msg_count, %% w/o unacked
ram_msg_count_prev,
ram_ack_count_prev,
ram_bytes, %% w unacked
out_counter,
in_counter,
rates,
%% There are two confirms paths: either store/index produce confirms
%% separately (v1 and v2 with per-vhost message store) or the confirms
%% are produced all at once while syncing/flushing (v2 with per-queue
%% message store). The latter is more efficient as it avoids many
%% sets operations.
msgs_on_disk,
msg_indices_on_disk,
unconfirmed,
confirmed,
ack_out_counter,
ack_in_counter,
%% Unlike the other counters these two do not feed into
%% #rates{} and get reset
disk_read_count,
disk_write_count,
io_batch_size, %% Unused.
%% default queue or lazy queue
mode, %% Unused.
version = 2, %% Unused.
%% Fast path for confirms handling. Instead of having
%% index/store keep track of confirms separately and
%% doing intersect/subtract/union we just put the messages
%% here and on sync move them to 'confirmed'.
%%
%% Note: This field used to be 'memory_reduction_run_count'.
unconfirmed_simple,
%% Queue data is grouped by VHost. We need to store it
%% to work with queue index.
virtual_host,
waiting_bump = false
}).
-record(rates, { in, out, ack_in, ack_out, timestamp }).
-type msg_location() :: memory
| rabbit_msg_store
| rabbit_queue_index
| rabbit_classic_queue_store_v2:msg_location().
-export_type([msg_location/0]).
-record(msg_status,
{ seq_id,
msg_id,
msg,
is_persistent,
is_delivered,
msg_location, %% ?IN_SHARED_STORE | ?IN_QUEUE_STORE | ?IN_QUEUE_INDEX | ?IN_MEMORY
index_on_disk,
persist_to,
msg_props
}).
-record(delta,
{ start_seq_id, %% start_seq_id is inclusive
count,
transient,
end_seq_id %% end_seq_id is exclusive
}).
-define(HEADER_GUESS_SIZE, 100). %% see determine_persist_to/2
-define(PERSISTENT_MSG_STORE, msg_store_persistent).
-define(TRANSIENT_MSG_STORE, msg_store_transient).
-define(QUEUE, lqueue).
-define(IN_SHARED_STORE, rabbit_msg_store).
-define(IN_QUEUE_STORE, {rabbit_classic_queue_store_v2, _, _}).
-define(IN_QUEUE_INDEX, rabbit_queue_index).
-define(IN_MEMORY, memory).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("amqqueue.hrl").
%%----------------------------------------------------------------------------
-type seq_id() :: non_neg_integer().
-export_type([seq_id/0]).
-type rates() :: #rates { in :: float(),
out :: float(),
ack_in :: float(),
ack_out :: float(),
timestamp :: rabbit_types:timestamp()}.
-type delta() :: #delta { start_seq_id :: non_neg_integer(),
count :: non_neg_integer(),
end_seq_id :: non_neg_integer() }.
%% The compiler (rightfully) complains that ack() and state() are
%% unused. For this reason we duplicate a -spec from
%% rabbit_backing_queue with the only intent being to remove
%% warnings. The problem here is that we can't parameterise the BQ
%% behaviour by these two types as we would like to. We still leave
%% these here for documentation purposes.
-type ack() :: seq_id().
-type state() :: #vqstate {
q1 :: ?QUEUE:?QUEUE(),
q2 :: ?QUEUE:?QUEUE(),
delta :: delta(),
q3 :: ?QUEUE:?QUEUE(),
q4 :: ?QUEUE:?QUEUE(),
next_seq_id :: seq_id(),
next_deliver_seq_id :: seq_id(),
ram_pending_ack :: map(),
disk_pending_ack :: map(),
qi_pending_ack :: undefined,
index_state :: any(),
store_state :: any(),
msg_store_clients :: 'undefined' | {{any(), binary()},
{any(), binary()}},
durable :: boolean(),
transient_threshold :: non_neg_integer(),
qi_embed_msgs_below :: non_neg_integer(),
len :: non_neg_integer(),
bytes :: non_neg_integer(),
unacked_bytes :: non_neg_integer(),
persistent_count :: non_neg_integer(),
persistent_bytes :: non_neg_integer(),
target_ram_count :: non_neg_integer() | 'infinity',
ram_msg_count :: non_neg_integer(),
ram_msg_count_prev :: non_neg_integer(),
ram_ack_count_prev :: non_neg_integer(),
ram_bytes :: non_neg_integer(),
out_counter :: non_neg_integer(),
in_counter :: non_neg_integer(),
rates :: rates(),
msgs_on_disk :: sets:set(),
msg_indices_on_disk :: sets:set(),
unconfirmed :: sets:set(),
confirmed :: sets:set(),
ack_out_counter :: non_neg_integer(),
ack_in_counter :: non_neg_integer(),
disk_read_count :: non_neg_integer(),
disk_write_count :: non_neg_integer(),
io_batch_size :: 0,
mode :: 'default' | 'lazy',
version :: 2,
unconfirmed_simple :: sets:set()}.
-define(BLANK_DELTA, #delta { start_seq_id = undefined,
count = 0,
transient = 0,
end_seq_id = undefined }).
-define(BLANK_DELTA_PATTERN(Z), #delta { start_seq_id = Z,
count = 0,
transient = 0,
end_seq_id = Z }).
-define(MICROS_PER_SECOND, 1000000.0).
%% We're updating rates every 5s at most; a half life that is of
%% the same order of magnitude is probably about right.
-define(RATE_AVG_HALF_LIFE, 5.0).
%% We will recalculate the #rates{} every 5 seconds,
%% or every N messages published, whichever is
%% sooner. We do this since the priority calculations in
%% rabbit_amqqueue_process need fairly fresh rates.
-define(MSGS_PER_RATE_CALC, 100).
%%----------------------------------------------------------------------------
%% Public API
%%----------------------------------------------------------------------------
start(VHost, DurableQueues) ->
%% The v2 index walker function covers both v1 and v2 index files.
{AllTerms, StartFunState} = rabbit_classic_queue_index_v2:start(VHost, DurableQueues),
%% Group recovery terms by vhost.
ClientRefs = [Ref || Terms <- AllTerms,
Terms /= non_clean_shutdown,
begin
Ref = proplists:get_value(persistent_ref, Terms),
Ref =/= undefined
end],
start_msg_store(VHost, ClientRefs, StartFunState),
{ok, AllTerms}.
stop(VHost) ->
ok = stop_msg_store(VHost),
ok = rabbit_classic_queue_index_v2:stop(VHost).
start_msg_store(VHost, Refs, StartFunState) when is_list(Refs); Refs == undefined ->
rabbit_log:info("Starting message stores for vhost '~ts'", [VHost]),
do_start_msg_store(VHost, ?TRANSIENT_MSG_STORE, undefined, ?EMPTY_START_FUN_STATE),
do_start_msg_store(VHost, ?PERSISTENT_MSG_STORE, Refs, StartFunState),
ok.
do_start_msg_store(VHost, Type, Refs, StartFunState) ->
case rabbit_vhost_msg_store:start(VHost, Type, Refs, StartFunState) of
{ok, _} ->
rabbit_log:info("Started message store of type ~ts for vhost '~ts'", [abbreviated_type(Type), VHost]);
{error, {no_such_vhost, VHost}} = Err ->
rabbit_log:error("Failed to start message store of type ~ts for vhost '~ts': the vhost no longer exists!",
[Type, VHost]),
exit(Err);
{error, Error} ->
rabbit_log:error("Failed to start message store of type ~ts for vhost '~ts': ~tp",
[Type, VHost, Error]),
exit({error, Error})
end.
abbreviated_type(?TRANSIENT_MSG_STORE) -> transient;
abbreviated_type(?PERSISTENT_MSG_STORE) -> persistent.
stop_msg_store(VHost) ->
rabbit_vhost_msg_store:stop(VHost, ?TRANSIENT_MSG_STORE),
rabbit_vhost_msg_store:stop(VHost, ?PERSISTENT_MSG_STORE),
ok.
init(Queue, Recover, Callback) ->
init(
Queue, Recover,
fun (MsgIds, ActionTaken) ->
msgs_written_to_disk(Callback, MsgIds, ActionTaken)
end,
fun (MsgIds) -> msg_indices_written_to_disk(Callback, MsgIds) end,
fun (MsgIds) -> msgs_and_indices_written_to_disk(Callback, MsgIds) end).
init(Q, new, MsgOnDiskFun, MsgIdxOnDiskFun, MsgAndIdxOnDiskFun) when ?is_amqqueue(Q) ->
QueueName = amqqueue:get_name(Q),
IsDurable = amqqueue:is_durable(Q),
IndexState = rabbit_classic_queue_index_v2:init(QueueName,
MsgIdxOnDiskFun, MsgAndIdxOnDiskFun),
StoreState = rabbit_classic_queue_store_v2:init(QueueName),
VHost = QueueName#resource.virtual_host,
init(IsDurable, IndexState, StoreState, 0, 0, [],
case IsDurable of
true -> msg_store_client_init(?PERSISTENT_MSG_STORE,
MsgOnDiskFun, VHost);
false -> undefined
end,
msg_store_client_init(?TRANSIENT_MSG_STORE, undefined,
VHost), VHost);
%% We can be recovering a transient queue if it crashed
init(Q, Terms, MsgOnDiskFun, MsgIdxOnDiskFun, MsgAndIdxOnDiskFun) when ?is_amqqueue(Q) ->
QueueName = amqqueue:get_name(Q),
IsDurable = amqqueue:is_durable(Q),
{PRef, RecoveryTerms} = process_recovery_terms(Terms),
VHost = QueueName#resource.virtual_host,
{PersistentClient, ContainsCheckFun} =
case IsDurable of
true -> C = msg_store_client_init(?PERSISTENT_MSG_STORE, PRef,
MsgOnDiskFun, VHost),
{C, fun (MsgId) when is_binary(MsgId) ->
rabbit_msg_store:contains(MsgId, C);
(Msg) ->
mc:is_persistent(Msg)
end};
false -> {undefined, fun(_MsgId) -> false end}
end,
TransientClient = msg_store_client_init(?TRANSIENT_MSG_STORE,
undefined, VHost),
{DeltaCount, DeltaBytes, IndexState} =
rabbit_classic_queue_index_v2:recover(
QueueName, RecoveryTerms,
rabbit_vhost_msg_store:successfully_recovered_state(
VHost,
?PERSISTENT_MSG_STORE),
ContainsCheckFun, MsgIdxOnDiskFun, MsgAndIdxOnDiskFun,
main),
StoreState = rabbit_classic_queue_store_v2:init(QueueName),
init(IsDurable, IndexState, StoreState,
DeltaCount, DeltaBytes, RecoveryTerms,
PersistentClient, TransientClient, VHost).
process_recovery_terms(Terms=non_clean_shutdown) ->
{rabbit_guid:gen(), Terms};
process_recovery_terms(Terms) ->
case proplists:get_value(persistent_ref, Terms) of
undefined -> {rabbit_guid:gen(), []};
PRef -> {PRef, Terms}
end.
terminate(_Reason, State) ->
State1 = #vqstate { virtual_host = VHost,
next_seq_id = NextSeqId,
next_deliver_seq_id = NextDeliverSeqId,
persistent_count = PCount,
persistent_bytes = PBytes,
index_state = IndexState,
store_state = StoreState,
msg_store_clients = {MSCStateP, MSCStateT} } =
purge_pending_ack(true, State),
PRef = case MSCStateP of
undefined -> undefined;
_ -> ok = maybe_client_terminate(MSCStateP),
rabbit_msg_store:client_ref(MSCStateP)
end,
ok = rabbit_msg_store:client_delete_and_terminate(MSCStateT),
Terms = [{next_seq_id, NextSeqId},
{next_deliver_seq_id, NextDeliverSeqId},
{persistent_ref, PRef},
{persistent_count, PCount},
{persistent_bytes, PBytes}],
a(State1#vqstate {
index_state = rabbit_classic_queue_index_v2:terminate(VHost, Terms, IndexState),
store_state = rabbit_classic_queue_store_v2:terminate(StoreState),
msg_store_clients = undefined }).
%% the only difference between purge and delete is that delete also
%% needs to delete everything that's been delivered and not ack'd.
delete_and_terminate(_Reason, State) ->
%% Normally when we purge messages we interact with the qi by
%% issues delivers and acks for every purged message. In this case
%% we don't need to do that, so we just delete the qi.
State1 = purge_and_index_reset(State),
State2 = #vqstate { msg_store_clients = {MSCStateP, MSCStateT} } =
purge_pending_ack_delete_and_terminate(State1),
case MSCStateP of
undefined -> ok;
_ -> rabbit_msg_store:client_delete_and_terminate(MSCStateP)
end,
rabbit_msg_store:client_delete_and_terminate(MSCStateT),
a(State2 #vqstate { msg_store_clients = undefined }).
delete_crashed(Q) when ?is_amqqueue(Q) ->
QName = amqqueue:get_name(Q),
ok = rabbit_classic_queue_index_v2:erase(QName).
purge(State = #vqstate { len = Len }) ->
case is_pending_ack_empty(State) and is_unconfirmed_empty(State) of
true ->
{Len, purge_and_index_reset(State)};
false ->
{Len, purge_when_pending_acks(State)}
end.
purge_acks(State) -> a(purge_pending_ack(false, State)).
publish(Msg, MsgProps, IsDelivered, ChPid, State) ->
State1 =
publish1(Msg, MsgProps, IsDelivered, ChPid,
fun maybe_write_to_disk/4,
State),
a(maybe_update_rates(State1)).
publish_delivered(Msg, MsgProps, ChPid, State) ->
{SeqId, State1} =
publish_delivered1(Msg, MsgProps, ChPid,
fun maybe_write_to_disk/4,
State),
{SeqId, a(maybe_update_rates(State1))}.
discard(_Msg, _ChPid, State) -> State.
drain_confirmed(State = #vqstate { confirmed = C }) ->
case sets:is_empty(C) of
true -> {[], State}; %% common case
false -> {sets:to_list(C), State #vqstate {
confirmed = sets:new([{version, 2}]) }}
end.
dropwhile(Pred, State) ->
{MsgProps, State1} =
remove_by_predicate(Pred, State),
{MsgProps, a(State1)}.
fetchwhile(Pred, Fun, Acc, State) ->
{MsgProps, Acc1, State1} =
fetch_by_predicate(Pred, Fun, Acc, State),
{MsgProps, Acc1, a(State1)}.
fetch(AckRequired, State) ->
case queue_out(State) of
{empty, State1} ->
{empty, a(State1)};
{{value, MsgStatus}, State1} ->
%% it is possible that the message wasn't read from disk
%% at this point, so read it in.
{Msg, State2} = read_msg(MsgStatus, State1),
{AckTag, State3} = remove(AckRequired, MsgStatus, State2),
{{Msg, MsgStatus#msg_status.is_delivered, AckTag}, a(State3)}
end.
%% @todo It may seem like we would benefit from avoiding reading the
%% message content from disk. But benchmarks tell a different
%% story. So we don't, until a better understanding is gained.
drop(AckRequired, State) ->
case queue_out(State) of
{empty, State1} ->
{empty, a(State1)};
{{value, MsgStatus}, State1} ->
{AckTag, State2} = remove(AckRequired, MsgStatus, State1),
{{MsgStatus#msg_status.msg_id, AckTag}, a(State2)}
end.
%% Duplicated from rabbit_backing_queue
-spec ack([ack()], state()) -> {[rabbit_guid:guid()], state()}.
ack([], State) ->
{[], State};
%% optimisation: this head is essentially a partial evaluation of the
%% general case below, for the single-ack case.
ack([SeqId], State) ->
case remove_pending_ack(true, SeqId, State) of
{none, _} ->
{[], State};
{MsgStatus = #msg_status{ msg_id = MsgId },
State1 = #vqstate{ ack_out_counter = AckOutCount }} ->
State2 = remove_from_disk(MsgStatus, State1),
{[MsgId],
a(State2 #vqstate { ack_out_counter = AckOutCount + 1 })}
end;
ack(AckTags, State) ->
{{IndexOnDiskSeqIds, MsgIdsByStore, SeqIdsInStore, AllMsgIds},
State1 = #vqstate { index_state = IndexState,
store_state = StoreState0,
ack_out_counter = AckOutCount }} =
lists:foldl(
fun (SeqId, {Acc, State2}) ->
%% @todo When acking many messages we should update stats once not for every.
%% Also remove the pending acks all at once instead of every.
case remove_pending_ack(true, SeqId, State2) of
{none, _} ->
{Acc, State2};
{MsgStatus, State3} ->
{accumulate_ack(MsgStatus, Acc), State3}
end
end, {accumulate_ack_init(), State}, AckTags),
{DeletedSegments, IndexState1} = rabbit_classic_queue_index_v2:ack(IndexOnDiskSeqIds, IndexState),
StoreState1 = rabbit_classic_queue_store_v2:delete_segments(DeletedSegments, StoreState0),
StoreState = lists:foldl(fun rabbit_classic_queue_store_v2:remove/2, StoreState1, SeqIdsInStore),
State2 = remove_vhost_msgs_by_id(MsgIdsByStore, State1),
{lists:reverse(AllMsgIds),
a(State2 #vqstate { index_state = IndexState1,
store_state = StoreState,
ack_out_counter = AckOutCount + length(AckTags) })}.
requeue(AckTags, #vqstate { delta = Delta,
q3 = Q3,
in_counter = InCounter,
len = Len } = State) ->
%% @todo This can be heavily simplified: if the message falls into delta,
%% add it there. Otherwise just add it to q3 in the correct position.
{SeqIds, Q3a, MsgIds, State1} = requeue_merge(lists:sort(AckTags), Q3, [],
delta_limit(Delta), State),
{Delta1, MsgIds1, State2} = delta_merge(SeqIds, Delta, MsgIds,
State1),
MsgCount = length(MsgIds1),
{MsgIds1, a(
maybe_update_rates(ui(
State2 #vqstate { delta = Delta1,
q3 = Q3a,
in_counter = InCounter + MsgCount,
len = Len + MsgCount })))}.
ackfold(MsgFun, Acc, State, AckTags) ->
{AccN, StateN} =
lists:foldl(fun(SeqId, {Acc0, State0}) ->
MsgStatus = lookup_pending_ack(SeqId, State0),
{Msg, State1} = read_msg(MsgStatus, State0),
{MsgFun(Msg, SeqId, Acc0), State1}
end, {Acc, State}, AckTags),
{AccN, a(StateN)}.
fold(Fun, Acc, State = #vqstate{index_state = IndexState}) ->
{Its, IndexState1} = lists:foldl(fun inext/2, {[], IndexState},
[msg_iterator(State),
disk_ack_iterator(State),
ram_ack_iterator(State)]),
ifold(Fun, Acc, Its, State#vqstate{index_state = IndexState1}).
len(#vqstate { len = Len }) -> Len.
is_empty(State) -> 0 == len(State).
depth(State) ->
len(State) + count_pending_acks(State).
maybe_update_rates(State = #vqstate{ in_counter = InCount,
out_counter = OutCount })
when InCount + OutCount > ?MSGS_PER_RATE_CALC ->
update_rates(State);
maybe_update_rates(State) ->
State.
update_rates(State = #vqstate{ in_counter = InCount,
out_counter = OutCount,
ack_in_counter = AckInCount,
ack_out_counter = AckOutCount,
rates = #rates{ in = InRate,
out = OutRate,
ack_in = AckInRate,
ack_out = AckOutRate,
timestamp = TS }}) ->
Now = erlang:monotonic_time(),
Rates = #rates { in = update_rate(Now, TS, InCount, InRate),
out = update_rate(Now, TS, OutCount, OutRate),
ack_in = update_rate(Now, TS, AckInCount, AckInRate),
ack_out = update_rate(Now, TS, AckOutCount, AckOutRate),
timestamp = Now },
State#vqstate{ in_counter = 0,
out_counter = 0,
ack_in_counter = 0,
ack_out_counter = 0,
rates = Rates }.
update_rate(Now, TS, Count, Rate) ->
Time = erlang:convert_time_unit(Now - TS, native, micro_seconds) /
?MICROS_PER_SECOND,
if
Time == 0 -> Rate;
true -> rabbit_misc:moving_average(Time, ?RATE_AVG_HALF_LIFE,
Count / Time, Rate)
end.
needs_timeout(#vqstate { index_state = IndexState,
unconfirmed_simple = UCS }) ->
case {rabbit_classic_queue_index_v2:needs_sync(IndexState), sets:is_empty(UCS)} of
{false, false} -> timed;
{confirms, _} -> timed;
{false, true} -> false
end.
timeout(State = #vqstate { index_state = IndexState0,
store_state = StoreState0,
unconfirmed_simple = UCS,
confirmed = C }) ->
IndexState = rabbit_classic_queue_index_v2:sync(IndexState0),
StoreState = rabbit_classic_queue_store_v2:sync(StoreState0),
State #vqstate { index_state = IndexState,
store_state = StoreState,
unconfirmed_simple = sets:new([{version,2}]),
confirmed = sets:union(C, UCS) }.
handle_pre_hibernate(State = #vqstate { index_state = IndexState0,
store_state = StoreState0,
msg_store_clients = MSCState0,
unconfirmed_simple = UCS,
confirmed = C }) ->
MSCState = msg_store_pre_hibernate(MSCState0),
IndexState = rabbit_classic_queue_index_v2:flush(IndexState0),
StoreState = rabbit_classic_queue_store_v2:sync(StoreState0),
State #vqstate { index_state = IndexState,
store_state = StoreState,
msg_store_clients = MSCState,
unconfirmed_simple = sets:new([{version,2}]),
confirmed = sets:union(C, UCS) }.
resume(State) -> a(timeout(State)).
msg_rates(#vqstate { rates = #rates { in = AvgIngressRate,
out = AvgEgressRate } }) ->
{AvgIngressRate, AvgEgressRate}.
info(messages_ready_ram, #vqstate{ram_msg_count = RamMsgCount}) ->
RamMsgCount;
info(messages_unacknowledged_ram, #vqstate{ram_pending_ack = RPA}) ->
map_size(RPA);
info(messages_ram, State) ->
info(messages_ready_ram, State) + info(messages_unacknowledged_ram, State);
info(messages_persistent, #vqstate{persistent_count = PersistentCount}) ->
PersistentCount;
info(messages_paged_out, #vqstate{delta = #delta{transient = Count}}) ->
Count;
info(message_bytes, #vqstate{bytes = Bytes,
unacked_bytes = UBytes}) ->
Bytes + UBytes;
info(message_bytes_ready, #vqstate{bytes = Bytes}) ->
Bytes;
info(message_bytes_unacknowledged, #vqstate{unacked_bytes = UBytes}) ->
UBytes;
info(message_bytes_ram, #vqstate{ram_bytes = RamBytes}) ->
RamBytes;
info(message_bytes_persistent, #vqstate{persistent_bytes = PersistentBytes}) ->
PersistentBytes;
info(message_bytes_paged_out, #vqstate{delta_transient_bytes = PagedOutBytes}) ->
PagedOutBytes;
info(head_message_timestamp, #vqstate{
q3 = Q3,
ram_pending_ack = RPA}) ->
head_message_timestamp(Q3, RPA);
info(oldest_message_received_timestamp, #vqstate{
q3 = Q3,
ram_pending_ack = RPA}) ->
oldest_message_received_timestamp(Q3, RPA);
info(disk_reads, #vqstate{disk_read_count = Count}) ->
Count;
info(disk_writes, #vqstate{disk_write_count = Count}) ->
Count;
info(backing_queue_status, #vqstate {
delta = Delta, q3 = Q3,
mode = Mode,
len = Len,
target_ram_count = TargetRamCount,
next_seq_id = NextSeqId,
next_deliver_seq_id = NextDeliverSeqId,
ram_pending_ack = RPA,
disk_pending_ack = DPA,
unconfirmed = UC,
unconfirmed_simple = UCS,
index_state = IndexState,
store_state = StoreState,
rates = #rates { in = AvgIngressRate,
out = AvgEgressRate,
ack_in = AvgAckIngressRate,
ack_out = AvgAckEgressRate }}) ->
[ {mode , Mode},
{version , 2},
{q1 , 0},
{q2 , 0},
{delta , Delta},
{q3 , ?QUEUE:len(Q3)},
{q4 , 0},
{len , Len},
{target_ram_count , TargetRamCount},
{next_seq_id , NextSeqId},
{next_deliver_seq_id , NextDeliverSeqId},
{num_pending_acks , map_size(RPA) + map_size(DPA)},
{num_unconfirmed , sets:size(UC) + sets:size(UCS)},
{avg_ingress_rate , AvgIngressRate},
{avg_egress_rate , AvgEgressRate},
{avg_ack_ingress_rate, AvgAckIngressRate},
{avg_ack_egress_rate , AvgAckEgressRate} ]
++ rabbit_classic_queue_index_v2:info(IndexState)
++ rabbit_classic_queue_store_v2:info(StoreState);
info(_, _) ->
''.
invoke(?MODULE, Fun, State) -> Fun(?MODULE, State);
invoke( _, _, State) -> State.
is_duplicate(_Msg, State) -> {false, State}.
%% Queue mode has been unified.
set_queue_mode(_, State) ->
State.
zip_msgs_and_acks(Msgs, AckTags, Accumulator, _State) ->
lists:foldl(fun ({{Msg, _Props}, AckTag}, Acc) ->
Id = mc:get_annotation(id, Msg),
[{Id, AckTag} | Acc]
end, Accumulator, lists:zip(Msgs, AckTags)).
%% Queue version now ignored; only v2 is available.
set_queue_version(_, State) ->
State.
%% This function is used by rabbit_classic_queue_index_v2
%% to convert v1 queues to v2 after an upgrade to 4.0.
convert_from_v1_to_v2_loop(_, _, V2Index, V2Store, _, HiSeqId, HiSeqId, _) ->
{V2Index, V2Store};
convert_from_v1_to_v2_loop(QueueName, V1Index0, V2Index0, V2Store0,
Counters = {CountersRef, CountIx, BytesIx},
LoSeqId, HiSeqId, SkipFun) ->
UpSeqId = lists:min([rabbit_queue_index:next_segment_boundary(LoSeqId),
HiSeqId]),
{Messages, V1Index} = rabbit_queue_index:read(LoSeqId, UpSeqId, V1Index0),
%% We do a garbage collect immediately after the old index read
%% because that may have created a lot of garbage.
garbage_collect(),
{V2Index3, V2Store3} = lists:foldl(fun
%% Move embedded messages to the per-queue store.
({Msg, SeqId, rabbit_queue_index, Props, IsPersistent},
{V2Index1, V2Store1}) ->
MsgId = mc:get_annotation(id, Msg),
{MsgLocation, V2Store2} = rabbit_classic_queue_store_v2:write(SeqId, Msg, Props, V2Store1),
V2Index2 = case SkipFun(SeqId, V2Index1) of
{skip, V2Index1a} ->
V2Index1a;
{write, V2Index1a} ->
counters:add(CountersRef, CountIx, 1),
counters:add(CountersRef, BytesIx, Props#message_properties.size),
rabbit_classic_queue_index_v2:publish(MsgId, SeqId, MsgLocation, Props, IsPersistent, infinity, V2Index1a)
end,
{V2Index2, V2Store2};
%% Keep messages in the per-vhost store where they are.
({MsgId, SeqId, rabbit_msg_store, Props, IsPersistent},
{V2Index1, V2Store1}) ->
V2Index2 = case SkipFun(SeqId, V2Index1) of
{skip, V2Index1a} ->
V2Index1a;
{write, V2Index1a} ->
counters:add(CountersRef, CountIx, 1),
counters:add(CountersRef, BytesIx, Props#message_properties.size),
rabbit_classic_queue_index_v2:publish(MsgId, SeqId, rabbit_msg_store, Props, IsPersistent, infinity, V2Index1a)
end,
{V2Index2, V2Store1}
end, {V2Index0, V2Store0}, Messages),
%% Flush to disk to avoid keeping too much in memory between segments.
V2Index = rabbit_classic_queue_index_v2:flush(V2Index3),
V2Store = rabbit_classic_queue_store_v2:sync(V2Store3),
%% We have written everything to disk. We can delete the old segment file
%% to free up much needed space, to avoid doubling disk usage during the upgrade.
rabbit_queue_index:delete_segment_file_for_seq_id(LoSeqId, V1Index),
%% Log some progress to keep the user aware of what's going on, as moving
%% embedded messages can take quite some time.
#resource{virtual_host = VHost, name = Name} = QueueName,
rabbit_log:info("Queue ~ts in vhost ~ts converted ~b messages from v1 to v2",
[Name, VHost, length(Messages)]),
convert_from_v1_to_v2_loop(QueueName, V1Index, V2Index, V2Store, Counters, UpSeqId, HiSeqId, SkipFun).
%% Get the Timestamp property of the first msg, if present. This is
%% the one with the oldest timestamp among the heads of the pending
%% acks and unread queues. We can't check disk_pending_acks as these
%% are paged out - we assume some will soon be paged in rather than
%% forcing it to happen. Pending ack msgs are included as they are
%% regarded as unprocessed until acked, this also prevents the result
%% apparently oscillating during repeated rejects.
%%
head_message_timestamp(Q3, RPA) ->
HeadMsgs = [ HeadMsgStatus#msg_status.msg ||
HeadMsgStatus <-
[ get_q_head(Q3),
get_pa_head(RPA) ],
HeadMsgStatus /= undefined,
HeadMsgStatus#msg_status.msg /= undefined ],
Timestamps =
[Timestamp div 1000
|| HeadMsg <- HeadMsgs,
Timestamp <- [mc:timestamp(HeadMsg)],
Timestamp /= undefined
],
case Timestamps == [] of
true -> '';
false -> lists:min(Timestamps)
end.
oldest_message_received_timestamp(Q3, RPA) ->
HeadMsgs = [ HeadMsgStatus#msg_status.msg ||
HeadMsgStatus <-
[ get_q_head(Q3),
get_pa_head(RPA) ],
HeadMsgStatus /= undefined,
HeadMsgStatus#msg_status.msg /= undefined ],
Timestamps =
[Timestamp
|| HeadMsg <- HeadMsgs,
Timestamp <- [mc:get_annotation(?ANN_RECEIVED_AT_TIMESTAMP, HeadMsg)],
Timestamp /= undefined
],
case Timestamps == [] of
true -> '';
false -> lists:min(Timestamps)
end.
get_q_head(Q) ->
?QUEUE:get(Q, undefined).
get_pa_head(PA) ->
case maps:keys(PA) of
[] -> undefined;
Keys ->
Smallest = lists:min(Keys),
map_get(Smallest, PA)
end.
a(State = #vqstate { delta = Delta, q3 = Q3,
len = Len,
bytes = Bytes,
unacked_bytes = UnackedBytes,
persistent_count = PersistentCount,
persistent_bytes = PersistentBytes,
ram_msg_count = RamMsgCount,
ram_bytes = RamBytes}) ->
ED = Delta#delta.count == 0,
E3 = ?QUEUE:is_empty(Q3),
LZ = Len == 0,
L3 = ?QUEUE:len(Q3),
%% if the queue is empty, then delta is empty and q3 is empty.
true = LZ == (ED and E3),
%% There should be no messages in q1, q2, and q4
true = Delta#delta.count + L3 == Len,
true = Len >= 0,
true = Bytes >= 0,
true = UnackedBytes >= 0,
true = PersistentCount >= 0,
true = PersistentBytes >= 0,
true = RamMsgCount >= 0,
true = RamMsgCount =< Len,
true = RamBytes >= 0,
true = RamBytes =< Bytes + UnackedBytes,
State.
d(Delta = #delta { start_seq_id = Start, count = Count, end_seq_id = End })
when Start + Count =< End ->
Delta.
m(MsgStatus = #msg_status { is_persistent = IsPersistent,
msg_location = MsgLocation,
index_on_disk = IndexOnDisk }) ->
true = (not IsPersistent) or IndexOnDisk,
true = msg_in_ram(MsgStatus) or (MsgLocation =/= memory),
MsgStatus.
one_if(true ) -> 1;
one_if(false) -> 0.