-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathrabbit_channel.erl
2789 lines (2509 loc) · 119 KB
/
rabbit_channel.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-2024 Broadcom. All Rights Reserved. The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. All rights reserved.
%%
-module(rabbit_channel).
%% rabbit_channel processes represent an AMQP 0-9-1 channels.
%%
%% Connections parse protocol frames coming from clients and
%% dispatch them to channel processes.
%% Channels are responsible for implementing the logic behind
%% the various protocol methods, involving other processes as
%% needed:
%%
%% * Routing messages (using functions in various exchange type
%% modules) to queue processes.
%% * Managing queues, exchanges, and bindings.
%% * Keeping track of consumers
%% * Keeping track of unacknowledged deliveries to consumers
%% * Keeping track of publisher confirms
%% * Transaction management
%% * Authorisation (enforcing permissions)
%% * Publishing trace events if tracing is enabled
%%
%% Every channel has a number of dependent processes:
%%
%% * A writer which is responsible for sending frames to clients.
%% * A limiter which controls how many messages can be delivered
%% to consumers according to active QoS prefetch and internal
%% flow control logic.
%%
%% Channels are also aware of their connection's queue collector.
%% When a queue is declared as exclusive on a channel, the channel
%% will notify queue collector of that queue.
-include_lib("rabbit_common/include/rabbit_framing.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
-include_lib("rabbit_common/include/rabbit_misc.hrl").
-include("amqqueue.hrl").
-behaviour(gen_server2).
-export([start_link/11, start_link/12, do/2, do/3, do_flow/3, flush/1, shutdown/1]).
-export([send_command/2]).
-export([list/0, info_keys/0, info/1, info/2, info_all/0, info_all/1,
emit_info_all/4, info_local/1]).
-export([refresh_config_local/0, ready_for_close/1]).
-export([refresh_interceptors/0]).
-export([force_event_refresh/1]).
-export([update_user_state/2]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2, handle_pre_hibernate/1, handle_post_hibernate/1,
prioritise_call/4, prioritise_cast/3, prioritise_info/3,
format_message_queue/2]).
%% Internal
-export([list_local/0, emit_info_local/3, deliver_reply_local/3]).
-export([get_vhost/1, get_user/1]).
%% For testing
-export([build_topic_variable_map/3]).
-export([list_queue_states/1]).
%% Mgmt HTTP API refactor
-export([handle_method/6,
binding_action/4]).
-import(rabbit_misc, [maps_put_truthy/3]).
-record(conf, {
%% starting | running | flow | closing
state,
%% same as reader's protocol. Used when instantiating
%% (protocol) exceptions.
protocol,
%% channel number
channel,
%% reader process
reader_pid,
%% writer process
writer_pid,
%%
conn_pid,
%% same as reader's name, see #v1.name
%% in rabbit_reader
conn_name,
%% same as #v1.user in the reader, used in
%% authorisation checks
user,
virtual_host,
%% when queue.bind's queue field is empty,
%% this name will be used instead
most_recently_declared_queue,
%% when a queue is declared as exclusive, queue
%% collector must be notified.
%% see rabbit_queue_collector for more info.
queue_collector_pid,
%% same as capabilities in the reader
capabilities,
trace_state :: rabbit_trace:state(),
consumer_prefetch,
consumer_timeout,
authz_context,
max_consumers, % taken from rabbit.consumer_max_per_channel
%% defines how ofter gc will be executed
writer_gc_threshold
}).
-record(pending_ack, {
%% delivery identifier used by clients
%% to acknowledge and reject deliveries
delivery_tag,
%% consumer tag
tag,
delivered_at :: integer(),
%% queue name
queue,
%% message ID used by queue and message store implementations
msg_id
}).
-record(ch, {cfg :: #conf{},
%% limiter state, see rabbit_limiter
limiter,
%% none | {Msgs, Acks} | committing | failed |
tx,
%% (consumer) delivery tag sequence
next_tag,
%% messages pending consumer acknowledgement
unacked_message_q,
%% queue processes are monitored to update
%% queue names
queue_monitors,
%% a map of consumer tags to
%% consumer details: #amqqueue record, acknowledgement mode,
%% consumer exclusivity, etc
consumer_mapping,
%% a map of queue names to consumer tag lists
queue_consumers,
%% timer used to emit statistics
stats_timer,
%% are publisher confirms enabled for this channel?
confirm_enabled,
%% publisher confirm delivery tag sequence
publish_seqno,
%% an unconfirmed_messages data structure used to track unconfirmed
%% (to publishers) messages
unconfirmed,
%% a list of tags for published messages that were
%% delivered but are yet to be confirmed to the client
confirmed,
%% a list of tags for published messages that were
%% rejected but are yet to be sent to the client
rejected,
%% used by "one shot RPC" (amq.
reply_consumer :: none | {rabbit_types:ctag(), binary(), binary()},
delivery_flow, %% Deprecated since removal of CMQ in 4.0
interceptor_state,
queue_states,
tick_timer,
publishing_mode = false :: boolean()
}).
-define(QUEUE, lqueue).
-define(MAX_PERMISSION_CACHE_SIZE, 12).
-define(REFRESH_TIMEOUT, 15000).
-define(STATISTICS_KEYS,
[reductions,
pid,
transactional,
confirm,
consumer_count,
messages_unacknowledged,
messages_unconfirmed,
messages_uncommitted,
acks_uncommitted,
pending_raft_commands,
prefetch_count,
global_prefetch_count,
state,
garbage_collection]).
-define(CREATION_EVENT_KEYS,
[pid,
name,
connection,
number,
user,
vhost,
user_who_performed_action]).
-define(INFO_KEYS, ?CREATION_EVENT_KEYS ++ ?STATISTICS_KEYS -- [pid]).
-define(INCR_STATS(Type, Key, Inc, Measure, State),
case rabbit_event:stats_level(State, #ch.stats_timer) of
fine ->
rabbit_core_metrics:channel_stats(Type, Measure, {self(), Key}, Inc),
%% Keys in the process dictionary are used to clean up the core metrics
put({Type, Key}, none);
_ ->
ok
end).
-define(INCR_STATS(Type, Key, Inc, Measure),
begin
rabbit_core_metrics:channel_stats(Type, Measure, {self(), Key}, Inc),
%% Keys in the process dictionary are used to clean up the core metrics
put({Type, Key}, none)
end).
%%----------------------------------------------------------------------------
-export_type([channel_number/0]).
-type channel_number() :: rabbit_types:channel_number().
-export_type([channel/0]).
-type channel() :: #ch{}.
%%----------------------------------------------------------------------------
-rabbit_deprecated_feature(
{global_qos,
#{deprecation_phase => permitted_by_default,
doc_url => "https://blog.rabbitmq.com/posts/2021/08/4.0-deprecation-announcements/#removal-of-global-qos"
}}).
-spec start_link
(channel_number(), pid(), pid(), pid(), string(), rabbit_types:protocol(),
rabbit_types:user(), rabbit_types:vhost(), rabbit_framing:amqp_table(),
pid(), pid()) ->
rabbit_types:ok_pid_or_error().
start_link(Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol, User,
VHost, Capabilities, CollectorPid, Limiter) ->
start_link(Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol, User,
VHost, Capabilities, CollectorPid, Limiter, undefined).
-spec start_link
(channel_number(), pid(), pid(), pid(), string(), rabbit_types:protocol(),
rabbit_types:user(), rabbit_types:vhost(), rabbit_framing:amqp_table(),
pid(), pid(), any()) ->
rabbit_types:ok_pid_or_error().
start_link(Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol, User,
VHost, Capabilities, CollectorPid, Limiter, AmqpParams) ->
gen_server2:start_link(
?MODULE, [Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol,
User, VHost, Capabilities, CollectorPid, Limiter, AmqpParams], []).
-spec do(pid(), rabbit_framing:amqp_method_record()) -> 'ok'.
do(Pid, Method) ->
rabbit_channel_common:do(Pid, Method).
-spec do
(pid(), rabbit_framing:amqp_method_record(),
rabbit_types:'maybe'(rabbit_types:content())) ->
'ok'.
do(Pid, Method, Content) ->
rabbit_channel_common:do(Pid, Method, Content).
-spec do_flow
(pid(), rabbit_framing:amqp_method_record(),
rabbit_types:'maybe'(rabbit_types:content())) ->
'ok'.
do_flow(Pid, Method, Content) ->
rabbit_channel_common:do_flow(Pid, Method, Content).
-spec flush(pid()) -> 'ok'.
flush(Pid) ->
gen_server2:call(Pid, flush, infinity).
-spec shutdown(pid()) -> 'ok'.
shutdown(Pid) ->
gen_server2:cast(Pid, terminate).
-spec send_command(pid(), rabbit_framing:amqp_method_record()) -> 'ok'.
send_command(Pid, Msg) ->
gen_server2:cast(Pid, {command, Msg}).
-spec deliver_reply(binary(), mc:state()) -> 'ok'.
deliver_reply(<<"amq.rabbitmq.reply-to.", EncodedBin/binary>>, Message) ->
case rabbit_direct_reply_to:decode_reply_to_v2(EncodedBin,
rabbit_nodes:all_running_with_hashes()) of
{ok, Pid, Key} ->
delegate:invoke_no_result(Pid, {?MODULE, deliver_reply_local,
[Key, Message]});
{error, _} ->
deliver_reply_v1(EncodedBin, Message)
end.
-spec deliver_reply_v1(binary(), mc:state()) -> 'ok'.
deliver_reply_v1(EncodedBin, Message) ->
%% the the original encoding function
case rabbit_direct_reply_to:decode_reply_to_v1(EncodedBin) of
{ok, V1Pid, V1Key} ->
delegate:invoke_no_result(V1Pid,
{?MODULE, deliver_reply_local, [V1Key, Message]});
{error, _} ->
ok
end.
%% We want to ensure people can't use this mechanism to send a message
%% to an arbitrary process and kill it!
-spec deliver_reply_local(pid(), binary(), mc:state()) -> 'ok'.
deliver_reply_local(Pid, Key, Message) ->
case pg_local:in_group(rabbit_channels, Pid) of
true -> gen_server2:cast(Pid, {deliver_reply, Key, Message});
false -> ok
end.
declare_fast_reply_to(<<"amq.rabbitmq.reply-to">>) ->
exists;
declare_fast_reply_to(<<"amq.rabbitmq.reply-to.", EncodedBin/binary>>) ->
case rabbit_direct_reply_to:decode_reply_to_v2(EncodedBin, rabbit_nodes:all_running_with_hashes()) of
{error, _} ->
declare_fast_reply_to_v1(EncodedBin);
{ok, Pid, Key} ->
Msg = {declare_fast_reply_to, Key},
rabbit_misc:with_exit_handler(
rabbit_misc:const(not_found),
fun() -> gen_server2:call(Pid, Msg, infinity) end)
end;
declare_fast_reply_to(_) ->
not_found.
declare_fast_reply_to_v1(EncodedBin) ->
%% the the original encoding function
case rabbit_direct_reply_to:decode_reply_to_v1(EncodedBin) of
{ok, V1Pid, V1Key} ->
Msg = {declare_fast_reply_to, V1Key},
rabbit_misc:with_exit_handler(
rabbit_misc:const(not_found),
fun() -> gen_server2:call(V1Pid, Msg, infinity) end);
{error, _} ->
not_found
end.
-spec list() -> [pid()].
list() ->
Nodes = rabbit_nodes:list_running(),
rabbit_misc:append_rpc_all_nodes(Nodes, rabbit_channel, list_local, [], ?RPC_TIMEOUT).
-spec list_local() -> [pid()].
list_local() ->
pg_local:get_members(rabbit_channels).
-spec info_keys() -> rabbit_types:info_keys().
info_keys() -> ?INFO_KEYS.
-spec info(pid()) -> rabbit_types:infos().
info(Pid) ->
{Timeout, Deadline} = get_operation_timeout_and_deadline(),
try
case gen_server2:call(Pid, {info, Deadline}, Timeout) of
{ok, Res} -> Res;
{error, Error} -> throw(Error)
end
catch
exit:{timeout, _} ->
rabbit_log:error("Timed out getting channel ~tp info", [Pid]),
throw(timeout)
end.
-spec info(pid(), rabbit_types:info_keys()) -> rabbit_types:infos().
info(Pid, Items) ->
{Timeout, Deadline} = get_operation_timeout_and_deadline(),
try
case gen_server2:call(Pid, {{info, Items}, Deadline}, Timeout) of
{ok, Res} -> Res;
{error, Error} -> throw(Error)
end
catch
exit:{timeout, _} ->
rabbit_log:error("Timed out getting channel ~tp info", [Pid]),
throw(timeout)
end.
-spec info_all() -> [rabbit_types:infos()].
info_all() ->
rabbit_misc:filter_exit_map(fun (C) -> info(C) end, list()).
-spec info_all(rabbit_types:info_keys()) -> [rabbit_types:infos()].
info_all(Items) ->
rabbit_misc:filter_exit_map(fun (C) -> info(C, Items) end, list()).
info_local(Items) ->
rabbit_misc:filter_exit_map(fun (C) -> info(C, Items) end, list_local()).
emit_info_all(Nodes, Items, Ref, AggregatorPid) ->
Pids = [ spawn_link(Node, rabbit_channel, emit_info_local, [Items, Ref, AggregatorPid]) || Node <- Nodes ],
rabbit_control_misc:await_emitters_termination(Pids).
emit_info_local(Items, Ref, AggregatorPid) ->
emit_info(list_local(), Items, Ref, AggregatorPid).
emit_info(PidList, InfoItems, Ref, AggregatorPid) ->
rabbit_control_misc:emitting_map_with_exit_handler(
AggregatorPid, Ref, fun(C) -> info(C, InfoItems) end, PidList).
-spec refresh_config_local() -> 'ok'.
refresh_config_local() ->
_ = rabbit_misc:upmap(
fun (C) ->
try
gen_server2:call(C, refresh_config, infinity)
catch _:Reason ->
rabbit_log:error("Failed to refresh channel config "
"for channel ~tp. Reason ~tp",
[C, Reason])
end
end,
list_local()),
ok.
refresh_interceptors() ->
_ = rabbit_misc:upmap(
fun (C) ->
try
gen_server2:call(C, refresh_interceptors, ?REFRESH_TIMEOUT)
catch _:Reason ->
rabbit_log:error("Failed to refresh channel interceptors "
"for channel ~tp. Reason ~tp",
[C, Reason])
end
end,
list_local()),
ok.
-spec ready_for_close(pid()) -> 'ok'.
ready_for_close(Pid) ->
rabbit_channel_common:ready_for_close(Pid).
-spec force_event_refresh(reference()) -> 'ok'.
% Note: https://www.pivotaltracker.com/story/show/166962656
% This event is necessary for the stats timer to be initialized with
% the correct values once the management agent has started
force_event_refresh(Ref) ->
[gen_server2:cast(C, {force_event_refresh, Ref}) || C <- list()],
ok.
list_queue_states(Pid) ->
gen_server2:call(Pid, list_queue_states).
-spec update_user_state(pid(), rabbit_types:auth_user()) -> 'ok' | {error, channel_terminated}.
update_user_state(Pid, UserState) when is_pid(Pid) ->
case erlang:is_process_alive(Pid) of
true -> Pid ! {update_user_state, UserState},
ok;
false -> {error, channel_terminated}
end.
%%---------------------------------------------------------------------------
init([Channel, ReaderPid, WriterPid, ConnPid, ConnName, Protocol, User, VHost,
Capabilities, CollectorPid, LimiterPid, AmqpParams]) ->
process_flag(trap_exit, true),
?LG_PROCESS_TYPE(channel),
?store_proc_name({ConnName, Channel}),
ok = pg_local:join(rabbit_channels, self()),
{ok, {Global0, Prefetch}} = application:get_env(rabbit, default_consumer_prefetch),
Limiter0 = rabbit_limiter:new(LimiterPid),
Global = Global0 andalso is_global_qos_permitted(),
Limiter = case {Global, Prefetch} of
{true, 0} ->
rabbit_limiter:unlimit_prefetch(Limiter0);
{true, _} ->
rabbit_limiter:limit_prefetch(Limiter0, Prefetch, 0);
_ ->
Limiter0
end,
%% Process dictionary is used here because permission cache already uses it. MK.
put(permission_cache_can_expire, rabbit_access_control:permission_cache_can_expire(User)),
ConsumerTimeout = get_consumer_timeout(),
OptionalVariables = extract_variable_map_from_amqp_params(AmqpParams),
{ok, GCThreshold} = application:get_env(rabbit, writer_gc_threshold),
MaxConsumers = application:get_env(rabbit, consumer_max_per_channel, infinity),
State = #ch{cfg = #conf{state = starting,
protocol = Protocol,
channel = Channel,
reader_pid = ReaderPid,
writer_pid = WriterPid,
conn_pid = ConnPid,
conn_name = ConnName,
user = User,
virtual_host = VHost,
most_recently_declared_queue = <<>>,
queue_collector_pid = CollectorPid,
capabilities = Capabilities,
trace_state = rabbit_trace:init(VHost),
consumer_prefetch = Prefetch,
consumer_timeout = ConsumerTimeout,
authz_context = OptionalVariables,
max_consumers = MaxConsumers,
writer_gc_threshold = GCThreshold
},
limiter = Limiter,
tx = none,
next_tag = 1,
unacked_message_q = ?QUEUE:new(),
consumer_mapping = #{},
queue_consumers = #{},
confirm_enabled = false,
publish_seqno = 1,
unconfirmed = rabbit_confirms:init(),
rejected = [],
confirmed = [],
reply_consumer = none,
interceptor_state = undefined,
queue_states = rabbit_queue_type:init()
},
State1 = State#ch{
interceptor_state = rabbit_channel_interceptor:init(State)},
State2 = rabbit_event:init_stats_timer(State1, #ch.stats_timer),
Infos = infos(?CREATION_EVENT_KEYS, State2),
rabbit_core_metrics:channel_created(self(), Infos),
rabbit_event:notify(channel_created, Infos),
rabbit_event:if_enabled(State2, #ch.stats_timer,
fun() -> emit_stats(State2) end),
put_operation_timeout(),
State3 = init_tick_timer(State2),
{ok, State3, hibernate,
{backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE}}.
prioritise_call(Msg, _From, _Len, _State) ->
case Msg of
info -> 9;
{info, _Items} -> 9;
_ -> 0
end.
prioritise_cast(Msg, _Len, _State) ->
case Msg of
{confirm, _MsgSeqNos, _QPid} -> 5;
{reject_publish, _MsgSeqNos, _QPid} -> 5;
{queue_event, _, {confirm, _MsgSeqNos, _QPid}} -> 5;
{queue_event, _, {reject_publish, _MsgSeqNos, _QPid}} -> 5;
_ -> 0
end.
prioritise_info(Msg, _Len, _State) ->
case Msg of
emit_stats -> 7;
_ -> 0
end.
handle_call(flush, _From, State) ->
reply(ok, State);
handle_call({info, Deadline}, _From, State) ->
try
reply({ok, infos(?INFO_KEYS, Deadline, State)}, State)
catch
Error ->
reply({error, Error}, State)
end;
handle_call({{info, Items}, Deadline}, _From, State) ->
try
reply({ok, infos(Items, Deadline, State)}, State)
catch
Error ->
reply({error, Error}, State)
end;
handle_call(refresh_config, _From,
State = #ch{cfg = #conf{virtual_host = VHost} = Cfg}) ->
reply(ok, State#ch{cfg = Cfg#conf{trace_state = rabbit_trace:init(VHost)}});
handle_call(refresh_interceptors, _From, State) ->
IState = rabbit_channel_interceptor:init(State),
reply(ok, State#ch{interceptor_state = IState});
handle_call({declare_fast_reply_to, Key}, _From,
State = #ch{reply_consumer = Consumer}) ->
reply(case Consumer of
{_, _, Key} -> exists;
_ -> not_found
end, State);
handle_call(list_queue_states, _From, State = #ch{queue_states = QueueStates}) ->
%% For testing of cleanup only
%% HACK
{reply, maps:keys(element(2, QueueStates)), State};
handle_call(_Request, _From, State) ->
noreply(State).
handle_cast({method, Method, Content, Flow},
State = #ch{cfg = #conf{reader_pid = Reader},
interceptor_state = IState}) ->
case Flow of
%% We are going to process a message from the rabbit_reader
%% process, so here we ack it. In this case we are accessing
%% the rabbit_channel process dictionary.
flow -> credit_flow:ack(Reader);
noflow -> ok
end,
try handle_method(rabbit_channel_interceptor:intercept_in(
expand_shortcuts(Method, State), Content, IState),
State) of
{reply, Reply, NewState} ->
ok = send(Reply, NewState),
noreply(NewState);
{noreply, NewState} ->
noreply(NewState);
stop ->
{stop, normal, State}
catch
exit:Reason = #amqp_error{} ->
MethodName = rabbit_misc:method_record_type(Method),
handle_exception(Reason#amqp_error{method = MethodName}, State);
_:Reason:Stacktrace ->
{stop, {Reason, Stacktrace}, State}
end;
handle_cast(ready_for_close,
State = #ch{cfg = #conf{state = closing,
writer_pid = WriterPid}}) ->
ok = rabbit_writer:send_command_sync(WriterPid, #'channel.close_ok'{}),
{stop, normal, State};
handle_cast(terminate, State = #ch{cfg = #conf{writer_pid = WriterPid}}) ->
ok = rabbit_writer:flush(WriterPid),
{stop, normal, State};
handle_cast({command, #'basic.consume_ok'{consumer_tag = CTag} = Msg}, State) ->
ok = send(Msg, State),
noreply(consumer_monitor(CTag, State));
handle_cast({command, Msg}, State) ->
ok = send(Msg, State),
noreply(State);
handle_cast({deliver_reply, _K, _Del},
State = #ch{cfg = #conf{state = closing}}) ->
noreply(State);
handle_cast({deliver_reply, _K, _Msg}, State = #ch{reply_consumer = none}) ->
noreply(State);
handle_cast({deliver_reply, Key, Msg},
State = #ch{cfg = #conf{writer_pid = WriterPid},
next_tag = DeliveryTag,
reply_consumer = {ConsumerTag, _Suffix, Key}}) ->
Content = mc:protocol_state(mc:convert(mc_amqpl, Msg)),
ExchName = mc:exchange(Msg),
[RoutingKey | _] = mc:routing_keys(Msg),
ok = rabbit_writer:send_command(
WriterPid,
#'basic.deliver'{consumer_tag = ConsumerTag,
delivery_tag = DeliveryTag,
redelivered = false,
exchange = ExchName,
routing_key = RoutingKey},
Content),
noreply(State);
handle_cast({deliver_reply, _K1, _}, State=#ch{reply_consumer = {_, _, _K2}}) ->
noreply(State);
% Note: https://www.pivotaltracker.com/story/show/166962656
% This event is necessary for the stats timer to be initialized with
% the correct values once the management agent has started
handle_cast({force_event_refresh, Ref}, State) ->
rabbit_event:notify(channel_created, infos(?CREATION_EVENT_KEYS, State),
Ref),
noreply(rabbit_event:init_stats_timer(State, #ch.stats_timer));
handle_cast({queue_event, QRef, Evt},
#ch{queue_states = QueueStates0} = State0) ->
case rabbit_queue_type:handle_event(QRef, Evt, QueueStates0) of
{ok, QState1, Actions} ->
State1 = State0#ch{queue_states = QState1},
State = handle_queue_actions(Actions, State1),
noreply_coalesce(State);
{eol, Actions} ->
State = handle_queue_actions(Actions, State0),
handle_eol(QRef, State);
{protocol_error, Type, Reason, ReasonArgs} ->
rabbit_misc:protocol_error(Type, Reason, ReasonArgs)
end.
handle_info({bump_credit, Msg}, State) ->
%% A rabbit_amqqueue_process is granting credit to our channel. If
%% our channel was being blocked by this process, and no other
%% process is blocking our channel, then this channel will be
%% unblocked. This means that any credit that was deferred will be
%% sent to rabbit_reader processs that might be blocked by this
%% particular channel.
credit_flow:handle_bump_msg(Msg),
noreply(State);
handle_info(timeout, State) ->
noreply(State);
handle_info(emit_stats, State) ->
emit_stats(State),
State1 = rabbit_event:reset_stats_timer(State, #ch.stats_timer),
%% NB: don't call noreply/1 since we don't want to kick off the
%% stats timer.
{noreply, send_confirms_and_nacks(State1), hibernate};
handle_info({{'DOWN', QName}, _MRef, process, QPid, Reason},
#ch{queue_states = QStates0} = State0) ->
credit_flow:peer_down(QPid),
case rabbit_queue_type:handle_down(QPid, QName, Reason, QStates0) of
{ok, QState1, Actions} ->
State1 = State0#ch{queue_states = QState1},
State = handle_queue_actions(Actions, State1),
noreply_coalesce(State);
{eol, QState1, QRef} ->
State = State0#ch{queue_states = QState1},
handle_eol(QRef, State)
end;
handle_info({'EXIT', _Pid, Reason}, State) ->
{stop, Reason, State};
handle_info({{Ref, Node}, LateAnswer},
State = #ch{cfg = #conf{channel = Channel}})
when is_reference(Ref) ->
rabbit_log_channel:warning("Channel ~tp ignoring late answer ~tp from ~tp",
[Channel, LateAnswer, Node]),
noreply(State);
handle_info(tick, State0 = #ch{queue_states = QueueStates0}) ->
case get(permission_cache_can_expire) of
true -> ok = clear_permission_cache();
_ -> ok
end,
case evaluate_consumer_timeout(State0#ch{queue_states = QueueStates0}) of
{noreply, State} ->
noreply(init_tick_timer(reset_tick_timer(State)));
Return ->
Return
end;
handle_info({update_user_state, User}, State = #ch{cfg = Cfg}) ->
noreply(State#ch{cfg = Cfg#conf{user = User}}).
handle_pre_hibernate(State0) ->
ok = clear_permission_cache(),
State = maybe_cancel_tick_timer(State0),
rabbit_event:if_enabled(
State, #ch.stats_timer,
fun () -> emit_stats(State,
[{idle_since,
os:system_time(millisecond)}])
end),
{hibernate, rabbit_event:stop_stats_timer(State, #ch.stats_timer)}.
handle_post_hibernate(State0) ->
State = init_tick_timer(State0),
{noreply, State}.
terminate(_Reason,
State = #ch{cfg = #conf{user = #user{username = Username}},
consumer_mapping = CM,
queue_states = QueueCtxs}) ->
rabbit_queue_type:close(QueueCtxs),
{_Res, _State1} = notify_queues(State),
pg_local:leave(rabbit_channels, self()),
rabbit_event:if_enabled(State, #ch.stats_timer,
fun() -> emit_stats(State) end),
[delete_stats(Tag) || {Tag, _} <- get()],
maybe_decrease_global_publishers(State),
maps:foreach(
fun (_, _) ->
rabbit_global_counters:consumer_deleted(amqp091)
end, CM),
rabbit_core_metrics:channel_closed(self()),
rabbit_event:notify(channel_closed, [{pid, self()},
{user_who_performed_action, Username},
{consumer_count, maps:size(CM)}]),
case rabbit_confirms:size(State#ch.unconfirmed) of
0 -> ok;
NumConfirms ->
rabbit_log:warning("Channel is stopping with ~b pending publisher confirms",
[NumConfirms])
end.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
format_message_queue(Opt, MQ) -> rabbit_misc:format_message_queue(Opt, MQ).
get_consumer_timeout() ->
case application:get_env(rabbit, consumer_timeout) of
{ok, MS} when is_integer(MS) ->
MS;
_ ->
undefined
end.
%%---------------------------------------------------------------------------
reply(Reply, NewState) -> {reply, Reply, next_state(NewState), hibernate}.
noreply(NewState) -> {noreply, next_state(NewState), hibernate}.
next_state(State) -> ensure_stats_timer(send_confirms_and_nacks(State)).
noreply_coalesce(#ch{confirmed = [], rejected = []} = State) ->
{noreply, ensure_stats_timer(State), hibernate};
noreply_coalesce(#ch{} = State) ->
% Immediately process 'timeout' info message
{noreply, ensure_stats_timer(State), 0}.
ensure_stats_timer(State) ->
rabbit_event:ensure_stats_timer(State, #ch.stats_timer, emit_stats).
return_ok(State, true, _Msg) -> {noreply, State};
return_ok(State, false, Msg) -> {reply, Msg, State}.
ok_msg(true, _Msg) -> undefined;
ok_msg(false, Msg) -> Msg.
send(_Command, #ch{cfg = #conf{state = closing}}) ->
ok;
send(Command, #ch{cfg = #conf{writer_pid = WriterPid}}) ->
ok = rabbit_writer:send_command(WriterPid, Command).
format_soft_error(#amqp_error{name = N, explanation = E, method = M}) ->
io_lib:format("operation ~ts caused a channel exception ~ts: ~ts", [M, N, E]).
handle_exception(Reason, State = #ch{cfg = #conf{protocol = Protocol,
channel = Channel,
writer_pid = WriterPid,
reader_pid = ReaderPid,
conn_pid = ConnPid,
conn_name = ConnName,
virtual_host = VHost,
user = User
}}) ->
%% something bad's happened: notify_queues may not be 'ok'
{_Result, State1} = notify_queues(State),
case rabbit_binary_generator:map_exception(Channel, Reason, Protocol) of
{Channel, CloseMethod} ->
rabbit_log_channel:error(
"Channel error on connection ~tp (~ts, vhost: '~ts',"
" user: '~ts'), channel ~tp:~n~ts",
[ConnPid, ConnName, VHost, User#user.username,
Channel, format_soft_error(Reason)]),
ok = rabbit_writer:send_command(WriterPid, CloseMethod),
{noreply, State1};
{0, _} ->
ReaderPid ! {channel_exit, Channel, Reason},
{stop, normal, State1}
end.
return_queue_declare_ok(#resource{name = ActualName},
NoWait, MessageCount, ConsumerCount,
#ch{cfg = Cfg} = State) ->
return_ok(State#ch{cfg = Cfg#conf{most_recently_declared_queue = ActualName}},
NoWait, #'queue.declare_ok'{queue = ActualName,
message_count = MessageCount,
consumer_count = ConsumerCount}).
check_resource_access(User, Resource, Perm, Context) ->
V = {Resource, Context, Perm},
Cache = case get(permission_cache) of
undefined -> [];
Other -> Other
end,
case lists:member(V, Cache) of
true -> ok;
false -> ok = rabbit_access_control:check_resource_access(
User, Resource, Perm, Context),
CacheTail = lists:sublist(Cache, ?MAX_PERMISSION_CACHE_SIZE-1),
put(permission_cache, [V | CacheTail])
end.
clear_permission_cache() -> erase(permission_cache),
erase(topic_permission_cache),
ok.
check_configure_permitted(Resource, User, Context) ->
check_resource_access(User, Resource, configure, Context).
check_write_permitted(Resource, User, Context) ->
check_resource_access(User, Resource, write, Context).
check_read_permitted(Resource, User, Context) ->
check_resource_access(User, Resource, read, Context).
check_write_permitted_on_topic(Resource, User, RoutingKey, AuthzContext) ->
check_topic_authorisation(Resource, User, RoutingKey, AuthzContext, write).
check_read_permitted_on_topic(Resource, User, RoutingKey, AuthzContext) ->
check_topic_authorisation(Resource, User, RoutingKey, AuthzContext, read).
check_user_id_header(Msg, User) ->
case rabbit_access_control:check_user_id(Msg, User) of
ok ->
ok;
{refused, Reason, Args} ->
rabbit_misc:precondition_failed(Reason, Args)
end.
check_expiration_header(Props) ->
case rabbit_basic:parse_expiration(Props) of
{ok, _} -> ok;
{error, E} -> rabbit_misc:precondition_failed("invalid expiration '~ts': ~tp",
[Props#'P_basic'.expiration, E])
end.
check_internal_exchange(#exchange{name = Name, internal = true}) ->
rabbit_misc:protocol_error(access_refused,
"cannot publish to internal ~ts",
[rabbit_misc:rs(Name)]);
check_internal_exchange(_) ->
ok.
check_topic_authorisation(#exchange{name = Name = #resource{virtual_host = VHost}, type = topic},
User = #user{username = Username},
RoutingKey, AuthzContext, Permission) ->
Resource = Name#resource{kind = topic},
VariableMap = build_topic_variable_map(AuthzContext, VHost, Username),
Context = #{routing_key => RoutingKey,
variable_map => VariableMap},
Cache = case get(topic_permission_cache) of
undefined -> [];
Other -> Other
end,
case lists:member({Resource, Context, Permission}, Cache) of
true -> ok;
false -> ok = rabbit_access_control:check_topic_access(
User, Resource, Permission, Context),
CacheTail = lists:sublist(Cache, ?MAX_PERMISSION_CACHE_SIZE-1),
put(topic_permission_cache, [{Resource, Context, Permission} | CacheTail])
end;
check_topic_authorisation(_, _, _, _, _) ->
ok.
build_topic_variable_map(AuthzContext, VHost, Username) when is_map(AuthzContext) ->
maps:merge(AuthzContext, #{<<"vhost">> => VHost, <<"username">> => Username});
build_topic_variable_map(AuthzContext, VHost, Username) ->
maps:merge(extract_variable_map_from_amqp_params(AuthzContext), #{<<"vhost">> => VHost, <<"username">> => Username}).
%% Use tuple representation of amqp_params to avoid a dependency on amqp_client.
%% Extracts variable map only from amqp_params_direct, not amqp_params_network.
%% amqp_params_direct records are usually used by plugins (e.g. STOMP)
extract_variable_map_from_amqp_params({amqp_params, {amqp_params_direct, _, _, _, _,
{amqp_adapter_info, _,_,_,_,_,_,AdditionalInfo}, _}}) ->
proplists:get_value(variable_map, AdditionalInfo, #{});
extract_variable_map_from_amqp_params({amqp_params_direct, _, _, _, _,
{amqp_adapter_info, _,_,_,_,_,_,AdditionalInfo}, _}) ->
proplists:get_value(variable_map, AdditionalInfo, #{});
extract_variable_map_from_amqp_params([Value]) ->
extract_variable_map_from_amqp_params(Value);
extract_variable_map_from_amqp_params(_) ->
#{}.
check_msg_size(Content, GCThreshold) ->
MaxMessageSize = persistent_term:get(max_message_size),
Size = rabbit_basic:maybe_gc_large_msg(Content, GCThreshold),
case Size =< MaxMessageSize of
true ->
ok;
false ->
Fmt = case MaxMessageSize of
?MAX_MSG_SIZE ->
"message size ~B is larger than max size ~B";
_ ->
"message size ~B is larger than configured max size ~B"
end,
rabbit_misc:precondition_failed(
Fmt, [Size, MaxMessageSize])
end.
qbin_to_resource(QueueNameBin, VHostPath) ->