-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
rabbit_amqqueue_process.erl
1884 lines (1698 loc) · 79.6 KB
/
rabbit_amqqueue_process.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-2023 VMware, Inc. or its affiliates. All rights reserved.
%%
-module(rabbit_amqqueue_process).
-include_lib("rabbit_common/include/rabbit.hrl").
-include_lib("rabbit_common/include/rabbit_framing.hrl").
-include("amqqueue.hrl").
-behaviour(gen_server2).
-define(SYNC_INTERVAL, 200). %% milliseconds
-define(RAM_DURATION_UPDATE_INTERVAL, 5000).
-define(CONSUMER_BIAS_RATIO, 2.0). %% i.e. consume 100% faster
-export([info_keys/0]).
-export([init_with_backing_queue_state/7]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2, handle_pre_hibernate/1, prioritise_call/4,
prioritise_cast/3, prioritise_info/3, format_message_queue/2]).
-export([format/1]).
-export([is_policy_applicable/2]).
%% Queue's state
-record(q, {
%% an #amqqueue record
q :: amqqueue:amqqueue(),
%% none | {exclusive consumer channel PID, consumer tag} | {single active consumer channel PID, consumer}
active_consumer,
%% Set to true if a queue has ever had a consumer.
%% This is used to determine when to delete auto-delete queues.
has_had_consumers,
%% backing queue module.
%% for mirrored queues, this will be rabbit_mirror_queue_master.
%% for non-priority and non-mirrored queues, rabbit_variable_queue.
%% see rabbit_backing_queue.
backing_queue,
%% backing queue state.
%% see rabbit_backing_queue, rabbit_variable_queue.
backing_queue_state,
%% consumers state, see rabbit_queue_consumers
consumers,
%% queue expiration value
expires,
%% timer used to periodically sync (flush) queue index
sync_timer_ref,
%% timer used to update ingress/egress rates and queue RAM duration target
rate_timer_ref,
%% timer used to clean up this queue due to TTL (on when unused)
expiry_timer_ref,
%% stats emission timer
stats_timer,
%% maps message IDs to {channel pid, MsgSeqNo}
%% pairs
msg_id_to_channel,
%% message TTL value
ttl,
%% timer used to delete expired messages
ttl_timer_ref,
ttl_timer_expiry,
%% Keeps track of channels that publish to this queue.
%% When channel process goes down, queues have to perform
%% certain cleanup.
senders,
%% dead letter exchange as a #resource record, if any
dlx,
dlx_routing_key,
%% max length in messages, if configured
max_length,
%% max length in bytes, if configured
max_bytes,
%% an action to perform if queue is to be over a limit,
%% can be either drop-head (default), reject-publish or reject-publish-dlx
overflow,
%% when policies change, this version helps queue
%% determine what previously scheduled/set up state to ignore,
%% e.g. message expiration messages from previously set up timers
%% that may or may not be still valid
args_policy_version,
%% used to discard outdated/superseded policy updates,
%% e.g. when policies are applied concurrently. See
%% https://github.com/rabbitmq/rabbitmq-server/issues/803 for one
%% example.
mirroring_policy_version = 0,
%% running | flow | idle
status,
%% true | false
single_active_consumer_on
}).
%%----------------------------------------------------------------------------
-define(STATISTICS_KEYS,
[messages_ready,
messages_unacknowledged,
messages,
reductions,
name,
policy,
operator_policy,
effective_policy_definition,
exclusive_consumer_pid,
exclusive_consumer_tag,
single_active_consumer_pid,
single_active_consumer_tag,
consumers,
consumer_utilisation,
consumer_capacity,
memory,
slave_pids,
synchronised_slave_pids,
recoverable_slaves,
state,
garbage_collection
]).
-define(CREATION_EVENT_KEYS,
[name,
type,
durable,
auto_delete,
arguments,
owner_pid,
exclusive,
user_who_performed_action
]).
-define(INFO_KEYS, [pid | ?CREATION_EVENT_KEYS ++ ?STATISTICS_KEYS -- [name, type]]).
%%----------------------------------------------------------------------------
-spec info_keys() -> rabbit_types:info_keys().
info_keys() -> ?INFO_KEYS ++ rabbit_backing_queue:info_keys().
statistics_keys() -> ?STATISTICS_KEYS ++ rabbit_backing_queue:info_keys().
%%----------------------------------------------------------------------------
init(Q) ->
process_flag(trap_exit, true),
?store_proc_name(amqqueue:get_name(Q)),
{ok, init_state(amqqueue:set_pid(Q, self())), hibernate,
{backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE},
?MODULE}.
init_state(Q) ->
SingleActiveConsumerOn = case rabbit_misc:table_lookup(amqqueue:get_arguments(Q), <<"x-single-active-consumer">>) of
{bool, true} -> true;
_ -> false
end,
State = #q{q = Q,
active_consumer = none,
has_had_consumers = false,
consumers = rabbit_queue_consumers:new(),
senders = pmon:new(delegate),
msg_id_to_channel = #{},
status = running,
args_policy_version = 0,
overflow = 'drop-head',
single_active_consumer_on = SingleActiveConsumerOn},
rabbit_event:init_stats_timer(State, #q.stats_timer).
init_it(Recover, From, State = #q{q = Q})
when ?amqqueue_exclusive_owner_is(Q, none) ->
init_it2(Recover, From, State);
%% You used to be able to declare an exclusive durable queue. Sadly we
%% need to still tidy up after that case, there could be the remnants
%% of one left over from an upgrade. So that's why we don't enforce
%% Recover = new here.
init_it(Recover, From, State = #q{q = Q0}) ->
Owner = amqqueue:get_exclusive_owner(Q0),
case rabbit_misc:is_process_alive(Owner) of
true -> erlang:monitor(process, Owner),
init_it2(Recover, From, State);
false -> #q{backing_queue = undefined,
backing_queue_state = undefined,
q = Q} = State,
send_reply(From, {owner_died, Q}),
BQ = backing_queue_module(Q),
{_, Terms} = recovery_status(Recover),
BQS = bq_init(BQ, Q, Terms),
%% Rely on terminate to delete the queue.
log_delete_exclusive(Owner, State),
{stop, {shutdown, missing_owner},
State#q{backing_queue = BQ, backing_queue_state = BQS}}
end.
init_it2(Recover, From, State = #q{q = Q,
backing_queue = undefined,
backing_queue_state = undefined}) ->
{Barrier, TermsOrNew} = recovery_status(Recover),
case rabbit_amqqueue:internal_declare(Q, Recover /= new) of
{Res, Q1}
when ?is_amqqueue(Q1) andalso
(Res == created orelse Res == existing) ->
case matches(Recover, Q, Q1) of
true ->
ok = file_handle_cache:register_callback(
rabbit_amqqueue, set_maximum_since_use, [self()]),
ok = rabbit_memory_monitor:register(
self(), {rabbit_amqqueue,
set_ram_duration_target, [self()]}),
BQ = backing_queue_module(Q1),
BQS = bq_init(BQ, Q, TermsOrNew),
send_reply(From, {new, Q}),
recovery_barrier(Barrier),
State1 = process_args_policy(
State#q{backing_queue = BQ,
backing_queue_state = BQS}),
notify_decorators(startup, State),
rabbit_event:notify(queue_created,
infos(?CREATION_EVENT_KEYS, State1)),
rabbit_event:if_enabled(State1, #q.stats_timer,
fun() -> emit_stats(State1) end),
noreply(State1);
false ->
{stop, normal, {existing, Q1}, State}
end;
Err ->
{stop, normal, Err, State}
end.
recovery_status(new) -> {no_barrier, new};
recovery_status({Recover, Terms}) -> {Recover, Terms}.
send_reply(none, _Q) -> ok;
send_reply(From, Q) -> gen_server2:reply(From, Q).
matches(new, Q1, Q2) ->
%% i.e. not policy
amqqueue:get_name(Q1) =:= amqqueue:get_name(Q2) andalso
amqqueue:is_durable(Q1) =:= amqqueue:is_durable(Q2) andalso
amqqueue:is_auto_delete(Q1) =:= amqqueue:is_auto_delete(Q2) andalso
amqqueue:get_exclusive_owner(Q1) =:= amqqueue:get_exclusive_owner(Q2) andalso
amqqueue:get_arguments(Q1) =:= amqqueue:get_arguments(Q2) andalso
amqqueue:get_pid(Q1) =:= amqqueue:get_pid(Q2) andalso
amqqueue:get_slave_pids(Q1) =:= amqqueue:get_slave_pids(Q2);
%% FIXME: Should v1 vs. v2 of the same record match?
matches(_, Q, Q) -> true;
matches(_, _Q, _Q1) -> false.
recovery_barrier(no_barrier) ->
ok;
recovery_barrier(BarrierPid) ->
MRef = erlang:monitor(process, BarrierPid),
receive
{BarrierPid, go} -> erlang:demonitor(MRef, [flush]);
{'DOWN', MRef, process, _, _} -> ok
end.
-spec init_with_backing_queue_state
(amqqueue:amqqueue(), atom(), tuple(), any(),
[rabbit_types:delivery()], pmon:pmon(), map()) ->
#q{}.
init_with_backing_queue_state(Q, BQ, BQS,
RateTRef, Deliveries, Senders, MTC) ->
Owner = amqqueue:get_exclusive_owner(Q),
_ = case Owner of
none -> ok;
_ -> erlang:monitor(process, Owner)
end,
State = init_state(Q),
State1 = State#q{backing_queue = BQ,
backing_queue_state = BQS,
rate_timer_ref = RateTRef,
senders = Senders,
msg_id_to_channel = MTC},
State2 = process_args_policy(State1),
State3 = lists:foldl(fun (Delivery, StateN) ->
maybe_deliver_or_enqueue(Delivery, true, StateN)
end, State2, Deliveries),
notify_decorators(startup, State3),
State3.
terminate(shutdown = R, State = #q{backing_queue = BQ, q = Q0}) ->
rabbit_core_metrics:queue_deleted(qname(State)),
terminate_shutdown(
fun (BQS) ->
_ = update_state(stopped, Q0),
BQ:terminate(R, BQS)
end, State);
terminate({shutdown, missing_owner} = Reason, State) ->
%% if the owner was missing then there will be no queue, so don't emit stats
terminate_shutdown(terminate_delete(false, Reason, State), State);
terminate({shutdown, _} = R, State = #q{backing_queue = BQ}) ->
rabbit_core_metrics:queue_deleted(qname(State)),
terminate_shutdown(fun (BQS) -> BQ:terminate(R, BQS) end, State);
terminate(normal, State = #q{status = {terminated_by, auto_delete}}) ->
%% auto_delete case
%% To increase performance we want to avoid a mnesia_sync:sync call
%% after every transaction, as we could be deleting simultaneously
%% thousands of queues. A optimisation introduced by server#1513
%% needs to be reverted by this case, avoiding to guard the delete
%% operation on `rabbit_durable_queue`
terminate_shutdown(terminate_delete(true, auto_delete, State), State);
terminate(normal, State) -> %% delete case
terminate_shutdown(terminate_delete(true, normal, State), State);
%% If we crashed don't try to clean up the BQS, probably best to leave it.
terminate(_Reason, State = #q{q = Q}) ->
terminate_shutdown(fun (BQS) ->
Q2 = amqqueue:set_state(Q, crashed),
rabbit_amqqueue:store_queue(Q2),
BQS
end, State).
terminate_delete(EmitStats, Reason0,
State = #q{q = Q,
backing_queue = BQ,
status = Status}) ->
QName = amqqueue:get_name(Q),
ActingUser = terminated_by(Status),
fun (BQS) ->
Reason = case Reason0 of
auto_delete -> normal;
Any -> Any
end,
BQS1 = BQ:delete_and_terminate(Reason, BQS),
if EmitStats -> rabbit_event:if_enabled(State, #q.stats_timer,
fun() -> emit_stats(State) end);
true -> ok
end,
%% This try-catch block transforms throws to errors since throws are not
%% logged.
try
%% don't care if the internal delete doesn't return 'ok'.
rabbit_amqqueue:internal_delete(QName, ActingUser, Reason0)
catch
{error, ReasonE} -> error(ReasonE)
end,
BQS1
end.
terminated_by({terminated_by, auto_delete}) ->
?INTERNAL_USER;
terminated_by({terminated_by, ActingUser}) ->
ActingUser;
terminated_by(_) ->
?INTERNAL_USER.
terminate_shutdown(Fun, #q{status = Status} = State) ->
ActingUser = terminated_by(Status),
State1 = #q{backing_queue_state = BQS, consumers = Consumers} =
lists:foldl(fun (F, S) -> F(S) end, State,
[fun stop_sync_timer/1,
fun stop_rate_timer/1,
fun stop_expiry_timer/1,
fun stop_ttl_timer/1]),
case BQS of
undefined -> State1;
_ -> ok = rabbit_memory_monitor:deregister(self()),
QName = qname(State),
notify_decorators(shutdown, State),
[emit_consumer_deleted(Ch, CTag, QName, ActingUser) ||
{Ch, CTag, _, _, _, _, _, _} <-
rabbit_queue_consumers:all(Consumers)],
State1#q{backing_queue_state = Fun(BQS)}
end.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%----------------------------------------------------------------------------
maybe_notify_decorators(false, State) -> State;
maybe_notify_decorators(true, State) -> notify_decorators(State), State.
notify_decorators(Event, State) ->
_ = decorator_callback(qname(State), Event, []),
ok.
notify_decorators(State = #q{consumers = Consumers,
backing_queue = BQ,
backing_queue_state = BQS}) ->
P = rabbit_queue_consumers:max_active_priority(Consumers),
_ = decorator_callback(qname(State), consumer_state_changed,
[P, BQ:is_empty(BQS)]),
ok.
decorator_callback(QName, F, A) ->
%% Look up again in case policy and hence decorators have changed
case rabbit_amqqueue:lookup(QName) of
{ok, Q} ->
Ds = amqqueue:get_decorators(Q),
[ok = apply(M, F, [Q|A]) || M <- rabbit_queue_decorator:select(Ds)];
{error, not_found} ->
ok
end.
bq_init(BQ, Q, Recover) ->
Self = self(),
BQ:init(Q, Recover,
fun (Mod, Fun) ->
rabbit_amqqueue:run_backing_queue(Self, Mod, Fun)
end).
process_args_policy(State = #q{q = Q,
args_policy_version = N}) ->
ArgsTable =
[{<<"expires">>, fun res_min/2, fun init_exp/2},
{<<"dead-letter-exchange">>, fun res_arg/2, fun init_dlx/2},
{<<"dead-letter-routing-key">>, fun res_arg/2, fun init_dlx_rkey/2},
{<<"message-ttl">>, fun res_min/2, fun init_ttl/2},
{<<"max-length">>, fun res_min/2, fun init_max_length/2},
{<<"max-length-bytes">>, fun res_min/2, fun init_max_bytes/2},
{<<"overflow">>, fun res_arg/2, fun init_overflow/2},
{<<"queue-mode">>, fun res_arg/2, fun init_queue_mode/2},
{<<"queue-version">>, fun res_arg/2, fun init_queue_version/2}],
drop_expired_msgs(
lists:foldl(fun({Name, Resolve, Fun}, StateN) ->
Fun(rabbit_queue_type_util:args_policy_lookup(Name, Resolve, Q), StateN)
end, State#q{args_policy_version = N + 1}, ArgsTable)).
res_arg(_PolVal, ArgVal) -> ArgVal.
res_min(PolVal, ArgVal) -> erlang:min(PolVal, ArgVal).
%% In both these we init with the undefined variant first to stop any
%% existing timer, then start a new one which may fire after a
%% different time.
init_exp(undefined, State) -> stop_expiry_timer(State#q{expires = undefined});
init_exp(Expires, State) -> State1 = init_exp(undefined, State),
ensure_expiry_timer(State1#q{expires = Expires}).
init_ttl(undefined, State) -> stop_ttl_timer(State#q{ttl = undefined});
init_ttl(TTL, State) -> (init_ttl(undefined, State))#q{ttl = TTL}.
init_dlx(undefined, State) ->
State#q{dlx = undefined};
init_dlx(DLX, State = #q{q = Q}) ->
QName = amqqueue:get_name(Q),
State#q{dlx = rabbit_misc:r(QName, exchange, DLX)}.
init_dlx_rkey(RoutingKey, State) -> State#q{dlx_routing_key = RoutingKey}.
init_max_length(MaxLen, State) ->
{_Dropped, State1} = maybe_drop_head(State#q{max_length = MaxLen}),
State1.
init_max_bytes(MaxBytes, State) ->
{_Dropped, State1} = maybe_drop_head(State#q{max_bytes = MaxBytes}),
State1.
%% Reset overflow to default 'drop-head' value if it's undefined.
init_overflow(undefined, #q{overflow = 'drop-head'} = State) ->
State;
init_overflow(undefined, State) ->
{_Dropped, State1} = maybe_drop_head(State#q{overflow = 'drop-head'}),
State1;
init_overflow(Overflow, State) ->
OverflowVal = binary_to_existing_atom(Overflow, utf8),
case OverflowVal of
'drop-head' ->
{_Dropped, State1} = maybe_drop_head(State#q{overflow = OverflowVal}),
State1;
_ ->
State#q{overflow = OverflowVal}
end.
init_queue_mode(undefined, State) ->
State;
init_queue_mode(Mode, State = #q {backing_queue = BQ,
backing_queue_state = BQS}) ->
BQS1 = BQ:set_queue_mode(binary_to_existing_atom(Mode, utf8), BQS),
State#q{backing_queue_state = BQS1}.
init_queue_version(Version0, State = #q {backing_queue = BQ,
backing_queue_state = BQS}) ->
%% When the version is undefined we use the default version 1.
%% We want to BQ:set_queue_version in all cases because a v2
%% policy might have been deleted, for example, and we want
%% the queue to go back to v1.
Version = case Version0 of
undefined -> rabbit_misc:get_env(rabbit, classic_queue_default_version, 1);
_ -> Version0
end,
BQS1 = BQ:set_queue_version(Version, BQS),
State#q{backing_queue_state = BQS1}.
reply(Reply, NewState) ->
{NewState1, Timeout} = next_state(NewState),
{reply, Reply, ensure_stats_timer(ensure_rate_timer(NewState1)), Timeout}.
noreply(NewState) ->
{NewState1, Timeout} = next_state(NewState),
{noreply, ensure_stats_timer(ensure_rate_timer(NewState1)), Timeout}.
next_state(State = #q{q = Q,
backing_queue = BQ,
backing_queue_state = BQS,
msg_id_to_channel = MTC}) ->
assert_invariant(State),
{MsgIds, BQS1} = BQ:drain_confirmed(BQS),
MTC1 = confirm_messages(MsgIds, MTC, amqqueue:get_name(Q)),
State1 = State#q{backing_queue_state = BQS1, msg_id_to_channel = MTC1},
case BQ:needs_timeout(BQS1) of
false -> {stop_sync_timer(State1), hibernate };
idle -> {stop_sync_timer(State1), ?SYNC_INTERVAL};
timed -> {ensure_sync_timer(State1), 0 }
end.
backing_queue_module(Q) ->
case rabbit_mirror_queue_misc:is_mirrored(Q) of
false -> {ok, BQM} = application:get_env(backing_queue_module),
BQM;
true -> rabbit_mirror_queue_master
end.
ensure_sync_timer(State) ->
rabbit_misc:ensure_timer(State, #q.sync_timer_ref,
?SYNC_INTERVAL, sync_timeout).
stop_sync_timer(State) -> rabbit_misc:stop_timer(State, #q.sync_timer_ref).
ensure_rate_timer(State) ->
rabbit_misc:ensure_timer(State, #q.rate_timer_ref,
?RAM_DURATION_UPDATE_INTERVAL,
update_ram_duration).
stop_rate_timer(State) -> rabbit_misc:stop_timer(State, #q.rate_timer_ref).
%% We wish to expire only when there are no consumers *and* the expiry
%% hasn't been refreshed (by queue.declare or basic.get) for the
%% configured period.
ensure_expiry_timer(State = #q{expires = undefined}) ->
State;
ensure_expiry_timer(State = #q{expires = Expires,
args_policy_version = Version}) ->
case is_unused(State) of
true -> NewState = stop_expiry_timer(State),
rabbit_misc:ensure_timer(NewState, #q.expiry_timer_ref,
Expires, {maybe_expire, Version});
false -> State
end.
stop_expiry_timer(State) -> rabbit_misc:stop_timer(State, #q.expiry_timer_ref).
ensure_ttl_timer(undefined, State) ->
State;
ensure_ttl_timer(Expiry, State = #q{ttl_timer_ref = undefined,
args_policy_version = Version}) ->
After = (case Expiry - os:system_time(micro_seconds) of
V when V > 0 -> V + 999; %% always fire later
_ -> 0
end) div 1000,
TRef = rabbit_misc:send_after(After, self(), {drop_expired, Version}),
State#q{ttl_timer_ref = TRef, ttl_timer_expiry = Expiry};
ensure_ttl_timer(Expiry, State = #q{ttl_timer_ref = TRef,
ttl_timer_expiry = TExpiry})
when Expiry + 1000 < TExpiry ->
rabbit_misc:cancel_timer(TRef),
ensure_ttl_timer(Expiry, State#q{ttl_timer_ref = undefined});
ensure_ttl_timer(_Expiry, State) ->
State.
stop_ttl_timer(State) -> rabbit_misc:stop_timer(State, #q.ttl_timer_ref).
ensure_stats_timer(State) ->
rabbit_event:ensure_stats_timer(State, #q.stats_timer, emit_stats).
assert_invariant(#q{single_active_consumer_on = true}) ->
%% queue may contain messages and have available consumers with exclusive consumer
ok;
assert_invariant(State = #q{consumers = Consumers, single_active_consumer_on = false}) ->
true = (rabbit_queue_consumers:inactive(Consumers) orelse is_empty(State)).
is_empty(#q{backing_queue = BQ, backing_queue_state = BQS}) -> BQ:is_empty(BQS).
maybe_send_drained(WasEmpty, #q{q = Q} = State) ->
case (not WasEmpty) andalso is_empty(State) of
true -> notify_decorators(State),
rabbit_queue_consumers:send_drained(amqqueue:get_name(Q));
false -> ok
end,
State.
confirm_messages([], MTC, _QName) ->
MTC;
confirm_messages(MsgIds, MTC, QName) ->
{CMs, MTC1} =
lists:foldl(
fun(MsgId, {CMs, MTC0}) ->
case maps:get(MsgId, MTC0, none) of
none ->
{CMs, MTC0};
{SenderPid, MsgSeqNo} ->
{maps:update_with(SenderPid,
fun(MsgSeqNos) ->
[MsgSeqNo | MsgSeqNos]
end,
[MsgSeqNo],
CMs),
maps:remove(MsgId, MTC0)}
end
end, {#{}, MTC}, MsgIds),
maps:fold(
fun(Pid, MsgSeqNos, _) ->
confirm_to_sender(Pid, QName, MsgSeqNos)
end,
ok,
CMs),
MTC1.
send_or_record_confirm(#delivery{confirm = false}, State) ->
{never, State};
send_or_record_confirm(#delivery{confirm = true,
sender = SenderPid,
msg_seq_no = MsgSeqNo,
message = #basic_message {
is_persistent = true,
id = MsgId}},
State = #q{q = Q,
msg_id_to_channel = MTC})
when ?amqqueue_is_durable(Q) ->
MTC1 = maps:put(MsgId, {SenderPid, MsgSeqNo}, MTC),
{eventually, State#q{msg_id_to_channel = MTC1}};
send_or_record_confirm(#delivery{confirm = true,
sender = SenderPid,
msg_seq_no = MsgSeqNo},
#q{q = Q} = State) ->
confirm_to_sender(SenderPid, amqqueue:get_name(Q), [MsgSeqNo]),
{immediately, State}.
%% This feature was used by `rabbit_amqqueue_process` and
%% `rabbit_mirror_queue_slave` up-to and including RabbitMQ 3.7.x. It is
%% unused in 3.8.x and thus deprecated. We keep it to support in-place
%% upgrades to 3.8.x (i.e. mixed-version clusters), but it is a no-op
%% starting with that version.
send_mandatory(#delivery{mandatory = false}) ->
ok;
send_mandatory(#delivery{mandatory = true,
sender = SenderPid,
msg_seq_no = MsgSeqNo}) ->
gen_server2:cast(SenderPid, {mandatory_received, MsgSeqNo}).
discard(#delivery{confirm = Confirm,
sender = SenderPid,
flow = Flow,
message = #basic_message{id = MsgId}}, BQ, BQS, MTC, QName) ->
MTC1 = case Confirm of
true -> confirm_messages([MsgId], MTC, QName);
false -> MTC
end,
BQS1 = BQ:discard(MsgId, SenderPid, Flow, BQS),
{BQS1, MTC1}.
run_message_queue(State) -> run_message_queue(false, State).
run_message_queue(ActiveConsumersChanged, State) ->
case is_empty(State) of
true -> maybe_notify_decorators(ActiveConsumersChanged, State);
false -> case rabbit_queue_consumers:deliver(
fun(AckRequired) -> fetch(AckRequired, State) end,
qname(State), State#q.consumers,
State#q.single_active_consumer_on, State#q.active_consumer) of
{delivered, ActiveConsumersChanged1, State1, Consumers} ->
run_message_queue(
ActiveConsumersChanged or ActiveConsumersChanged1,
State1#q{consumers = Consumers});
{undelivered, ActiveConsumersChanged1, Consumers} ->
maybe_notify_decorators(
ActiveConsumersChanged or ActiveConsumersChanged1,
State#q{consumers = Consumers})
end
end.
attempt_delivery(Delivery = #delivery{sender = SenderPid,
flow = Flow,
message = Message},
Props, Delivered, State = #q{q = Q,
backing_queue = BQ,
backing_queue_state = BQS,
msg_id_to_channel = MTC}) ->
case rabbit_queue_consumers:deliver(
fun (true) -> {AckTag, BQS1} =
BQ:publish_delivered(
Message, Props, SenderPid, Flow, BQS),
{{Message, Delivered, AckTag}, {BQS1, MTC}};
(false) -> {{Message, Delivered, undefined},
discard(Delivery, BQ, BQS, MTC, amqqueue:get_name(Q))}
end, qname(State), State#q.consumers, State#q.single_active_consumer_on, State#q.active_consumer) of
{delivered, ActiveConsumersChanged, {BQS1, MTC1}, Consumers} ->
{delivered, maybe_notify_decorators(
ActiveConsumersChanged,
State#q{backing_queue_state = BQS1,
msg_id_to_channel = MTC1,
consumers = Consumers})};
{undelivered, ActiveConsumersChanged, Consumers} ->
{undelivered, maybe_notify_decorators(
ActiveConsumersChanged,
State#q{consumers = Consumers})}
end.
maybe_deliver_or_enqueue(Delivery = #delivery{message = Message},
Delivered,
State = #q{overflow = Overflow,
backing_queue = BQ,
backing_queue_state = BQS,
dlx = DLX,
dlx_routing_key = RK}) ->
send_mandatory(Delivery), %% must do this before confirms
case {will_overflow(Delivery, State), Overflow} of
{true, 'reject-publish'} ->
%% Drop publish and nack to publisher
send_reject_publish(Delivery, Delivered, State);
{true, 'reject-publish-dlx'} ->
%% Publish to DLX
_ = with_dlx(
DLX,
fun (X) ->
rabbit_global_counters:messages_dead_lettered(maxlen, rabbit_classic_queue,
at_most_once, 1),
QName = qname(State),
rabbit_dead_letter:publish(Message, maxlen, X, RK, QName)
end,
fun () -> rabbit_global_counters:messages_dead_lettered(maxlen, rabbit_classic_queue,
disabled, 1)
end),
%% Drop publish and nack to publisher
send_reject_publish(Delivery, Delivered, State);
_ ->
{IsDuplicate, BQS1} = BQ:is_duplicate(Message, BQS),
State1 = State#q{backing_queue_state = BQS1},
case IsDuplicate of
true -> State1;
{true, drop} -> State1;
%% Drop publish and nack to publisher
{true, reject} ->
send_reject_publish(Delivery, Delivered, State1);
%% Enqueue and maybe drop head later
false ->
deliver_or_enqueue(Delivery, Delivered, State1)
end
end.
deliver_or_enqueue(Delivery = #delivery{message = Message,
sender = SenderPid,
flow = Flow},
Delivered,
State = #q{q = Q, backing_queue = BQ}) ->
{Confirm, State1} = send_or_record_confirm(Delivery, State),
Props = message_properties(Message, Confirm, State1),
case attempt_delivery(Delivery, Props, Delivered, State1) of
{delivered, State2} ->
State2;
%% The next one is an optimisation
{undelivered, State2 = #q{ttl = 0, dlx = undefined,
backing_queue_state = BQS,
msg_id_to_channel = MTC}} ->
rabbit_global_counters:messages_dead_lettered(expired, rabbit_classic_queue,
disabled, 1),
{BQS1, MTC1} = discard(Delivery, BQ, BQS, MTC, amqqueue:get_name(Q)),
State2#q{backing_queue_state = BQS1, msg_id_to_channel = MTC1};
{undelivered, State2 = #q{backing_queue_state = BQS}} ->
BQS1 = BQ:publish(Message, Props, Delivered, SenderPid, Flow, BQS),
{Dropped, State3 = #q{backing_queue_state = BQS2}} =
maybe_drop_head(State2#q{backing_queue_state = BQS1}),
QLen = BQ:len(BQS2),
%% optimisation: it would be perfectly safe to always
%% invoke drop_expired_msgs here, but that is expensive so
%% we only do that if a new message that might have an
%% expiry ends up at the head of the queue. If the head
%% remains unchanged, or if the newly published message
%% has no expiry and becomes the head of the queue then
%% the call is unnecessary.
case {Dropped, QLen =:= 1, Props#message_properties.expiry} of
{false, false, _} -> State3;
{true, true, undefined} -> State3;
{_, _, _} -> drop_expired_msgs(State3)
end
end.
maybe_drop_head(State = #q{max_length = undefined,
max_bytes = undefined}) ->
{false, State};
maybe_drop_head(State = #q{overflow = 'reject-publish'}) ->
{false, State};
maybe_drop_head(State = #q{overflow = 'reject-publish-dlx'}) ->
{false, State};
maybe_drop_head(State = #q{overflow = 'drop-head'}) ->
maybe_drop_head(false, State).
maybe_drop_head(AlreadyDropped, State = #q{backing_queue = BQ,
backing_queue_state = BQS}) ->
case over_max_length(State) of
true ->
maybe_drop_head(true,
with_dlx(
State#q.dlx,
fun (X) -> dead_letter_maxlen_msg(X, State) end,
fun () ->
rabbit_global_counters:messages_dead_lettered(maxlen,
rabbit_classic_queue,
disabled, 1),
{_, BQS1} = BQ:drop(false, BQS),
State#q{backing_queue_state = BQS1}
end));
false ->
{AlreadyDropped, State}
end.
send_reject_publish(#delivery{confirm = true,
sender = SenderPid,
flow = Flow,
msg_seq_no = MsgSeqNo,
message = #basic_message{id = MsgId}},
_Delivered,
State = #q{ q = Q,
backing_queue = BQ,
backing_queue_state = BQS,
msg_id_to_channel = MTC}) ->
ok = rabbit_classic_queue:send_rejection(SenderPid,
amqqueue:get_name(Q), MsgSeqNo),
MTC1 = maps:remove(MsgId, MTC),
BQS1 = BQ:discard(MsgId, SenderPid, Flow, BQS),
State#q{ backing_queue_state = BQS1, msg_id_to_channel = MTC1 };
send_reject_publish(#delivery{confirm = false},
_Delivered, State) ->
State.
will_overflow(_, #q{max_length = undefined,
max_bytes = undefined}) -> false;
will_overflow(#delivery{message = Message},
#q{max_length = MaxLen,
max_bytes = MaxBytes,
backing_queue = BQ,
backing_queue_state = BQS}) ->
ExpectedQueueLength = BQ:len(BQS) + 1,
#basic_message{content = #content{payload_fragments_rev = PFR}} = Message,
MessageSize = iolist_size(PFR),
ExpectedQueueSizeBytes = BQ:info(message_bytes_ready, BQS) + MessageSize,
ExpectedQueueLength > MaxLen orelse ExpectedQueueSizeBytes > MaxBytes.
over_max_length(#q{max_length = MaxLen,
max_bytes = MaxBytes,
backing_queue = BQ,
backing_queue_state = BQS}) ->
BQ:len(BQS) > MaxLen orelse BQ:info(message_bytes_ready, BQS) > MaxBytes.
requeue_and_run(AckTags, State = #q{backing_queue = BQ,
backing_queue_state = BQS}) ->
WasEmpty = BQ:is_empty(BQS),
{_MsgIds, BQS1} = BQ:requeue(AckTags, BQS),
{_Dropped, State1} = maybe_drop_head(State#q{backing_queue_state = BQS1}),
run_message_queue(maybe_send_drained(WasEmpty, drop_expired_msgs(State1))).
fetch(AckRequired, State = #q{backing_queue = BQ,
backing_queue_state = BQS}) ->
{Result, BQS1} = BQ:fetch(AckRequired, BQS),
State1 = drop_expired_msgs(State#q{backing_queue_state = BQS1}),
{Result, maybe_send_drained(Result =:= empty, State1)}.
ack(AckTags, ChPid, State) ->
subtract_acks(ChPid, AckTags, State,
fun (State1 = #q{backing_queue = BQ,
backing_queue_state = BQS}) ->
{_Guids, BQS1} = BQ:ack(AckTags, BQS),
State1#q{backing_queue_state = BQS1}
end).
requeue(AckTags, ChPid, State) ->
subtract_acks(ChPid, AckTags, State,
fun (State1) -> requeue_and_run(AckTags, State1) end).
possibly_unblock(Update, ChPid, State = #q{consumers = Consumers}) ->
case rabbit_queue_consumers:possibly_unblock(Update, ChPid, Consumers) of
unchanged -> State;
{unblocked, Consumers1} -> State1 = State#q{consumers = Consumers1},
run_message_queue(true, State1)
end.
should_auto_delete(#q{q = Q})
when not ?amqqueue_is_auto_delete(Q) -> false;
should_auto_delete(#q{has_had_consumers = false}) -> false;
should_auto_delete(State) -> is_unused(State).
handle_ch_down(DownPid, State = #q{consumers = Consumers,
active_consumer = Holder,
single_active_consumer_on = SingleActiveConsumerOn,
senders = Senders}) ->
State1 = State#q{senders = case pmon:is_monitored(DownPid, Senders) of
false ->
Senders;
true ->
%% A rabbit_channel process died. Here credit_flow will take care
%% of cleaning up the rabbit_amqqueue_process process dictionary
%% with regards to the credit we were tracking for the channel
%% process. See handle_cast({deliver, Deliver, ...}, State) in this
%% module. In that cast function we process deliveries from the
%% channel, which means we credit_flow:ack/1 said
%% messages. credit_flow:ack'ing messages means we are increasing
%% a counter to know when we need to send MoreCreditAfter. Since
%% the process died, the credit_flow flow module will clean up
%% that for us.
credit_flow:peer_down(DownPid),
pmon:demonitor(DownPid, Senders)
end},
case rabbit_queue_consumers:erase_ch(DownPid, Consumers) of
not_found ->
{ok, State1};
{ChAckTags, ChCTags, Consumers1} ->
QName = qname(State1),
[emit_consumer_deleted(DownPid, CTag, QName, ?INTERNAL_USER) || CTag <- ChCTags],
Holder1 = new_single_active_consumer_after_channel_down(DownPid, Holder, SingleActiveConsumerOn, Consumers1),
State2 = State1#q{consumers = Consumers1,
active_consumer = Holder1},
maybe_notify_consumer_updated(State2, Holder, Holder1),
notify_decorators(State2),
case should_auto_delete(State2) of
true ->
log_auto_delete(
io_lib:format(
"because all of its consumers (~tp) were on a channel that was closed",
[length(ChCTags)]),
State),
{stop, State2};
false -> {ok, requeue_and_run(ChAckTags,
ensure_expiry_timer(State2))}
end
end.
new_single_active_consumer_after_channel_down(DownChPid, CurrentSingleActiveConsumer, _SingleActiveConsumerIsOn = true, Consumers) ->
case CurrentSingleActiveConsumer of
{DownChPid, _} ->
% the single active consumer is on the down channel, we have to replace it
case rabbit_queue_consumers:get_consumer(Consumers) of
undefined -> none;
Consumer -> Consumer
end;
_ ->
CurrentSingleActiveConsumer
end;
new_single_active_consumer_after_channel_down(DownChPid, CurrentSingleActiveConsumer, _SingleActiveConsumerIsOn = false, _Consumers) ->
case CurrentSingleActiveConsumer of
{DownChPid, _} -> none;
Other -> Other
end.
check_exclusive_access({_ChPid, _ConsumerTag}, _ExclusiveConsume, _State) ->
in_use;
check_exclusive_access(none, false, _State) ->
ok;
check_exclusive_access(none, true, State) ->
case is_unused(State) of
true -> ok;
false -> in_use
end.
is_unused(_State) -> rabbit_queue_consumers:count() == 0.
maybe_send_reply(_ChPid, undefined) -> ok;
maybe_send_reply(ChPid, Msg) -> ok = rabbit_channel:send_command(ChPid, Msg).
qname(#q{q = Q}) -> amqqueue:get_name(Q).
backing_queue_timeout(State = #q{backing_queue = BQ,
backing_queue_state = BQS}) ->
State#q{backing_queue_state = BQ:timeout(BQS)}.
subtract_acks(ChPid, AckTags, State = #q{consumers = Consumers}, Fun) ->
case rabbit_queue_consumers:subtract_acks(ChPid, AckTags, Consumers) of
not_found -> State;
unchanged -> Fun(State);
{unblocked, Consumers1} -> State1 = State#q{consumers = Consumers1},
run_message_queue(true, Fun(State1))
end.
message_properties(Message = #basic_message{content = Content},
Confirm, #q{ttl = TTL}) ->
#content{payload_fragments_rev = PFR} = Content,
#message_properties{expiry = calculate_msg_expiry(Message, TTL),
needs_confirming = Confirm == eventually,
size = iolist_size(PFR)}.
calculate_msg_expiry(#basic_message{content = Content}, TTL) ->
#content{properties = Props} =
rabbit_binary_parser:ensure_content_decoded(Content),
%% We assert that the expiration must be valid - we check in the channel.
{ok, MsgTTL} = rabbit_basic:parse_expiration(Props),
case lists:min([TTL, MsgTTL]) of
undefined -> undefined;
T -> os:system_time(micro_seconds) + T * 1000
end.
%% Logically this function should invoke maybe_send_drained/2.
%% However, that is expensive. Since some frequent callers of
%% drop_expired_msgs/1, in particular deliver_or_enqueue/3, cannot
%% possibly cause the queue to become empty, we push the
%% responsibility to the callers. So be cautious when adding new ones.
drop_expired_msgs(State) ->