summaryrefslogtreecommitdiff
path: root/src/rabbit_router.erl
blob: ad653a2f2ac2dad7418b5631d2e8e8cb54490daa (plain)
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
%%   The contents of this file are subject to the Mozilla Public License
%%   Version 1.1 (the "License"); you may not use this file except in
%%   compliance with the License. You may obtain a copy of the License at
%%   http://www.mozilla.org/MPL/
%%
%%   Software distributed under the License is distributed on an "AS IS"
%%   basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%%   License for the specific language governing rights and limitations
%%   under the License.
%%
%%   The Original Code is RabbitMQ.
%%
%%   The Initial Developers of the Original Code are LShift Ltd,
%%   Cohesive Financial Technologies LLC, and Rabbit Technologies Ltd.
%%
%%   Portions created before 22-Nov-2008 00:00:00 GMT by LShift Ltd,
%%   Cohesive Financial Technologies LLC, or Rabbit Technologies Ltd
%%   are Copyright (C) 2007-2008 LShift Ltd, Cohesive Financial
%%   Technologies LLC, and Rabbit Technologies Ltd.
%%
%%   Portions created by LShift Ltd are Copyright (C) 2007-2009 LShift
%%   Ltd. Portions created by Cohesive Financial Technologies LLC are
%%   Copyright (C) 2007-2009 Cohesive Financial Technologies
%%   LLC. Portions created by Rabbit Technologies Ltd are Copyright
%%   (C) 2007-2009 Rabbit Technologies Ltd.
%%
%%   All Rights Reserved.
%%
%%   Contributor(s): ______________________________________.
%%

-module(rabbit_router).
-include("rabbit.hrl").

-behaviour(gen_server).

-export([start_link/0,
         deliver/5]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).

-define(SERVER, ?MODULE).

%% cross-node routing optimisation is disabled because of bug 19758.
-define(BUG19758, true).

%%----------------------------------------------------------------------------

-ifdef(use_specs).

-spec(start_link/0 :: () -> {'ok', pid()} | 'ignore' | {'error', any()}).
-spec(deliver/5 :: ([pid()], bool(), bool(), maybe(txn()), message()) ->
             {'ok', [pid()]} | {'error', 'unroutable' | 'not_delivered'}).

-endif.

%%----------------------------------------------------------------------------

start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

-ifdef(BUG19758).

deliver(QPids, Mandatory, Immediate, Txn, Message) ->
    check_delivery(Mandatory, Immediate,
                   run_bindings(QPids, Mandatory, Immediate, Txn, Message)).

-else.

deliver(QPids, Mandatory, Immediate, Txn, Message) ->
    %% we reduce inter-node traffic by grouping the qpids by node and
    %% only delivering one copy of the message to each node involved,
    %% which then in turn delivers it to its queues.
    deliver_per_node(
      dict:to_list(
        lists:foldl(
          fun (QPid, D) ->
                  dict:update(node(QPid),
                              fun (QPids1) -> [QPid | QPids1] end,
                              [QPid], D)
          end,
          dict:new(), QPids)),
      Mandatory, Immediate, Txn, Message).

deliver_per_node([{Node, QPids}], Mandatory, Immediate,
                 Txn, Message)
  when Node == node() ->
    %% optimisation
    check_delivery(Mandatory, Immediate,
                   run_bindings(QPids, Mandatory, Immediate, Txn, Message));
deliver_per_node(NodeQPids, Mandatory = false, Immediate = false,
                 Txn, Message) ->
    %% optimisation: when Mandatory = false and Immediate = false,
    %% rabbit_amqqueue:deliver in run_bindings below will deliver the
    %% message to the queue process asynchronously, and return true,
    %% which means all the QPids will always be returned. It is
    %% therefore safe to use a fire-and-forget cast here and return
    %% the QPids - the semantics is preserved. This scales much better
    %% than the non-immediate case below.
    {ok, lists:flatmap(
           fun ({Node, QPids}) ->
                   gen_server:cast(
                     {?SERVER, Node},
                     {deliver, QPids, Mandatory, Immediate, Txn, Message}),
                   QPids
           end,
           NodeQPids)};
deliver_per_node(NodeQPids, Mandatory, Immediate,
                 Txn, Message) ->
    R = rabbit_misc:upmap(
          fun ({Node, QPids}) ->
                  try gen_server:call(
                        {?SERVER, Node},
                        {deliver, QPids, Mandatory, Immediate, Txn, Message})
                  catch
                      _Class:_Reason ->
                          %% TODO: figure out what to log (and do!) here
                          {false, []}
                  end
          end,
          NodeQPids),
    {Routed, Handled} =
        lists:foldl(fun ({Routed, Handled}, {RoutedAcc, HandledAcc}) ->
                            {Routed or RoutedAcc,
                             %% we do the concatenation below, which
                             %% should be faster
                             [Handled | HandledAcc]}
                    end,
                    {false, []},
                    R),
    check_delivery(Mandatory, Immediate, {Routed, lists:append(Handled)}).

-endif.

%%--------------------------------------------------------------------

init([]) ->
    {ok, no_state}.

handle_call({deliver, QPids, Mandatory, Immediate, Txn, Message},
            From, State) ->
    spawn(
      fun () ->
              R = run_bindings(QPids, Mandatory, Immediate, Txn, Message),
              gen_server:reply(From, R)
      end),
    {noreply, State}.

handle_cast({deliver, QPids, Mandatory, Immediate, Txn, Message},
            State) ->
    %% in order to preserve message ordering we must not spawn here
    run_bindings(QPids, Mandatory, Immediate, Txn, Message),
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%--------------------------------------------------------------------

run_bindings(QPids, IsMandatory, IsImmediate, Txn, Message) ->
    lists:foldl(
      fun (QPid, {Routed, Handled}) ->
              case catch rabbit_amqqueue:deliver(IsMandatory, IsImmediate,
                                                 Txn, Message, QPid) of
                  true              -> {true, [QPid | Handled]};
                  false             -> {true, Handled};
                  {'EXIT', _Reason} -> {Routed, Handled}
              end
      end,
      {false, []},
      QPids).

%% check_delivery(Mandatory, Immediate, {WasRouted, QPids})
check_delivery(true, _   , {false, []}) -> {error, unroutable};
check_delivery(_   , true, {_    , []}) -> {error, not_delivered};
check_delivery(_   , _   , {_    , Qs}) -> {ok, Qs}.