-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
rabbit_reader.erl
1830 lines (1670 loc) · 79.3 KB
/
rabbit_reader.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_reader).
%% This is an AMQP 0-9-1 connection implementation. If AMQP 1.0 plugin is enabled,
%% this module passes control of incoming AMQP 1.0 connections to it.
%%
%% Every connection (as in, a process using this module)
%% is a controlling process for a server socket.
%%
%% Connections have a number of responsibilities:
%%
%% * Performing protocol handshake
%% * Parsing incoming data and dispatching protocol methods
%% * Authenticating clients (with the help of authentication backends)
%% * Enforcing TCP backpressure (throttling clients)
%% * Enforcing connection limits, e.g. channel_max
%% * Channel management
%% * Setting up heartbeater and alarm notifications
%% * Emitting connection and network activity metric events
%% * Gracefully handling client disconnects, channel termination, etc
%%
%% and a few more.
%%
%% Every connection has
%%
%% * a queue collector which is responsible for keeping
%% track of exclusive queues on the connection and their cleanup.
%% * a heartbeater that's responsible for sending heartbeat frames to clients,
%% keeping track of the incoming ones and notifying connection about
%% heartbeat timeouts
%% * Stats timer, a timer that is used to periodically emit metric events
%%
%% Some dependencies are started under a separate supervisor to avoid deadlocks
%% during system shutdown. See rabbit_channel_sup:start_link/0 for details.
%%
%% Reader processes are special processes (in the OTP sense).
-include_lib("rabbit_common/include/rabbit_framing.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
-export([start_link/2, info_keys/0, info/1, info/2, force_event_refresh/2,
shutdown/2]).
-export([system_continue/3, system_terminate/4, system_code_change/4]).
-export([init/3, mainloop/4, recvloop/4]).
-export([conserve_resources/3, server_properties/1]).
-define(NORMAL_TIMEOUT, 3).
-define(CLOSING_TIMEOUT, 30).
-define(CHANNEL_TERMINATION_TIMEOUT, 3).
%% we wait for this many seconds before closing TCP connection
%% with a client that failed to log in. Provides some relief
%% from connection storms and DoS.
-define(SILENT_CLOSE_DELAY, 3).
-define(CHANNEL_MIN, 1).
%% AMQP 1.0 §5.3
-define(PROTOCOL_ID_SASL, 3).
%%--------------------------------------------------------------------------
-record(v1, {
%% parent process
parent,
%% Ranch ref
ranch_ref,
%% socket
sock,
%% connection state, see connection record
connection,
callback,
recv_len,
pending_recv,
%% pre_init | securing | running | blocking | blocked | closing | closed | {become, F}
connection_state,
%% see comment in rabbit_connection_sup:start_link/0
helper_sup :: {HelperSupAmqp091 :: pid(),
HelperSupAmqp10 :: pid()} % pre version negotiation
| pid(), % post version negotiation
%% takes care of cleaning up exclusive queues,
%% see rabbit_queue_collector
queue_collector,
%% sends and receives heartbeat frames,
%% see rabbit_heartbeat
heartbeater,
%% timer used to emit statistics
stats_timer,
%% channel supervisor
channel_sup_sup_pid,
%% how many channels this connection has
channel_count,
%% throttling state, for both
%% credit- and resource-driven flow control
throttle,
proxy_socket}).
-record(throttle, {
%% never | timestamp()
last_blocked_at,
%% a set of the reasons why we are
%% blocked: {resource, memory}, {resource, disk}.
%% More reasons can be added in the future.
blocked_by,
%% true if received any publishes, false otherwise
%% note that this will also be true when connection is
%% already blocked
should_block,
%% true if we had we sent a connection.blocked,
%% false otherwise
connection_blocked_message_sent
}).
-define(STATISTICS_KEYS, [pid, recv_oct, recv_cnt, send_oct, send_cnt,
send_pend, state, channels, reductions,
garbage_collection]).
-define(SIMPLE_METRICS, [pid, recv_oct, send_oct, reductions]).
-define(OTHER_METRICS, [recv_cnt, send_cnt, send_pend, state, channels,
garbage_collection]).
-define(CREATION_EVENT_KEYS,
[pid, name, port, peer_port, host,
peer_host, ssl, peer_cert_subject, peer_cert_issuer,
peer_cert_validity, auth_mechanism, ssl_protocol,
ssl_key_exchange, ssl_cipher, ssl_hash, protocol, user, vhost,
timeout, frame_max, channel_max, client_properties, connected_at,
node, user_who_performed_action]).
-define(INFO_KEYS, ?CREATION_EVENT_KEYS ++ ?STATISTICS_KEYS -- [pid]).
-define(AUTH_NOTIFICATION_INFO_KEYS,
[host, name, peer_host, peer_port, protocol, auth_mechanism,
ssl, ssl_protocol, ssl_cipher, peer_cert_issuer, peer_cert_subject,
peer_cert_validity]).
-define(IS_RUNNING(State),
(State#v1.connection_state =:= running orelse
State#v1.connection_state =:= blocked)).
-define(IS_STOPPING(State),
(State#v1.connection_state =:= closing orelse
State#v1.connection_state =:= closed)).
%%--------------------------------------------------------------------------
-spec start_link({pid(), pid()}, ranch:ref()) ->
rabbit_types:ok(pid()).
start_link(HelperSups, Ref) ->
Pid = proc_lib:spawn_link(?MODULE, init, [self(), HelperSups, Ref]),
{ok, Pid}.
-spec shutdown(pid(), string()) -> 'ok'.
shutdown(Pid, Explanation) ->
gen_server:call(Pid, {shutdown, Explanation}, infinity).
-spec init(pid(), {pid(), pid()}, ranch:ref()) ->
no_return().
init(Parent, HelperSups, Ref) ->
?LG_PROCESS_TYPE(reader),
%% Note:
%% This function could return an error if the handshake times out.
%% It is less likely to happen here as compared to MQTT, so
%% crashing with a `badmatch` seems appropriate.
{ok, Sock} = rabbit_networking:handshake(Ref,
application:get_env(rabbit, proxy_protocol, false)),
Deb = sys:debug_options([]),
start_connection(Parent, HelperSups, Ref, Deb, Sock).
-spec system_continue(_,_,{[binary()], non_neg_integer(), #v1{}}) -> any().
system_continue(Parent, Deb, {Buf, BufLen, State}) ->
mainloop(Deb, Buf, BufLen, State#v1{parent = Parent}).
-spec system_terminate(_,_,_,_) -> no_return().
system_terminate(Reason, _Parent, _Deb, _State) ->
exit(Reason).
-spec system_code_change(_,_,_,_) -> {'ok',_}.
system_code_change(Misc, _Module, _OldVsn, _Extra) ->
{ok, Misc}.
-spec info_keys() -> rabbit_types:info_keys().
info_keys() -> ?INFO_KEYS.
-spec info(pid()) -> rabbit_types:infos().
info(Pid) ->
gen_server:call(Pid, info, infinity).
-spec info(pid(), rabbit_types:info_keys()) -> rabbit_types:infos().
info(Pid, Items) ->
case gen_server:call(Pid, {info, Items}, infinity) of
{ok, Res} -> Res;
{error, Error} -> throw(Error)
end.
-spec force_event_refresh(pid(), 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(Pid, Ref) ->
gen_server:cast(Pid, {force_event_refresh, Ref}).
-spec conserve_resources(pid(),
rabbit_alarm:resource_alarm_source(),
rabbit_alarm:resource_alert()) -> 'ok'.
conserve_resources(Pid, Source, {_, Conserve, _}) ->
Pid ! {conserve_resources, Source, Conserve},
ok.
-spec server_properties(rabbit_types:protocol() | 'amqp_1_0') ->
rabbit_framing:amqp_table().
server_properties(Protocol) ->
{ok, Product} = application:get_key(rabbit, description),
{ok, Version} = application:get_key(rabbit, vsn),
%% Get any configuration-specified server properties
{ok, RawConfigServerProps} = application:get_env(rabbit,
server_properties),
%% Normalize the simplified (2-tuple) and unsimplified (3-tuple) forms
%% from the config and merge them with the generated built-in properties
NormalizedConfigServerProps =
[{<<"capabilities">>, table, server_capabilities(Protocol)} |
[case X of
{KeyAtom, Value} -> {atom_to_binary(KeyAtom),
longstr,
maybe_list_to_binary(Value)};
{BinKey, Type, Value} -> {BinKey, Type, Value}
end || X <- RawConfigServerProps ++
[{product, Product},
{version, Version},
{cluster_name, rabbit_nodes:cluster_name()},
{platform, rabbit_misc:platform_and_version()},
{copyright, ?COPYRIGHT_MESSAGE},
{information, ?INFORMATION_MESSAGE}]]],
%% Filter duplicated properties in favour of config file provided values
lists:usort(fun ({K1,_,_}, {K2,_,_}) -> K1 =< K2 end,
NormalizedConfigServerProps).
maybe_list_to_binary(V) when is_binary(V) -> V;
maybe_list_to_binary(V) when is_list(V) -> list_to_binary(V).
server_capabilities(rabbit_framing_amqp_0_9_1) ->
[{<<"publisher_confirms">>, bool, true},
{<<"exchange_exchange_bindings">>, bool, true},
{<<"basic.nack">>, bool, true},
{<<"consumer_cancel_notify">>, bool, true},
{<<"connection.blocked">>, bool, true},
{<<"consumer_priorities">>, bool, true},
{<<"authentication_failure_close">>, bool, true},
{<<"per_consumer_qos">>, bool, true},
{<<"direct_reply_to">>, bool, true}];
server_capabilities(_) ->
[].
%%--------------------------------------------------------------------------
socket_error(Reason) when is_atom(Reason) ->
rabbit_log_connection:error("Error on AMQP connection ~tp: ~ts",
[self(), rabbit_misc:format_inet_error(Reason)]);
socket_error(Reason) ->
Fmt = "Error on AMQP connection ~tp:~n~tp",
Args = [self(), Reason],
case Reason of
%% The socket was closed while upgrading to SSL.
%% This is presumably a TCP healthcheck, so don't log
%% it unless specified otherwise.
{ssl_upgrade_error, closed} ->
rabbit_log_connection:debug(Fmt, Args);
_ ->
rabbit_log_connection:error(Fmt, Args)
end.
inet_op(F) -> rabbit_misc:throw_on_error(inet_error, F).
socket_op(Sock, Fun) ->
RealSocket = rabbit_net:unwrap_socket(Sock),
case Fun(Sock) of
{ok, Res} -> Res;
{error, Reason} -> socket_error(Reason),
rabbit_net:fast_close(RealSocket),
exit(normal)
end.
-spec start_connection(pid(), {pid(), pid()}, ranch:ref(), any(), rabbit_net:socket()) ->
no_return().
start_connection(Parent, HelperSups, RanchRef, Deb, Sock) ->
process_flag(trap_exit, true),
RealSocket = rabbit_net:unwrap_socket(Sock),
Name = case rabbit_net:connection_string(Sock, inbound) of
{ok, Str} -> list_to_binary(Str);
{error, enotconn} -> rabbit_net:fast_close(RealSocket),
exit(normal);
{error, Reason} -> socket_error(Reason),
rabbit_net:fast_close(RealSocket),
exit(normal)
end,
{ok, HandshakeTimeout} = application:get_env(rabbit, handshake_timeout),
InitialFrameMax = application:get_env(rabbit, initial_frame_max, ?FRAME_MIN_SIZE),
erlang:send_after(HandshakeTimeout, self(), handshake_timeout),
{PeerHost, PeerPort, Host, Port} =
socket_op(Sock, fun (S) -> rabbit_net:socket_ends(S, inbound) end),
?store_proc_name(Name),
State = #v1{parent = Parent,
ranch_ref = RanchRef,
sock = RealSocket,
connection = #connection{
name = Name,
log_name = Name,
host = Host,
peer_host = PeerHost,
port = Port,
peer_port = PeerPort,
protocol = none,
user = none,
timeout_sec = (HandshakeTimeout / 1000),
frame_max = InitialFrameMax,
vhost = none,
client_properties = none,
capabilities = [],
auth_mechanism = none,
auth_state = none,
connected_at = os:system_time(
milli_seconds)},
callback = uninitialized_callback,
recv_len = 0,
pending_recv = false,
connection_state = pre_init,
queue_collector = undefined, %% started on tune-ok
helper_sup = HelperSups,
heartbeater = none,
channel_sup_sup_pid = none,
channel_count = 0,
throttle = #throttle{
last_blocked_at = never,
should_block = false,
blocked_by = sets:new(),
connection_blocked_message_sent = false
},
proxy_socket = rabbit_net:maybe_get_proxy_socket(Sock)},
try
case run({?MODULE, recvloop,
[Deb, [], 0, switch_callback(rabbit_event:init_stats_timer(
State, #v1.stats_timer),
handshake, 8)]}) of
%% connection was closed cleanly by the client
#v1{connection = #connection{user = #user{username = Username},
vhost = VHost}} ->
rabbit_log_connection:info("closing AMQP connection (~ts, vhost: '~ts', user: '~ts')",
[dynamic_connection_name(Name), VHost, Username]);
%% just to be more defensive
_ ->
rabbit_log_connection:info("closing AMQP connection (~ts)",
[dynamic_connection_name(Name)])
end
catch
Ex ->
log_connection_exception(dynamic_connection_name(Name), Ex)
after
%% We don't call gen_tcp:close/1 here since it waits for
%% pending output to be sent, which results in unnecessary
%% delays.
rabbit_net:fast_close(RealSocket),
rabbit_networking:unregister_connection(self()),
rabbit_core_metrics:connection_closed(self()),
ClientProperties = case get(client_properties) of
undefined ->
[];
Properties ->
Properties
end,
EventProperties = [{name, Name},
{pid, self()},
{node, node()},
{client_properties, ClientProperties}],
EventProperties1 = case get(connection_user_provided_name) of
undefined ->
EventProperties;
ConnectionUserProvidedName ->
[{user_provided_name, ConnectionUserProvidedName} | EventProperties]
end,
rabbit_event:notify(connection_closed, EventProperties1)
end,
done.
log_connection_exception(Name, Ex) ->
Severity = case Ex of
connection_closed_with_no_data_received -> debug;
{connection_closed_abruptly, _} -> warning;
connection_closed_abruptly -> warning;
_ -> error
end,
log_connection_exception(Severity, Name, Ex).
log_connection_exception(Severity, Name, {heartbeat_timeout, TimeoutSec}) ->
%% Long line to avoid extra spaces and line breaks in log
log_connection_exception_with_severity(Severity,
"closing AMQP connection ~tp (~ts):~n"
"missed heartbeats from client, timeout: ~ps",
[self(), Name, TimeoutSec]);
log_connection_exception(Severity, Name, {connection_closed_abruptly,
#v1{connection = #connection{user = #user{username = Username},
vhost = VHost}}}) ->
log_connection_exception_with_severity(Severity,
"closing AMQP connection ~tp (~ts, vhost: '~ts', user: '~ts'):~nclient unexpectedly closed TCP connection",
[self(), Name, VHost, Username]);
%% when client abruptly closes connection before connection.open/authentication/authorization
%% succeeded, don't log username and vhost as 'none'
log_connection_exception(Severity, Name, {connection_closed_abruptly, _}) ->
log_connection_exception_with_severity(Severity,
"closing AMQP connection ~tp (~ts):~nclient unexpectedly closed TCP connection",
[self(), Name]);
%% failed connection.tune negotiations
log_connection_exception(Severity, Name, {handshake_error, tuning, _Channel,
{exit, #amqp_error{explanation = Explanation},
_Method, _Stacktrace}}) ->
log_connection_exception_with_severity(Severity,
"closing AMQP connection ~tp (~ts):~nfailed to negotiate connection parameters: ~ts",
[self(), Name, Explanation]);
log_connection_exception(Severity, Name, {sasl_required, ProtocolId}) ->
log_connection_exception_with_severity(
Severity,
"closing AMQP 1.0 connection (~ts): RabbitMQ requires SASL "
"security layer (expected protocol ID 3, but client sent protocol ID ~b)",
[Name, ProtocolId]);
%% old exception structure
log_connection_exception(Severity, Name, connection_closed_abruptly) ->
log_connection_exception_with_severity(Severity,
"closing AMQP connection ~tp (~ts):~n"
"client unexpectedly closed TCP connection",
[self(), Name]);
log_connection_exception(Severity, Name, Ex) ->
log_connection_exception_with_severity(Severity,
"closing AMQP connection ~tp (~ts):~n~tp",
[self(), Name, Ex]).
log_connection_exception_with_severity(Severity, Fmt, Args) ->
case Severity of
debug -> rabbit_log_connection:debug(Fmt, Args);
warning -> rabbit_log_connection:warning(Fmt, Args);
error -> rabbit_log_connection:error(Fmt, Args)
end.
run({M, F, A}) ->
try apply(M, F, A)
catch {become, MFA} -> run(MFA)
end.
recvloop(Deb, Buf, BufLen, State = #v1{pending_recv = true}) ->
mainloop(Deb, Buf, BufLen, State);
recvloop(Deb, Buf, BufLen, State = #v1{connection_state = blocked}) ->
mainloop(Deb, Buf, BufLen, State);
recvloop(Deb, Buf, BufLen, State = #v1{connection_state = {become, F}}) ->
throw({become, F(Deb, Buf, BufLen, State)});
recvloop(Deb, Buf, BufLen, State = #v1{sock = Sock, recv_len = RecvLen})
when BufLen < RecvLen ->
case rabbit_net:setopts(Sock, [{active, once}]) of
ok -> mainloop(Deb, Buf, BufLen,
State#v1{pending_recv = true});
{error, Reason} -> stop(Reason, State)
end;
recvloop(Deb, [B], _BufLen, State) ->
{Rest, State1} = handle_input(State#v1.callback, B, State),
recvloop(Deb, [Rest], size(Rest), State1);
recvloop(Deb, Buf, BufLen, State = #v1{recv_len = RecvLen}) ->
{DataLRev, RestLRev} = binlist_split(BufLen - RecvLen, Buf, []),
Data = list_to_binary(lists:reverse(DataLRev)),
{<<>>, State1} = handle_input(State#v1.callback, Data, State),
recvloop(Deb, lists:reverse(RestLRev), BufLen - RecvLen, State1).
binlist_split(0, L, Acc) ->
{L, Acc};
binlist_split(Len, L, [Acc0|Acc]) when Len < 0 ->
{H, T} = split_binary(Acc0, -Len),
{[H|L], [T|Acc]};
binlist_split(Len, [H|T], Acc) ->
binlist_split(Len - size(H), T, [H|Acc]).
-spec mainloop(_,[binary()], non_neg_integer(), #v1{}) -> any().
mainloop(Deb, Buf, BufLen, State = #v1{sock = Sock,
connection_state = CS,
connection = #connection{
name = ConnName}}) ->
Recv = rabbit_net:recv(Sock),
case CS of
pre_init when Buf =:= [] ->
%% We only log incoming connections when either the
%% first byte was received or there was an error (eg. a
%% timeout).
%%
%% The goal is to not log TCP healthchecks (a connection
%% with no data received) unless specified otherwise.
Fmt = "accepting AMQP connection ~ts",
Args = [ConnName],
case Recv of
closed -> _ = rabbit_log_connection:debug(Fmt, Args);
_ -> _ = rabbit_log_connection:info(Fmt, Args)
end;
_ ->
ok
end,
case Recv of
{data, Data} ->
recvloop(Deb, [Data | Buf], BufLen + size(Data),
State#v1{pending_recv = false});
closed when State#v1.connection_state =:= closed ->
State;
closed when CS =:= pre_init andalso Buf =:= [] ->
stop(tcp_healthcheck, State);
closed ->
stop(closed, State);
{other, {heartbeat_send_error, _}=ErrHeartbeat} ->
%% The only portable way to detect disconnect on blocked
%% connection is to wait for heartbeat send failure.
stop(ErrHeartbeat, State);
{error, Reason} ->
stop(Reason, State);
{other, {system, From, Request}} ->
sys:handle_system_msg(Request, From, State#v1.parent,
?MODULE, Deb, {Buf, BufLen, State});
{other, Other} ->
case handle_other(Other, State) of
stop -> State;
NewState -> recvloop(Deb, Buf, BufLen, NewState)
end
end.
-spec stop(_, #v1{}) -> no_return().
stop(tcp_healthcheck, State) ->
%% The connection was closed before any packet was received. It's
%% probably a load-balancer healthcheck: don't consider this a
%% failure.
maybe_emit_stats(State),
throw(connection_closed_with_no_data_received);
stop(closed, State) ->
maybe_emit_stats(State),
throw({connection_closed_abruptly, State});
stop(Reason, State) ->
maybe_emit_stats(State),
throw({inet_error, Reason}).
handle_other({conserve_resources, Source, Conserve},
State = #v1{throttle = Throttle = #throttle{blocked_by = Blockers}}) ->
Resource = {resource, Source},
Blockers1 = case Conserve of
true -> sets:add_element(Resource, Blockers);
false -> sets:del_element(Resource, Blockers)
end,
control_throttle(State#v1{throttle = Throttle#throttle{blocked_by = Blockers1}});
handle_other({channel_closing, ChPid}, State) ->
ok = rabbit_channel:ready_for_close(ChPid),
{_, State1} = channel_cleanup(ChPid, State),
maybe_close(control_throttle(State1));
handle_other({'EXIT', Parent, normal}, State = #v1{parent = Parent}) ->
%% rabbitmq/rabbitmq-server#544
%% The connection port process has exited due to the TCP socket being closed.
%% Handle this case in the same manner as receiving {error, closed}
stop(closed, State);
handle_other({'EXIT', Parent, Reason}, State = #v1{parent = Parent}) ->
Msg = io_lib:format("broker forced connection closure with reason '~w'", [Reason]),
_ = terminate(Msg, State),
%% this is what we are expected to do according to
%% https://www.erlang.org/doc/man/sys.html
%%
%% If we wanted to be *really* nice we should wait for a while for
%% clients to close the socket at their end, just as we do in the
%% ordinary error case. However, since this termination is
%% initiated by our parent it is probably more important to exit
%% quickly.
maybe_emit_stats(State),
exit(Reason);
handle_other({channel_exit, _Channel, E = {writer, send_failed, _E}}, State) ->
maybe_emit_stats(State),
throw(E);
handle_other({channel_exit, Channel, Reason}, State) ->
handle_exception(State, Channel, Reason);
handle_other({'DOWN', _MRef, process, ChPid, Reason}, State) ->
handle_dependent_exit(ChPid, Reason, State);
handle_other(terminate_connection, State) ->
maybe_emit_stats(State),
stop;
handle_other(handshake_timeout, State)
when ?IS_RUNNING(State) orelse ?IS_STOPPING(State) ->
State;
handle_other(handshake_timeout, State) ->
maybe_emit_stats(State),
throw({handshake_timeout, State#v1.callback});
handle_other(heartbeat_timeout, State = #v1{connection_state = closed}) ->
State;
handle_other(heartbeat_timeout,
State = #v1{connection = #connection{timeout_sec = T}}) ->
maybe_emit_stats(State),
throw({heartbeat_timeout, T});
handle_other({'$gen_call', From, {shutdown, Explanation}}, State) ->
{ForceTermination, NewState} = terminate(Explanation, State),
gen_server:reply(From, ok),
case ForceTermination of
force -> stop;
normal -> NewState
end;
handle_other({'$gen_call', From, info}, State) ->
gen_server:reply(From, infos(?INFO_KEYS, State)),
State;
handle_other({'$gen_call', From, {info, Items}}, State) ->
gen_server:reply(From, try {ok, infos(Items, State)}
catch Error -> {error, Error}
end),
State;
handle_other({'$gen_cast', {force_event_refresh, Ref}}, State)
when ?IS_RUNNING(State) ->
rabbit_event:notify(
connection_created,
augment_infos_with_user_provided_connection_name(
[{type, network} | infos(?CREATION_EVENT_KEYS, State)], State),
Ref),
rabbit_event:init_stats_timer(State, #v1.stats_timer);
handle_other({'$gen_cast', {force_event_refresh, _Ref}}, State) ->
%% Ignore, we will emit a created event once we start running.
State;
handle_other(ensure_stats, State) ->
ensure_stats_timer(State);
handle_other(emit_stats, State) ->
emit_stats(State);
handle_other({bump_credit, Msg}, State) ->
%% Here we are receiving credit by some channel process.
credit_flow:handle_bump_msg(Msg),
control_throttle(State);
handle_other(Other, State) ->
%% internal error -> something worth dying for
maybe_emit_stats(State),
exit({unexpected_message, Other}).
switch_callback(State, Callback, Length) ->
State#v1{callback = Callback, recv_len = Length}.
terminate(Explanation, State) when ?IS_RUNNING(State) ->
{normal, handle_exception(State, 0,
rabbit_misc:amqp_error(
connection_forced, "~ts", [Explanation], none))};
terminate(_Explanation, State) ->
{force, State}.
send_blocked(#v1{connection = #connection{protocol = Protocol,
capabilities = Capabilities},
sock = Sock}, Reason) ->
case rabbit_misc:table_lookup(Capabilities, <<"connection.blocked">>) of
{bool, true} ->
ok = send_on_channel0(Sock, #'connection.blocked'{reason = Reason},
Protocol);
_ ->
ok
end.
send_unblocked(#v1{connection = #connection{protocol = Protocol,
capabilities = Capabilities},
sock = Sock}) ->
case rabbit_misc:table_lookup(Capabilities, <<"connection.blocked">>) of
{bool, true} ->
ok = send_on_channel0(Sock, #'connection.unblocked'{}, Protocol);
_ ->
ok
end.
%%--------------------------------------------------------------------------
%% error handling / termination
close_connection(State = #v1{queue_collector = Collector,
connection = #connection{
timeout_sec = TimeoutSec}}) ->
%% The spec says "Exclusive queues may only be accessed by the
%% current connection, and are deleted when that connection
%% closes." This does not strictly imply synchrony, but in
%% practice it seems to be what people assume.
clean_up_exclusive_queues(Collector),
%% We terminate the connection after the specified interval, but
%% no later than ?CLOSING_TIMEOUT seconds.
erlang:send_after((if TimeoutSec > 0 andalso
TimeoutSec < ?CLOSING_TIMEOUT -> TimeoutSec;
true -> ?CLOSING_TIMEOUT
end) * 1000, self(), terminate_connection),
State#v1{connection_state = closed}.
%% queue collector will be undefined when connection
%% tuning was never performed or didn't finish. In such cases
%% there's also nothing to clean up.
clean_up_exclusive_queues(undefined) ->
ok;
clean_up_exclusive_queues(Collector) ->
rabbit_queue_collector:delete_all(Collector).
handle_dependent_exit(ChPid, Reason, State) ->
{Channel, State1} = channel_cleanup(ChPid, State),
case {Channel, termination_kind(Reason)} of
{undefined, controlled} -> State1;
{undefined, uncontrolled} -> handle_uncontrolled_channel_close(ChPid),
exit({abnormal_dependent_exit,
ChPid, Reason});
{_, controlled} -> maybe_close(control_throttle(State1));
{_, uncontrolled} -> handle_uncontrolled_channel_close(ChPid),
State2 = handle_exception(
State1, Channel, Reason),
maybe_close(control_throttle(State2))
end.
terminate_channels(#v1{channel_count = 0} = State) ->
State;
terminate_channels(#v1{channel_count = ChannelCount} = State) ->
lists:foreach(fun rabbit_channel:shutdown/1, all_channels()),
Timeout = 1000 * ?CHANNEL_TERMINATION_TIMEOUT * ChannelCount,
TimerRef = erlang:send_after(Timeout, self(), cancel_wait),
wait_for_channel_termination(ChannelCount, TimerRef, State).
wait_for_channel_termination(0, TimerRef, State) ->
case erlang:cancel_timer(TimerRef) of
false -> receive
cancel_wait -> State
end;
_ -> State
end;
wait_for_channel_termination(N, TimerRef,
State = #v1{connection_state = CS,
connection = #connection{
log_name = ConnName,
user = User,
vhost = VHost},
sock = Sock}) ->
receive
{'DOWN', _MRef, process, ChPid, Reason} ->
{Channel, State1} = channel_cleanup(ChPid, State),
case {Channel, termination_kind(Reason)} of
{undefined, _} ->
exit({abnormal_dependent_exit, ChPid, Reason});
{_, controlled} ->
wait_for_channel_termination(N-1, TimerRef, State1);
{_, uncontrolled} ->
rabbit_log_connection:error(
"Error on AMQP connection ~tp (~ts, vhost: '~ts',"
" user: '~ts', state: ~tp), channel ~tp:"
"error while terminating:~n~tp",
[self(), ConnName, VHost, User#user.username,
CS, Channel, Reason]),
handle_uncontrolled_channel_close(ChPid),
wait_for_channel_termination(N-1, TimerRef, State1)
end;
{'EXIT', Sock, _Reason} ->
clean_up_all_channels(State),
exit(normal);
cancel_wait ->
exit(channel_termination_timeout)
end.
maybe_close(State = #v1{connection_state = closing,
channel_count = 0,
connection = #connection{protocol = Protocol},
sock = Sock}) ->
NewState = close_connection(State),
ok = send_on_channel0(Sock, #'connection.close_ok'{}, Protocol),
NewState;
maybe_close(State) ->
State.
termination_kind(normal) -> controlled;
termination_kind(_) -> uncontrolled.
format_hard_error(#amqp_error{name = N, explanation = E, method = M}) ->
io_lib:format("operation ~ts caused a connection exception ~ts: ~tp", [M, N, E]);
format_hard_error(Reason) ->
case io_lib:deep_char_list(Reason) of
true -> Reason;
false -> rabbit_misc:format("~tp", [Reason])
end.
log_hard_error(#v1{connection_state = CS,
connection = #connection{
log_name = ConnName,
user = User,
vhost = VHost}}, Channel, Reason) ->
rabbit_log_connection:error(
"Error on AMQP connection ~tp (~ts, vhost: '~ts',"
" user: '~ts', state: ~tp), channel ~tp:~n ~ts",
[self(), ConnName, VHost, User#user.username, CS, Channel, format_hard_error(Reason)]).
handle_exception(State = #v1{connection_state = closed}, Channel, Reason) ->
log_hard_error(State, Channel, Reason),
State;
handle_exception(State = #v1{connection = #connection{protocol = Protocol},
connection_state = CS},
Channel, Reason)
when ?IS_RUNNING(State) orelse CS =:= closing ->
respond_and_close(State, Channel, Protocol, Reason, Reason);
%% authentication failure
handle_exception(State = #v1{connection = #connection{protocol = Protocol,
log_name = ConnName,
capabilities = Capabilities},
connection_state = starting},
Channel, Reason = #amqp_error{name = access_refused,
explanation = ErrMsg}) ->
rabbit_log_connection:error(
"Error on AMQP connection ~tp (~ts, state: ~tp):~n~ts",
[self(), ConnName, starting, ErrMsg]),
%% respect authentication failure notification capability
case rabbit_misc:table_lookup(Capabilities,
<<"authentication_failure_close">>) of
{bool, true} ->
send_error_on_channel0_and_close(Channel, Protocol, Reason, State);
_ ->
close_connection(terminate_channels(State))
end;
%% when loopback-only user tries to connect from a non-local host
%% when user tries to access a vhost it has no permissions for
handle_exception(State = #v1{connection = #connection{protocol = Protocol,
log_name = ConnName,
user = User},
connection_state = opening},
Channel, Reason = #amqp_error{name = not_allowed,
explanation = ErrMsg}) ->
rabbit_log_connection:error(
"Error on AMQP connection ~tp (~ts, user: '~ts', state: ~tp):~n~ts",
[self(), ConnName, User#user.username, opening, ErrMsg]),
send_error_on_channel0_and_close(Channel, Protocol, Reason, State);
handle_exception(State = #v1{connection = #connection{protocol = Protocol},
connection_state = CS = opening},
Channel, Reason = #amqp_error{}) ->
respond_and_close(State, Channel, Protocol, Reason,
{handshake_error, CS, Reason});
%% when negotiation fails, e.g. due to channel_max being higher than the
%% maximum allowed limit
handle_exception(State = #v1{connection = #connection{protocol = Protocol,
log_name = ConnName,
user = User},
connection_state = tuning},
Channel, Reason = #amqp_error{name = not_allowed,
explanation = ErrMsg}) ->
rabbit_log_connection:error(
"Error on AMQP connection ~tp (~ts,"
" user: '~ts', state: ~tp):~n~ts",
[self(), ConnName, User#user.username, tuning, ErrMsg]),
send_error_on_channel0_and_close(Channel, Protocol, Reason, State);
handle_exception(State, Channel, Reason) ->
%% We don't trust the client at this point - force them to wait
%% for a bit so they can't DOS us with repeated failed logins etc.
timer:sleep(?SILENT_CLOSE_DELAY * 1000),
throw({handshake_error, State#v1.connection_state, Channel, Reason}).
%% we've "lost sync" with the client and hence must not accept any
%% more input
-spec fatal_frame_error(_, _, _, _, _) -> no_return().
fatal_frame_error(Error, Type, Channel, Payload, State) ->
_ = frame_error(Error, Type, Channel, Payload, State),
%% grace period to allow transmission of error
timer:sleep(?SILENT_CLOSE_DELAY * 1000),
throw(fatal_frame_error).
frame_error(Error, Type, Channel, Payload, State) ->
{Str, Bin} = payload_snippet(Payload),
handle_exception(State, Channel,
rabbit_misc:amqp_error(frame_error,
"type ~tp, ~ts octets = ~tp: ~tp",
[Type, Str, Bin, Error], none)).
unexpected_frame(Type, Channel, Payload, State) ->
{Str, Bin} = payload_snippet(Payload),
handle_exception(State, Channel,
rabbit_misc:amqp_error(unexpected_frame,
"type ~tp, ~ts octets = ~tp",
[Type, Str, Bin], none)).
payload_snippet(Payload) when size(Payload) =< 16 ->
{"all", Payload};
payload_snippet(<<Snippet:16/binary, _/binary>>) ->
{"first 16", Snippet}.
%%--------------------------------------------------------------------------
create_channel(_Channel,
#v1{channel_count = ChannelCount,
connection = #connection{channel_max = ChannelMax}})
when ChannelMax /= 0 andalso ChannelCount >= ChannelMax ->
{error, rabbit_misc:amqp_error(
not_allowed, "number of channels opened (~w) has reached the "
"negotiated channel_max (~w)",
[ChannelCount, ChannelMax], 'none')};
create_channel(Channel,
#v1{sock = Sock,
queue_collector = Collector,
channel_sup_sup_pid = ChanSupSup,
channel_count = ChannelCount,
connection =
#connection{name = Name,
protocol = Protocol,
frame_max = FrameMax,
vhost = VHost,
capabilities = Capabilities,
user = #user{username = Username} = User}
} = State) ->
case is_over_limits(Username) of
false ->
{ok, _ChSupPid, {ChPid, AState}} =
rabbit_channel_sup_sup:start_channel(
ChanSupSup, {tcp, Sock, Channel, FrameMax, self(), Name,
Protocol, User, VHost, Capabilities,
Collector}),
MRef = erlang:monitor(process, ChPid),
put({ch_pid, ChPid}, {Channel, MRef}),
put({channel, Channel}, {ChPid, AState}),
{ok, {ChPid, AState}, State#v1{channel_count = ChannelCount + 1}};
{true, Limit, Fmt} ->
{error, rabbit_misc:amqp_error(
not_allowed,
Fmt,
[node(), Limit], 'none')}
end.
is_over_limits(Username) ->
case rabbit_auth_backend_internal:is_over_channel_limit(Username) of
false ->
case is_over_node_channel_limit() of
false ->
false;
{true, Limit} ->
Fmt =
"number of channels opened on node '~ts' has reached "
"the maximum allowed limit of (~w)",
{true, Limit, Fmt}
end;
{true, Limit} ->
Fmt =
"number of channels opened for user '~ts' has reached "
"the maximum allowed user limit of (~w)",
{true, Limit, Fmt}
end.
is_over_node_channel_limit() ->
case rabbit_misc:get_env(rabbit, channel_max_per_node, infinity) of
infinity ->
false;
NodeLimit ->
%% Only fetch this if a limit is set
CurrNodeChannels = rabbit_channel_tracking:channel_count_on_node(node()),
case CurrNodeChannels < NodeLimit of
true ->
false;
false ->
{true, NodeLimit}
end
end.
channel_cleanup(ChPid, State = #v1{channel_count = ChannelCount}) ->
case get({ch_pid, ChPid}) of
undefined -> {undefined, State};
{Channel, MRef} -> credit_flow:peer_down(ChPid),
erase({channel, Channel}),
erase({ch_pid, ChPid}),
erlang:demonitor(MRef, [flush]),
{Channel, State#v1{channel_count = ChannelCount - 1}}
end.
all_channels() -> [ChPid || {{ch_pid, ChPid}, _ChannelMRef} <- get()].
clean_up_all_channels(State) ->
CleanupFun = fun(ChPid) ->
channel_cleanup(ChPid, State)
end,
lists:foreach(CleanupFun, all_channels()).
%%--------------------------------------------------------------------------
handle_frame(Type, 0, Payload,
State = #v1{connection = #connection{protocol = Protocol}})
when ?IS_STOPPING(State) ->
case rabbit_command_assembler:analyze_frame(Type, Payload, Protocol) of
{method, MethodName, FieldsBin} ->
handle_method0(MethodName, FieldsBin, State);
_Other -> State
end;
handle_frame(Type, 0, Payload,
State = #v1{connection = #connection{protocol = Protocol}}) ->
case rabbit_command_assembler:analyze_frame(Type, Payload, Protocol) of
error -> frame_error(unknown_frame, Type, 0, Payload, State);
heartbeat -> State;