src/gm.erl
author Simon MacMullen <simon@rabbitmq.com>
Thu Apr 17 14:48:59 2014 +0100 (5 hours ago)
changeset 13343 09705e6df648
parent 13303 a5e10d286a75
permissions -rw-r--r--
stable to default
     1 %% The contents of this file are subject to the Mozilla Public License
     2 %% Version 1.1 (the "License"); you may not use this file except in
     3 %% compliance with the License. You may obtain a copy of the License at
     4 %% http://www.mozilla.org/MPL/
     5 %%
     6 %% Software distributed under the License is distributed on an "AS IS"
     7 %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     8 %% License for the specific language governing rights and limitations
     9 %% under the License.
    10 %%
    11 %% The Original Code is RabbitMQ.
    12 %%
    13 %% The Initial Developer of the Original Code is GoPivotal, Inc.
    14 %% Copyright (c) 2007-2014 GoPivotal, Inc.  All rights reserved.
    15 %%
    16 
    17 -module(gm).
    18 
    19 %% Guaranteed Multicast
    20 %% ====================
    21 %%
    22 %% This module provides the ability to create named groups of
    23 %% processes to which members can be dynamically added and removed,
    24 %% and for messages to be broadcast within the group that are
    25 %% guaranteed to reach all members of the group during the lifetime of
    26 %% the message. The lifetime of a message is defined as being, at a
    27 %% minimum, the time from which the message is first sent to any
    28 %% member of the group, up until the time at which it is known by the
    29 %% member who published the message that the message has reached all
    30 %% group members.
    31 %%
    32 %% The guarantee given is that provided a message, once sent, makes it
    33 %% to members who do not all leave the group, the message will
    34 %% continue to propagate to all group members.
    35 %%
    36 %% Another way of stating the guarantee is that if member P publishes
    37 %% messages m and m', then for all members P', if P' is a member of
    38 %% the group prior to the publication of m, and P' receives m', then
    39 %% P' will receive m.
    40 %%
    41 %% Note that only local-ordering is enforced: i.e. if member P sends
    42 %% message m and then message m', then for-all members P', if P'
    43 %% receives m and m', then they will receive m' after m. Causality
    44 %% ordering is _not_ enforced. I.e. if member P receives message m
    45 %% and as a result publishes message m', there is no guarantee that
    46 %% other members P' will receive m before m'.
    47 %%
    48 %%
    49 %% API Use
    50 %% -------
    51 %%
    52 %% Mnesia must be started. Use the idempotent create_tables/0 function
    53 %% to create the tables required.
    54 %%
    55 %% start_link/3
    56 %% Provide the group name, the callback module name, and any arguments
    57 %% you wish to be passed into the callback module's functions. The
    58 %% joined/2 function will be called when we have joined the group,
    59 %% with the arguments passed to start_link and a list of the current
    60 %% members of the group. See the callbacks specs and the comments
    61 %% below for further details of the callback functions.
    62 %%
    63 %% leave/1
    64 %% Provide the Pid. Removes the Pid from the group. The callback
    65 %% terminate/2 function will be called.
    66 %%
    67 %% broadcast/2
    68 %% Provide the Pid and a Message. The message will be sent to all
    69 %% members of the group as per the guarantees given above. This is a
    70 %% cast and the function call will return immediately. There is no
    71 %% guarantee that the message will reach any member of the group.
    72 %%
    73 %% confirmed_broadcast/2
    74 %% Provide the Pid and a Message. As per broadcast/2 except that this
    75 %% is a call, not a cast, and only returns 'ok' once the Message has
    76 %% reached every member of the group. Do not call
    77 %% confirmed_broadcast/2 directly from the callback module otherwise
    78 %% you will deadlock the entire group.
    79 %%
    80 %% info/1
    81 %% Provide the Pid. Returns a proplist with various facts, including
    82 %% the group name and the current group members.
    83 %%
    84 %% validate_members/2
    85 %% Check whether a given member list agrees with the chosen member's
    86 %% view. Any differences will be communicated via the members_changed
    87 %% callback. If there are no differences then there will be no reply.
    88 %% Note that members will not necessarily share the same view.
    89 %%
    90 %% forget_group/1
    91 %% Provide the group name. Removes its mnesia record. Makes no attempt
    92 %% to ensure the group is empty.
    93 %%
    94 %% Implementation Overview
    95 %% -----------------------
    96 %%
    97 %% One possible means of implementation would be a fan-out from the
    98 %% sender to every member of the group. This would require that the
    99 %% group is fully connected, and, in the event that the original
   100 %% sender of the message disappears from the group before the message
   101 %% has made it to every member of the group, raises questions as to
   102 %% who is responsible for sending on the message to new group members.
   103 %% In particular, the issue is with [ Pid ! Msg || Pid <- Members ] -
   104 %% if the sender dies part way through, who is responsible for
   105 %% ensuring that the remaining Members receive the Msg? In the event
   106 %% that within the group, messages sent are broadcast from a subset of
   107 %% the members, the fan-out arrangement has the potential to
   108 %% substantially impact the CPU and network workload of such members,
   109 %% as such members would have to accommodate the cost of sending each
   110 %% message to every group member.
   111 %%
   112 %% Instead, if the members of the group are arranged in a chain, then
   113 %% it becomes easier to reason about who within the group has received
   114 %% each message and who has not. It eases issues of responsibility: in
   115 %% the event of a group member disappearing, the nearest upstream
   116 %% member of the chain is responsible for ensuring that messages
   117 %% continue to propagate down the chain. It also results in equal
   118 %% distribution of sending and receiving workload, even if all
   119 %% messages are being sent from just a single group member. This
   120 %% configuration has the further advantage that it is not necessary
   121 %% for every group member to know of every other group member, and
   122 %% even that a group member does not have to be accessible from all
   123 %% other group members.
   124 %%
   125 %% Performance is kept high by permitting pipelining and all
   126 %% communication between joined group members is asynchronous. In the
   127 %% chain A -> B -> C -> D, if A sends a message to the group, it will
   128 %% not directly contact C or D. However, it must know that D receives
   129 %% the message (in addition to B and C) before it can consider the
   130 %% message fully sent. A simplistic implementation would require that
   131 %% D replies to C, C replies to B and B then replies to A. This would
   132 %% result in a propagation delay of twice the length of the chain. It
   133 %% would also require, in the event of the failure of C, that D knows
   134 %% to directly contact B and issue the necessary replies. Instead, the
   135 %% chain forms a ring: D sends the message on to A: D does not
   136 %% distinguish A as the sender, merely as the next member (downstream)
   137 %% within the chain (which has now become a ring). When A receives
   138 %% from D messages that A sent, it knows that all members have
   139 %% received the message. However, the message is not dead yet: if C
   140 %% died as B was sending to C, then B would need to detect the death
   141 %% of C and forward the message on to D instead: thus every node has
   142 %% to remember every message published until it is told that it can
   143 %% forget about the message. This is essential not just for dealing
   144 %% with failure of members, but also for the addition of new members.
   145 %%
   146 %% Thus once A receives the message back again, it then sends to B an
   147 %% acknowledgement for the message, indicating that B can now forget
   148 %% about the message. B does so, and forwards the ack to C. C forgets
   149 %% the message, and forwards the ack to D, which forgets the message
   150 %% and finally forwards the ack back to A. At this point, A takes no
   151 %% further action: the message and its acknowledgement have made it to
   152 %% every member of the group. The message is now dead, and any new
   153 %% member joining the group at this point will not receive the
   154 %% message.
   155 %%
   156 %% We therefore have two roles:
   157 %%
   158 %% 1. The sender, who upon receiving their own messages back, must
   159 %% then send out acknowledgements, and upon receiving their own
   160 %% acknowledgements back perform no further action.
   161 %%
   162 %% 2. The other group members who upon receiving messages and
   163 %% acknowledgements must update their own internal state accordingly
   164 %% (the sending member must also do this in order to be able to
   165 %% accommodate failures), and forwards messages on to their downstream
   166 %% neighbours.
   167 %%
   168 %%
   169 %% Implementation: It gets trickier
   170 %% --------------------------------
   171 %%
   172 %% Chain A -> B -> C -> D
   173 %%
   174 %% A publishes a message which B receives. A now dies. B and D will
   175 %% detect the death of A, and will link up, thus the chain is now B ->
   176 %% C -> D. B forwards A's message on to C, who forwards it to D, who
   177 %% forwards it to B. Thus B is now responsible for A's messages - both
   178 %% publications and acknowledgements that were in flight at the point
   179 %% at which A died. Even worse is that this is transitive: after B
   180 %% forwards A's message to C, B dies as well. Now C is not only
   181 %% responsible for B's in-flight messages, but is also responsible for
   182 %% A's in-flight messages.
   183 %%
   184 %% Lemma 1: A member can only determine which dead members they have
   185 %% inherited responsibility for if there is a total ordering on the
   186 %% conflicting additions and subtractions of members from the group.
   187 %%
   188 %% Consider the simultaneous death of B and addition of B' that
   189 %% transitions a chain from A -> B -> C to A -> B' -> C. Either B' or
   190 %% C is responsible for in-flight messages from B. It is easy to
   191 %% ensure that at least one of them thinks they have inherited B, but
   192 %% if we do not ensure that exactly one of them inherits B, then we
   193 %% could have B' converting publishes to acks, which then will crash C
   194 %% as C does not believe it has issued acks for those messages.
   195 %%
   196 %% More complex scenarios are easy to concoct: A -> B -> C -> D -> E
   197 %% becoming A -> C' -> E. Who has inherited which of B, C and D?
   198 %%
   199 %% However, for non-conflicting membership changes, only a partial
   200 %% ordering is required. For example, A -> B -> C becoming A -> A' ->
   201 %% B. The addition of A', between A and B can have no conflicts with
   202 %% the death of C: it is clear that A has inherited C's messages.
   203 %%
   204 %% For ease of implementation, we adopt the simple solution, of
   205 %% imposing a total order on all membership changes.
   206 %%
   207 %% On the death of a member, it is ensured the dead member's
   208 %% neighbours become aware of the death, and the upstream neighbour
   209 %% now sends to its new downstream neighbour its state, including the
   210 %% messages pending acknowledgement. The downstream neighbour can then
   211 %% use this to calculate which publishes and acknowledgements it has
   212 %% missed out on, due to the death of its old upstream. Thus the
   213 %% downstream can catch up, and continues the propagation of messages
   214 %% through the group.
   215 %%
   216 %% Lemma 2: When a member is joining, it must synchronously
   217 %% communicate with its upstream member in order to receive its
   218 %% starting state atomically with its addition to the group.
   219 %%
   220 %% New members must start with the same state as their nearest
   221 %% upstream neighbour. This ensures that it is not surprised by
   222 %% acknowledgements they are sent, and that should their downstream
   223 %% neighbour die, they are able to send the correct state to their new
   224 %% downstream neighbour to ensure it can catch up. Thus in the
   225 %% transition A -> B -> C becomes A -> A' -> B -> C becomes A -> A' ->
   226 %% C, A' must start with the state of A, so that it can send C the
   227 %% correct state when B dies, allowing C to detect any missed
   228 %% messages.
   229 %%
   230 %% If A' starts by adding itself to the group membership, A could then
   231 %% die, without A' having received the necessary state from A. This
   232 %% would leave A' responsible for in-flight messages from A, but
   233 %% having the least knowledge of all, of those messages. Thus A' must
   234 %% start by synchronously calling A, which then immediately sends A'
   235 %% back its state. A then adds A' to the group. If A dies at this
   236 %% point then A' will be able to see this (as A' will fail to appear
   237 %% in the group membership), and thus A' will ignore the state it
   238 %% receives from A, and will simply repeat the process, trying to now
   239 %% join downstream from some other member. This ensures that should
   240 %% the upstream die as soon as the new member has been joined, the new
   241 %% member is guaranteed to receive the correct state, allowing it to
   242 %% correctly process messages inherited due to the death of its
   243 %% upstream neighbour.
   244 %%
   245 %% The canonical definition of the group membership is held by a
   246 %% distributed database. Whilst this allows the total ordering of
   247 %% changes to be achieved, it is nevertheless undesirable to have to
   248 %% query this database for the current view, upon receiving each
   249 %% message. Instead, we wish for members to be able to cache a view of
   250 %% the group membership, which then requires a cache invalidation
   251 %% mechanism. Each member maintains its own view of the group
   252 %% membership. Thus when the group's membership changes, members may
   253 %% need to become aware of such changes in order to be able to
   254 %% accurately process messages they receive. Because of the
   255 %% requirement of a total ordering of conflicting membership changes,
   256 %% it is not possible to use the guaranteed broadcast mechanism to
   257 %% communicate these changes: to achieve the necessary ordering, it
   258 %% would be necessary for such messages to be published by exactly one
   259 %% member, which can not be guaranteed given that such a member could
   260 %% die.
   261 %%
   262 %% The total ordering we enforce on membership changes gives rise to a
   263 %% view version number: every change to the membership creates a
   264 %% different view, and the total ordering permits a simple
   265 %% monotonically increasing view version number.
   266 %%
   267 %% Lemma 3: If a message is sent from a member that holds view version
   268 %% N, it can be correctly processed by any member receiving the
   269 %% message with a view version >= N.
   270 %%
   271 %% Initially, let us suppose that each view contains the ordering of
   272 %% every member that was ever part of the group. Dead members are
   273 %% marked as such. Thus we have a ring of members, some of which are
   274 %% dead, and are thus inherited by the nearest alive downstream
   275 %% member.
   276 %%
   277 %% In the chain A -> B -> C, all three members initially have view
   278 %% version 1, which reflects reality. B publishes a message, which is
   279 %% forward by C to A. B now dies, which A notices very quickly. Thus A
   280 %% updates the view, creating version 2. It now forwards B's
   281 %% publication, sending that message to its new downstream neighbour,
   282 %% C. This happens before C is aware of the death of B. C must become
   283 %% aware of the view change before it interprets the message its
   284 %% received, otherwise it will fail to learn of the death of B, and
   285 %% thus will not realise it has inherited B's messages (and will
   286 %% likely crash).
   287 %%
   288 %% Thus very simply, we have that each subsequent view contains more
   289 %% information than the preceding view.
   290 %%
   291 %% However, to avoid the views growing indefinitely, we need to be
   292 %% able to delete members which have died _and_ for which no messages
   293 %% are in-flight. This requires that upon inheriting a dead member, we
   294 %% know the last publication sent by the dead member (this is easy: we
   295 %% inherit a member because we are the nearest downstream member which
   296 %% implies that we know at least as much than everyone else about the
   297 %% publications of the dead member), and we know the earliest message
   298 %% for which the acknowledgement is still in flight.
   299 %%
   300 %% In the chain A -> B -> C, when B dies, A will send to C its state
   301 %% (as C is the new downstream from A), allowing C to calculate which
   302 %% messages it has missed out on (described above). At this point, C
   303 %% also inherits B's messages. If that state from A also includes the
   304 %% last message published by B for which an acknowledgement has been
   305 %% seen, then C knows exactly which further acknowledgements it must
   306 %% receive (also including issuing acknowledgements for publications
   307 %% still in-flight that it receives), after which it is known there
   308 %% are no more messages in flight for B, thus all evidence that B was
   309 %% ever part of the group can be safely removed from the canonical
   310 %% group membership.
   311 %%
   312 %% Thus, for every message that a member sends, it includes with that
   313 %% message its view version. When a member receives a message it will
   314 %% update its view from the canonical copy, should its view be older
   315 %% than the view version included in the message it has received.
   316 %%
   317 %% The state held by each member therefore includes the messages from
   318 %% each publisher pending acknowledgement, the last publication seen
   319 %% from that publisher, and the last acknowledgement from that
   320 %% publisher. In the case of the member's own publications or
   321 %% inherited members, this last acknowledgement seen state indicates
   322 %% the last acknowledgement retired, rather than sent.
   323 %%
   324 %%
   325 %% Proof sketch
   326 %% ------------
   327 %%
   328 %% We need to prove that with the provided operational semantics, we
   329 %% can never reach a state that is not well formed from a well-formed
   330 %% starting state.
   331 %%
   332 %% Operational semantics (small step): straight-forward message
   333 %% sending, process monitoring, state updates.
   334 %%
   335 %% Well formed state: dead members inherited by exactly one non-dead
   336 %% member; for every entry in anyone's pending-acks, either (the
   337 %% publication of the message is in-flight downstream from the member
   338 %% and upstream from the publisher) or (the acknowledgement of the
   339 %% message is in-flight downstream from the publisher and upstream
   340 %% from the member).
   341 %%
   342 %% Proof by induction on the applicable operational semantics.
   343 %%
   344 %%
   345 %% Related work
   346 %% ------------
   347 %%
   348 %% The ring configuration and double traversal of messages around the
   349 %% ring is similar (though developed independently) to the LCR
   350 %% protocol by [Levy 2008]. However, LCR differs in several
   351 %% ways. Firstly, by using vector clocks, it enforces a total order of
   352 %% message delivery, which is unnecessary for our purposes. More
   353 %% significantly, it is built on top of a "group communication system"
   354 %% which performs the group management functions, taking
   355 %% responsibility away from the protocol as to how to cope with safely
   356 %% adding and removing members. When membership changes do occur, the
   357 %% protocol stipulates that every member must perform communication
   358 %% with every other member of the group, to ensure all outstanding
   359 %% deliveries complete, before the entire group transitions to the new
   360 %% view. This, in total, requires two sets of all-to-all synchronous
   361 %% communications.
   362 %%
   363 %% This is not only rather inefficient, but also does not explain what
   364 %% happens upon the failure of a member during this process. It does
   365 %% though entirely avoid the need for inheritance of responsibility of
   366 %% dead members that our protocol incorporates.
   367 %%
   368 %% In [Marandi et al 2010], a Paxos-based protocol is described. This
   369 %% work explicitly focuses on the efficiency of communication. LCR
   370 %% (and our protocol too) are more efficient, but at the cost of
   371 %% higher latency. The Ring-Paxos protocol is itself built on top of
   372 %% IP-multicast, which rules it out for many applications where
   373 %% point-to-point communication is all that can be required. They also
   374 %% have an excellent related work section which I really ought to
   375 %% read...
   376 %%
   377 %%
   378 %% [Levy 2008] The Complexity of Reliable Distributed Storage, 2008.
   379 %% [Marandi et al 2010] Ring Paxos: A High-Throughput Atomic Broadcast
   380 %% Protocol
   381 
   382 
   383 -behaviour(gen_server2).
   384 
   385 -export([create_tables/0, start_link/4, leave/1, broadcast/2, broadcast/3,
   386          confirmed_broadcast/2, info/1, validate_members/2, forget_group/1]).
   387 
   388 -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
   389          code_change/3, prioritise_info/3]).
   390 
   391 -ifndef(use_specs).
   392 -export([behaviour_info/1]).
   393 -endif.
   394 
   395 -export([table_definitions/0]).
   396 
   397 -define(GROUP_TABLE, gm_group).
   398 -define(MAX_BUFFER_SIZE, 100000000). %% 100MB
   399 -define(HIBERNATE_AFTER_MIN, 1000).
   400 -define(DESIRED_HIBERNATE, 10000).
   401 -define(BROADCAST_TIMER, 25).
   402 -define(VERSION_START, 0).
   403 -define(SETS, ordsets).
   404 -define(DICT, orddict).
   405 
   406 -record(state,
   407         { self,
   408           left,
   409           right,
   410           group_name,
   411           module,
   412           view,
   413           pub_count,
   414           members_state,
   415           callback_args,
   416           confirms,
   417           broadcast_buffer,
   418           broadcast_buffer_sz,
   419           broadcast_timer,
   420           txn_executor
   421         }).
   422 
   423 -record(gm_group, { name, version, members }).
   424 
   425 -record(view_member, { id, aliases, left, right }).
   426 
   427 -record(member, { pending_ack, last_pub, last_ack }).
   428 
   429 -define(TABLE, {?GROUP_TABLE, [{record_name, gm_group},
   430                                {attributes, record_info(fields, gm_group)}]}).
   431 -define(TABLE_MATCH, {match, #gm_group { _ = '_' }}).
   432 
   433 -define(TAG, '$gm').
   434 
   435 -ifdef(use_specs).
   436 
   437 -export_type([group_name/0]).
   438 
   439 -type(group_name() :: any()).
   440 -type(txn_fun() :: fun((fun(() -> any())) -> any())).
   441 
   442 -spec(create_tables/0 :: () -> 'ok' | {'aborted', any()}).
   443 -spec(start_link/4 :: (group_name(), atom(), any(), txn_fun()) ->
   444                            rabbit_types:ok_pid_or_error()).
   445 -spec(leave/1 :: (pid()) -> 'ok').
   446 -spec(broadcast/2 :: (pid(), any()) -> 'ok').
   447 -spec(confirmed_broadcast/2 :: (pid(), any()) -> 'ok').
   448 -spec(info/1 :: (pid()) -> rabbit_types:infos()).
   449 -spec(validate_members/2 :: (pid(), [pid()]) -> 'ok').
   450 -spec(forget_group/1 :: (group_name()) -> 'ok').
   451 
   452 %% The joined, members_changed and handle_msg callbacks can all return
   453 %% any of the following terms:
   454 %%
   455 %% 'ok' - the callback function returns normally
   456 %%
   457 %% {'stop', Reason} - the callback indicates the member should stop
   458 %% with reason Reason and should leave the group.
   459 %%
   460 %% {'become', Module, Args} - the callback indicates that the callback
   461 %% module should be changed to Module and that the callback functions
   462 %% should now be passed the arguments Args. This allows the callback
   463 %% module to be dynamically changed.
   464 
   465 %% Called when we've successfully joined the group. Supplied with Args
   466 %% provided in start_link, plus current group members.
   467 -callback joined(Args :: term(), Members :: [pid()]) ->
   468     ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
   469 
   470 %% Supplied with Args provided in start_link, the list of new members
   471 %% and the list of members previously known to us that have since
   472 %% died. Note that if a member joins and dies very quickly, it's
   473 %% possible that we will never see that member appear in either births
   474 %% or deaths. However we are guaranteed that (1) we will see a member
   475 %% joining either in the births here, or in the members passed to
   476 %% joined/2 before receiving any messages from it; and (2) we will not
   477 %% see members die that we have not seen born (or supplied in the
   478 %% members to joined/2).
   479 -callback members_changed(Args :: term(),
   480                           Births :: [pid()], Deaths :: [pid()]) ->
   481     ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
   482 
   483 %% Supplied with Args provided in start_link, the sender, and the
   484 %% message. This does get called for messages injected by this member,
   485 %% however, in such cases, there is no special significance of this
   486 %% invocation: it does not indicate that the message has made it to
   487 %% any other members, let alone all other members.
   488 -callback handle_msg(Args :: term(), From :: pid(), Message :: term()) ->
   489     ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
   490 
   491 %% Called on gm member termination as per rules in gen_server, with
   492 %% the Args provided in start_link plus the termination Reason.
   493 -callback terminate(Args :: term(), Reason :: term()) ->
   494     ok | term().
   495 
   496 -else.
   497 
   498 behaviour_info(callbacks) ->
   499     [{joined, 2}, {members_changed, 3}, {handle_msg, 3}, {terminate, 2}];
   500 behaviour_info(_Other) ->
   501     undefined.
   502 
   503 -endif.
   504 
   505 create_tables() ->
   506     create_tables([?TABLE]).
   507 
   508 create_tables([]) ->
   509     ok;
   510 create_tables([{Table, Attributes} | Tables]) ->
   511     case mnesia:create_table(Table, Attributes) of
   512         {atomic, ok}                          -> create_tables(Tables);
   513         {aborted, {already_exists, gm_group}} -> create_tables(Tables);
   514         Err                                   -> Err
   515     end.
   516 
   517 table_definitions() ->
   518     {Name, Attributes} = ?TABLE,
   519     [{Name, [?TABLE_MATCH | Attributes]}].
   520 
   521 start_link(GroupName, Module, Args, TxnFun) ->
   522     gen_server2:start_link(?MODULE, [GroupName, Module, Args, TxnFun], []).
   523 
   524 leave(Server) ->
   525     gen_server2:cast(Server, leave).
   526 
   527 broadcast(Server, Msg) -> broadcast(Server, Msg, 0).
   528 
   529 broadcast(Server, Msg, SizeHint) ->
   530     gen_server2:cast(Server, {broadcast, Msg, SizeHint}).
   531 
   532 confirmed_broadcast(Server, Msg) ->
   533     gen_server2:call(Server, {confirmed_broadcast, Msg}, infinity).
   534 
   535 info(Server) ->
   536     gen_server2:call(Server, info, infinity).
   537 
   538 validate_members(Server, Members) ->
   539     gen_server2:cast(Server, {validate_members, Members}).
   540 
   541 forget_group(GroupName) ->
   542     {atomic, ok} = mnesia:sync_transaction(
   543                      fun () ->
   544                              mnesia:delete({?GROUP_TABLE, GroupName})
   545                      end),
   546     ok.
   547 
   548 init([GroupName, Module, Args, TxnFun]) ->
   549     put(process_name, {?MODULE, GroupName}),
   550     {MegaSecs, Secs, MicroSecs} = now(),
   551     random:seed(MegaSecs, Secs, MicroSecs),
   552     Self = make_member(GroupName),
   553     gen_server2:cast(self(), join),
   554     {ok, #state { self                = Self,
   555                   left                = {Self, undefined},
   556                   right               = {Self, undefined},
   557                   group_name          = GroupName,
   558                   module              = Module,
   559                   view                = undefined,
   560                   pub_count           = -1,
   561                   members_state       = undefined,
   562                   callback_args       = Args,
   563                   confirms            = queue:new(),
   564                   broadcast_buffer    = [],
   565                   broadcast_buffer_sz = 0,
   566                   broadcast_timer     = undefined,
   567                   txn_executor        = TxnFun }, hibernate,
   568      {backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE}}.
   569 
   570 
   571 handle_call({confirmed_broadcast, _Msg}, _From,
   572             State = #state { members_state = undefined }) ->
   573     reply(not_joined, State);
   574 
   575 handle_call({confirmed_broadcast, Msg}, _From,
   576             State = #state { self          = Self,
   577                              right         = {Self, undefined},
   578                              module        = Module,
   579                              callback_args = Args }) ->
   580     handle_callback_result({Module:handle_msg(Args, get_pid(Self), Msg),
   581                            ok, State});
   582 
   583 handle_call({confirmed_broadcast, Msg}, From, State) ->
   584     internal_broadcast(Msg, From, 0, State);
   585 
   586 handle_call(info, _From,
   587             State = #state { members_state = undefined }) ->
   588     reply(not_joined, State);
   589 
   590 handle_call(info, _From, State = #state { group_name = GroupName,
   591                                           module     = Module,
   592                                           view       = View }) ->
   593     reply([{group_name,    GroupName},
   594            {module,        Module},
   595            {group_members, get_pids(alive_view_members(View))}], State);
   596 
   597 handle_call({add_on_right, _NewMember}, _From,
   598             State = #state { members_state = undefined }) ->
   599     reply(not_ready, State);
   600 
   601 handle_call({add_on_right, NewMember}, _From,
   602             State = #state { self          = Self,
   603                              group_name    = GroupName,
   604                              view          = View,
   605                              members_state = MembersState,
   606                              module        = Module,
   607                              callback_args = Args,
   608                              txn_executor  = TxnFun }) ->
   609     {MembersState1, Group} =
   610       record_new_member_in_group(
   611         GroupName, Self, NewMember,
   612         fun (Group1) ->
   613                 View1 = group_to_view(Group1),
   614                 MembersState1 = remove_erased_members(MembersState, View1),
   615                 ok = send_right(NewMember, View1,
   616                                 {catchup, Self,
   617                                  prepare_members_state(MembersState1)}),
   618                 MembersState1
   619         end, TxnFun),
   620     View2 = group_to_view(Group),
   621     State1 = check_neighbours(State #state { view          = View2,
   622                                              members_state = MembersState1 }),
   623     Result = callback_view_changed(Args, Module, View, View2),
   624     handle_callback_result({Result, {ok, Group}, State1}).
   625 
   626 
   627 handle_cast({?TAG, ReqVer, Msg},
   628             State = #state { view          = View,
   629                              members_state = MembersState,
   630                              group_name    = GroupName,
   631                              module        = Module,
   632                              callback_args = Args }) ->
   633     {Result, State1} =
   634         case needs_view_update(ReqVer, View) of
   635             true  -> View1 = group_to_view(read_group(GroupName)),
   636                      MemberState1 = remove_erased_members(MembersState, View1),
   637                      {callback_view_changed(Args, Module, View, View1),
   638                       check_neighbours(
   639                         State #state { view          = View1,
   640                                        members_state = MemberState1 })};
   641             false -> {ok, State}
   642         end,
   643     handle_callback_result(
   644       if_callback_success(
   645         Result, fun handle_msg_true/3, fun handle_msg_false/3, Msg, State1));
   646 
   647 handle_cast({broadcast, _Msg, _SizeHint},
   648             State = #state { members_state = undefined }) ->
   649     noreply(State);
   650 
   651 handle_cast({broadcast, Msg, _SizeHint},
   652             State = #state { self          = Self,
   653                              right         = {Self, undefined},
   654                              module        = Module,
   655                              callback_args = Args }) ->
   656     handle_callback_result({Module:handle_msg(Args, get_pid(Self), Msg),
   657                             State});
   658 
   659 handle_cast({broadcast, Msg, SizeHint}, State) ->
   660     internal_broadcast(Msg, none, SizeHint, State);
   661 
   662 handle_cast(join, State = #state { self          = Self,
   663                                    group_name    = GroupName,
   664                                    members_state = undefined,
   665                                    module        = Module,
   666                                    callback_args = Args,
   667                                    txn_executor  = TxnFun }) ->
   668     View = join_group(Self, GroupName, TxnFun),
   669     MembersState =
   670         case alive_view_members(View) of
   671             [Self] -> blank_member_state();
   672             _      -> undefined
   673         end,
   674     State1 = check_neighbours(State #state { view          = View,
   675                                              members_state = MembersState }),
   676     handle_callback_result(
   677       {Module:joined(Args, get_pids(all_known_members(View))), State1});
   678 
   679 handle_cast({validate_members, OldMembers},
   680             State = #state { view          = View,
   681                              module        = Module,
   682                              callback_args = Args }) ->
   683     NewMembers = get_pids(all_known_members(View)),
   684     Births = NewMembers -- OldMembers,
   685     Deaths = OldMembers -- NewMembers,
   686     case {Births, Deaths} of
   687         {[], []}  -> noreply(State);
   688         _         -> Result = Module:members_changed(Args, Births, Deaths),
   689                      handle_callback_result({Result, State})
   690     end;
   691 
   692 handle_cast(leave, State) ->
   693     {stop, normal, State}.
   694 
   695 
   696 handle_info(flush, State) ->
   697     noreply(
   698       flush_broadcast_buffer(State #state { broadcast_timer = undefined }));
   699 
   700 handle_info(timeout, State) ->
   701     noreply(flush_broadcast_buffer(State));
   702 
   703 handle_info({'DOWN', MRef, process, _Pid, Reason},
   704             State = #state { self          = Self,
   705                              left          = Left,
   706                              right         = Right,
   707                              group_name    = GroupName,
   708                              confirms      = Confirms,
   709                              txn_executor  = TxnFun }) ->
   710     Member = case {Left, Right} of
   711                  {{Member1, MRef}, _} -> Member1;
   712                  {_, {Member1, MRef}} -> Member1;
   713                  _                    -> undefined
   714              end,
   715     case {Member, Reason} of
   716         {undefined, _} ->
   717             noreply(State);
   718         {_, {shutdown, ring_shutdown}} ->
   719             noreply(State);
   720         _ ->
   721             View1 = group_to_view(record_dead_member_in_group(
   722                                     Member, GroupName, TxnFun)),
   723             State1 = case alive_view_members(View1) of
   724                          [Self] -> State #state {
   725                                      members_state = blank_member_state(),
   726                                      confirms      = purge_confirms(Confirms) };
   727                          _      -> State
   728                      end,
   729             handle_callback_result(maybe_erase_aliases(State1, View1))
   730     end.
   731 
   732 
   733 terminate(Reason, State = #state { module        = Module,
   734                                    callback_args = Args }) ->
   735     flush_broadcast_buffer(State),
   736     Module:terminate(Args, Reason).
   737 
   738 
   739 code_change(_OldVsn, State, _Extra) ->
   740     {ok, State}.
   741 
   742 prioritise_info(flush, _Len, _State) ->
   743     1;
   744 prioritise_info({'DOWN', _MRef, process, _Pid, _Reason}, _Len,
   745                 #state { members_state = MS }) when MS /= undefined ->
   746     1;
   747 prioritise_info(_, _Len, _State) ->
   748     0.
   749 
   750 
   751 handle_msg(check_neighbours, State) ->
   752     %% no-op - it's already been done by the calling handle_cast
   753     {ok, State};
   754 
   755 handle_msg({catchup, Left, MembersStateLeft},
   756            State = #state { self          = Self,
   757                             left          = {Left, _MRefL},
   758                             right         = {Right, _MRefR},
   759                             view          = View,
   760                             members_state = undefined }) ->
   761     ok = send_right(Right, View, {catchup, Self, MembersStateLeft}),
   762     MembersStateLeft1 = build_members_state(MembersStateLeft),
   763     {ok, State #state { members_state = MembersStateLeft1 }};
   764 
   765 handle_msg({catchup, Left, MembersStateLeft},
   766            State = #state { self = Self,
   767                             left = {Left, _MRefL},
   768                             view = View,
   769                             members_state = MembersState })
   770   when MembersState =/= undefined ->
   771     MembersStateLeft1 = build_members_state(MembersStateLeft),
   772     AllMembers = lists:usort(?DICT:fetch_keys(MembersState) ++
   773                                  ?DICT:fetch_keys(MembersStateLeft1)),
   774     {MembersState1, Activity} =
   775         lists:foldl(
   776           fun (Id, MembersStateActivity) ->
   777                   #member { pending_ack = PALeft, last_ack = LA } =
   778                       find_member_or_blank(Id, MembersStateLeft1),
   779                   with_member_acc(
   780                     fun (#member { pending_ack = PA } = Member, Activity1) ->
   781                             case is_member_alias(Id, Self, View) of
   782                                 true ->
   783                                     {_AcksInFlight, Pubs, _PA1} =
   784                                         find_prefix_common_suffix(PALeft, PA),
   785                                     {Member #member { last_ack = LA },
   786                                      activity_cons(Id, pubs_from_queue(Pubs),
   787                                                    [], Activity1)};
   788                                 false ->
   789                                     {Acks, _Common, Pubs} =
   790                                         find_prefix_common_suffix(PA, PALeft),
   791                                     {Member,
   792                                      activity_cons(Id, pubs_from_queue(Pubs),
   793                                                    acks_from_queue(Acks),
   794                                                    Activity1)}
   795                             end
   796                     end, Id, MembersStateActivity)
   797           end, {MembersState, activity_nil()}, AllMembers),
   798     handle_msg({activity, Left, activity_finalise(Activity)},
   799                State #state { members_state = MembersState1 });
   800 
   801 handle_msg({catchup, _NotLeft, _MembersState}, State) ->
   802     {ok, State};
   803 
   804 handle_msg({activity, Left, Activity},
   805            State = #state { self          = Self,
   806                             left          = {Left, _MRefL},
   807                             view          = View,
   808                             members_state = MembersState,
   809                             confirms      = Confirms })
   810   when MembersState =/= undefined ->
   811     {MembersState1, {Confirms1, Activity1}} =
   812         lists:foldl(
   813           fun ({Id, Pubs, Acks}, MembersStateConfirmsActivity) ->
   814                   with_member_acc(
   815                     fun (Member = #member { pending_ack = PA,
   816                                             last_pub    = LP,
   817                                             last_ack    = LA },
   818                          {Confirms2, Activity2}) ->
   819                             case is_member_alias(Id, Self, View) of
   820                                 true ->
   821                                     {ToAck, PA1} =
   822                                         find_common(queue_from_pubs(Pubs), PA,
   823                                                     queue:new()),
   824                                     LA1 = last_ack(Acks, LA),
   825                                     AckNums = acks_from_queue(ToAck),
   826                                     Confirms3 = maybe_confirm(
   827                                                   Self, Id, Confirms2, AckNums),
   828                                     {Member #member { pending_ack = PA1,
   829                                                       last_ack    = LA1 },
   830                                      {Confirms3,
   831                                       activity_cons(
   832                                         Id, [], AckNums, Activity2)}};
   833                                 false ->
   834                                     PA1 = apply_acks(Acks, join_pubs(PA, Pubs)),
   835                                     LA1 = last_ack(Acks, LA),
   836                                     LP1 = last_pub(Pubs, LP),
   837                                     {Member #member { pending_ack = PA1,
   838                                                       last_pub    = LP1,
   839                                                       last_ack    = LA1 },
   840                                      {Confirms2,
   841                                       activity_cons(Id, Pubs, Acks, Activity2)}}
   842                             end
   843                     end, Id, MembersStateConfirmsActivity)
   844           end, {MembersState, {Confirms, activity_nil()}}, Activity),
   845     State1 = State #state { members_state = MembersState1,
   846                             confirms      = Confirms1 },
   847     Activity3 = activity_finalise(Activity1),
   848     ok = maybe_send_activity(Activity3, State1),
   849     {Result, State2} = maybe_erase_aliases(State1, View),
   850     if_callback_success(
   851       Result, fun activity_true/3, fun activity_false/3, Activity3, State2);
   852 
   853 handle_msg({activity, _NotLeft, _Activity}, State) ->
   854     {ok, State}.
   855 
   856 
   857 noreply(State) ->
   858     {noreply, ensure_broadcast_timer(State), flush_timeout(State)}.
   859 
   860 reply(Reply, State) ->
   861     {reply, Reply, ensure_broadcast_timer(State), flush_timeout(State)}.
   862 
   863 flush_timeout(#state{broadcast_buffer = []}) -> hibernate;
   864 flush_timeout(_)                             -> 0.
   865 
   866 ensure_broadcast_timer(State = #state { broadcast_buffer = [],
   867                                         broadcast_timer  = undefined }) ->
   868     State;
   869 ensure_broadcast_timer(State = #state { broadcast_buffer = [],
   870                                         broadcast_timer  = TRef }) ->
   871     erlang:cancel_timer(TRef),
   872     State #state { broadcast_timer = undefined };
   873 ensure_broadcast_timer(State = #state { broadcast_timer = undefined }) ->
   874     TRef = erlang:send_after(?BROADCAST_TIMER, self(), flush),
   875     State #state { broadcast_timer = TRef };
   876 ensure_broadcast_timer(State) ->
   877     State.
   878 
   879 internal_broadcast(Msg, From, SizeHint,
   880                    State = #state { self                = Self,
   881                                     pub_count           = PubCount,
   882                                     module              = Module,
   883                                     confirms            = Confirms,
   884                                     callback_args       = Args,
   885                                     broadcast_buffer    = Buffer,
   886                                     broadcast_buffer_sz = BufferSize }) ->
   887     PubCount1 = PubCount + 1,
   888     Result = Module:handle_msg(Args, get_pid(Self), Msg),
   889     Buffer1 = [{PubCount1, Msg} | Buffer],
   890     Confirms1 = case From of
   891                     none -> Confirms;
   892                     _    -> queue:in({PubCount1, From}, Confirms)
   893                 end,
   894     State1 = State #state { pub_count           = PubCount1,
   895                             confirms            = Confirms1,
   896                             broadcast_buffer    = Buffer1,
   897                             broadcast_buffer_sz = BufferSize + SizeHint},
   898     handle_callback_result(
   899         {Result, case From of
   900                      none -> maybe_flush_broadcast_buffer(State1);
   901                      _    -> flush_broadcast_buffer(State1)
   902                  end}).
   903 
   904 %% The Erlang distribution mechanism has an interesting quirk - it
   905 %% will kill the VM cold with "Absurdly large distribution output data
   906 %% buffer" if you attempt to send a message which serialises out to
   907 %% more than 2^31 bytes in size. It's therefore a very good idea to
   908 %% make sure that we don't exceed that size!
   909 %%
   910 %% Now, we could figure out the size of messages as they come in using
   911 %% size(term_to_binary(Msg)) or similar. The trouble is, that requires
   912 %% us to serialise the message only to throw the serialised form
   913 %% away. Hard to believe that's a sensible thing to do. So instead we
   914 %% accept a size hint from the application, via broadcast/3. This size
   915 %% hint can be the size of anything in the message which we expect
   916 %% could be large, and we just ignore the size of any small bits of
   917 %% the message term. Therefore MAX_BUFFER_SIZE is set somewhat
   918 %% conservatively at 100MB - but the buffer is only to allow us to
   919 %% buffer tiny messages anyway, so 100MB is plenty.
   920 
   921 maybe_flush_broadcast_buffer(State = #state{broadcast_buffer_sz = Size}) ->
   922     case Size > ?MAX_BUFFER_SIZE of
   923         true  -> flush_broadcast_buffer(State);
   924         false -> State
   925     end.
   926 
   927 flush_broadcast_buffer(State = #state { broadcast_buffer = [] }) ->
   928     State;
   929 flush_broadcast_buffer(State = #state { self             = Self,
   930                                         members_state    = MembersState,
   931                                         broadcast_buffer = Buffer,
   932                                         pub_count        = PubCount }) ->
   933     [{PubCount, _Msg}|_] = Buffer, %% ASSERTION match on PubCount
   934     Pubs = lists:reverse(Buffer),
   935     Activity = activity_cons(Self, Pubs, [], activity_nil()),
   936     ok = maybe_send_activity(activity_finalise(Activity), State),
   937     MembersState1 = with_member(
   938                       fun (Member = #member { pending_ack = PA }) ->
   939                               PA1 = queue:join(PA, queue:from_list(Pubs)),
   940                               Member #member { pending_ack = PA1,
   941                                                last_pub = PubCount }
   942                       end, Self, MembersState),
   943     State #state { members_state       = MembersState1,
   944                    broadcast_buffer    = [],
   945                    broadcast_buffer_sz = 0}.
   946 
   947 
   948 %% ---------------------------------------------------------------------------
   949 %% View construction and inspection
   950 %% ---------------------------------------------------------------------------
   951 
   952 needs_view_update(ReqVer, {Ver, _View}) -> Ver < ReqVer.
   953 
   954 view_version({Ver, _View}) -> Ver.
   955 
   956 is_member_alive({dead, _Member}) -> false;
   957 is_member_alive(_)               -> true.
   958 
   959 is_member_alias(Self, Self, _View) ->
   960     true;
   961 is_member_alias(Member, Self, View) ->
   962     ?SETS:is_element(Member,
   963                      ((fetch_view_member(Self, View)) #view_member.aliases)).
   964 
   965 dead_member_id({dead, Member}) -> Member.
   966 
   967 store_view_member(VMember = #view_member { id = Id }, {Ver, View}) ->
   968     {Ver, ?DICT:store(Id, VMember, View)}.
   969 
   970 with_view_member(Fun, View, Id) ->
   971     store_view_member(Fun(fetch_view_member(Id, View)), View).
   972 
   973 fetch_view_member(Id, {_Ver, View}) -> ?DICT:fetch(Id, View).
   974 
   975 find_view_member(Id, {_Ver, View}) -> ?DICT:find(Id, View).
   976 
   977 blank_view(Ver) -> {Ver, ?DICT:new()}.
   978 
   979 alive_view_members({_Ver, View}) -> ?DICT:fetch_keys(View).
   980 
   981 all_known_members({_Ver, View}) ->
   982     ?DICT:fold(
   983        fun (Member, #view_member { aliases = Aliases }, Acc) ->
   984                ?SETS:to_list(Aliases) ++ [Member | Acc]
   985        end, [], View).
   986 
   987 group_to_view(#gm_group { members = Members, version = Ver }) ->
   988     Alive = lists:filter(fun is_member_alive/1, Members),
   989     [_|_] = Alive, %% ASSERTION - can't have all dead members
   990     add_aliases(link_view(Alive ++ Alive ++ Alive, blank_view(Ver)), Members).
   991 
   992 link_view([Left, Middle, Right | Rest], View) ->
   993     case find_view_member(Middle, View) of
   994         error ->
   995             link_view(
   996               [Middle, Right | Rest],
   997               store_view_member(#view_member { id      = Middle,
   998                                                aliases = ?SETS:new(),
   999                                                left    = Left,
  1000                                                right   = Right }, View));
  1001         {ok, _} ->
  1002             View
  1003     end;
  1004 link_view(_, View) ->
  1005     View.
  1006 
  1007 add_aliases(View, Members) ->
  1008     Members1 = ensure_alive_suffix(Members),
  1009     {EmptyDeadSet, View1} =
  1010         lists:foldl(
  1011           fun (Member, {DeadAcc, ViewAcc}) ->
  1012                   case is_member_alive(Member) of
  1013                       true ->
  1014                           {?SETS:new(),
  1015                            with_view_member(
  1016                              fun (VMember =
  1017                                       #view_member { aliases = Aliases }) ->
  1018                                      VMember #view_member {
  1019                                        aliases = ?SETS:union(Aliases, DeadAcc) }
  1020                              end, ViewAcc, Member)};
  1021                       false ->
  1022                           {?SETS:add_element(dead_member_id(Member), DeadAcc),
  1023                            ViewAcc}
  1024                   end
  1025           end, {?SETS:new(), View}, Members1),
  1026     0 = ?SETS:size(EmptyDeadSet), %% ASSERTION
  1027     View1.
  1028 
  1029 ensure_alive_suffix(Members) ->
  1030     queue:to_list(ensure_alive_suffix1(queue:from_list(Members))).
  1031 
  1032 ensure_alive_suffix1(MembersQ) ->
  1033     {{value, Member}, MembersQ1} = queue:out_r(MembersQ),
  1034     case is_member_alive(Member) of
  1035         true  -> MembersQ;
  1036         false -> ensure_alive_suffix1(queue:in_r(Member, MembersQ1))
  1037     end.
  1038 
  1039 
  1040 %% ---------------------------------------------------------------------------
  1041 %% View modification
  1042 %% ---------------------------------------------------------------------------
  1043 
  1044 join_group(Self, GroupName, TxnFun) ->
  1045     join_group(Self, GroupName, read_group(GroupName), TxnFun).
  1046 
  1047 join_group(Self, GroupName, {error, not_found}, TxnFun) ->
  1048     join_group(Self, GroupName,
  1049                prune_or_create_group(Self, GroupName, TxnFun), TxnFun);
  1050 join_group(Self, _GroupName, #gm_group { members = [Self] } = Group, _TxnFun) ->
  1051     group_to_view(Group);
  1052 join_group(Self, GroupName, #gm_group { members = Members } = Group, TxnFun) ->
  1053     case lists:member(Self, Members) of
  1054         true ->
  1055             group_to_view(Group);
  1056         false ->
  1057             case lists:filter(fun is_member_alive/1, Members) of
  1058                 [] ->
  1059                     join_group(Self, GroupName,
  1060                                prune_or_create_group(Self, GroupName, TxnFun));
  1061                 Alive ->
  1062                     Left = lists:nth(random:uniform(length(Alive)), Alive),
  1063                     Handler =
  1064                         fun () ->
  1065                                 join_group(
  1066                                   Self, GroupName,
  1067                                   record_dead_member_in_group(
  1068                                     Left, GroupName, TxnFun),
  1069                                   TxnFun)
  1070                         end,
  1071                     try
  1072                         case gen_server2:call(
  1073                                get_pid(Left), {add_on_right, Self}, infinity) of
  1074                             {ok, Group1} -> group_to_view(Group1);
  1075                             not_ready    -> join_group(Self, GroupName, TxnFun)
  1076                         end
  1077                     catch
  1078                         exit:{R, _}
  1079                           when R =:= noproc; R =:= normal; R =:= shutdown ->
  1080                             Handler();
  1081                         exit:{{R, _}, _}
  1082                           when R =:= nodedown; R =:= shutdown ->
  1083                             Handler()
  1084                     end
  1085             end
  1086     end.
  1087 
  1088 read_group(GroupName) ->
  1089     case mnesia:dirty_read(?GROUP_TABLE, GroupName) of
  1090         []      -> {error, not_found};
  1091         [Group] -> Group
  1092     end.
  1093 
  1094 prune_or_create_group(Self, GroupName, TxnFun) ->
  1095     Group = TxnFun(
  1096               fun () ->
  1097                       GroupNew = #gm_group { name    = GroupName,
  1098                                              members = [Self],
  1099                                              version = get_version(Self) },
  1100                       case mnesia:read({?GROUP_TABLE, GroupName}) of
  1101                           [] ->
  1102                               mnesia:write(GroupNew),
  1103                               GroupNew;
  1104                           [Group1 = #gm_group { members = Members }] ->
  1105                               case lists:any(fun is_member_alive/1, Members) of
  1106                                   true  -> Group1;
  1107                                   false -> mnesia:write(GroupNew),
  1108                                            GroupNew
  1109                               end
  1110                       end
  1111               end),
  1112     Group.
  1113 
  1114 record_dead_member_in_group(Member, GroupName, TxnFun) ->
  1115     Group =
  1116         TxnFun(
  1117           fun () -> [Group1 = #gm_group { members = Members, version = Ver }] =
  1118                         mnesia:read({?GROUP_TABLE, GroupName}),
  1119                     case lists:splitwith(
  1120                            fun (Member1) -> Member1 =/= Member end, Members) of
  1121                         {_Members1, []} -> %% not found - already recorded dead
  1122                             Group1;
  1123                         {Members1, [Member | Members2]} ->
  1124                             Members3 = Members1 ++ [{dead, Member} | Members2],
  1125                             Group2 = Group1 #gm_group { members = Members3,
  1126                                                         version = Ver + 1 },
  1127                             mnesia:write(Group2),
  1128                             Group2
  1129                     end
  1130           end),
  1131     Group.
  1132 
  1133 record_new_member_in_group(GroupName, Left, NewMember, Fun, TxnFun) ->
  1134     {Result, Group} =
  1135         TxnFun(
  1136           fun () ->
  1137                   [#gm_group { members = Members, version = Ver } = Group1] =
  1138                       mnesia:read({?GROUP_TABLE, GroupName}),
  1139                   {Prefix, [Left | Suffix]} =
  1140                       lists:splitwith(fun (M) -> M =/= Left end, Members),
  1141                   Members1 = Prefix ++ [Left, NewMember | Suffix],
  1142                   Group2 = Group1 #gm_group { members = Members1,
  1143                                               version = Ver + 1 },
  1144                   Result = Fun(Group2),
  1145                   mnesia:write(Group2),
  1146                   {Result, Group2}
  1147           end),
  1148     {Result, Group}.
  1149 
  1150 erase_members_in_group(Members, GroupName, TxnFun) ->
  1151     DeadMembers = [{dead, Id} || Id <- Members],
  1152     Group =
  1153         TxnFun(
  1154           fun () ->
  1155                   [Group1 = #gm_group { members = [_|_] = Members1,
  1156                                         version = Ver }] =
  1157                       mnesia:read({?GROUP_TABLE, GroupName}),
  1158                   case Members1 -- DeadMembers of
  1159                       Members1 -> Group1;
  1160                       Members2 -> Group2 =
  1161                                       Group1 #gm_group { members = Members2,
  1162                                                          version = Ver + 1 },
  1163                                   mnesia:write(Group2),
  1164                                   Group2
  1165                   end
  1166           end),
  1167     Group.
  1168 
  1169 maybe_erase_aliases(State = #state { self          = Self,
  1170                                      group_name    = GroupName,
  1171                                      view          = View0,
  1172                                      members_state = MembersState,
  1173                                      module        = Module,
  1174                                      callback_args = Args,
  1175                                      txn_executor  = TxnFun }, View) ->
  1176     #view_member { aliases = Aliases } = fetch_view_member(Self, View),
  1177     {Erasable, MembersState1}
  1178         = ?SETS:fold(
  1179              fun (Id, {ErasableAcc, MembersStateAcc} = Acc) ->
  1180                      #member { last_pub = LP, last_ack = LA } =
  1181                          find_member_or_blank(Id, MembersState),
  1182                      case can_erase_view_member(Self, Id, LA, LP) of
  1183                          true  -> {[Id | ErasableAcc],
  1184                                    erase_member(Id, MembersStateAcc)};
  1185                          false -> Acc
  1186                      end
  1187              end, {[], MembersState}, Aliases),
  1188     View1 = case Erasable of
  1189                 [] -> View;
  1190                 _  -> group_to_view(
  1191                         erase_members_in_group(Erasable, GroupName, TxnFun))
  1192             end,
  1193     State1 = State #state { members_state = MembersState1, view = View1 },
  1194     {callback_view_changed(Args, Module, View0, View1),
  1195      check_neighbours(State1)}.
  1196 
  1197 can_erase_view_member(Self, Self, _LA, _LP) -> false;
  1198 can_erase_view_member(_Self, _Id,   N,   N) -> true;
  1199 can_erase_view_member(_Self, _Id, _LA, _LP) -> false.
  1200 
  1201 
  1202 %% ---------------------------------------------------------------------------
  1203 %% View monitoring and maintanence
  1204 %% ---------------------------------------------------------------------------
  1205 
  1206 ensure_neighbour(_Ver, Self, {Self, undefined}, Self) ->
  1207     {Self, undefined};
  1208 ensure_neighbour(Ver, Self, {Self, undefined}, RealNeighbour) ->
  1209     ok = gen_server2:cast(get_pid(RealNeighbour),
  1210                           {?TAG, Ver, check_neighbours}),
  1211     {RealNeighbour, maybe_monitor(RealNeighbour, Self)};
  1212 ensure_neighbour(_Ver, _Self, {RealNeighbour, MRef}, RealNeighbour) ->
  1213     {RealNeighbour, MRef};
  1214 ensure_neighbour(Ver, Self, {RealNeighbour, MRef}, Neighbour) ->
  1215     true = erlang:demonitor(MRef),
  1216     Msg = {?TAG, Ver, check_neighbours},
  1217     ok = gen_server2:cast(get_pid(RealNeighbour), Msg),
  1218     ok = case Neighbour of
  1219              Self -> ok;
  1220              _    -> gen_server2:cast(get_pid(Neighbour), Msg)
  1221          end,
  1222     {Neighbour, maybe_monitor(Neighbour, Self)}.
  1223 
  1224 maybe_monitor( Self,  Self) -> undefined;
  1225 maybe_monitor(Other, _Self) -> erlang:monitor(process, get_pid(Other)).
  1226 
  1227 check_neighbours(State = #state { self             = Self,
  1228                                   left             = Left,
  1229                                   right            = Right,
  1230                                   view             = View,
  1231                                   broadcast_buffer = Buffer }) ->
  1232     #view_member { left = VLeft, right = VRight }
  1233         = fetch_view_member(Self, View),
  1234     Ver = view_version(View),
  1235     Left1 = ensure_neighbour(Ver, Self, Left, VLeft),
  1236     Right1 = ensure_neighbour(Ver, Self, Right, VRight),
  1237     Buffer1 = case Right1 of
  1238                   {Self, undefined} -> [];
  1239                   _                 -> Buffer
  1240               end,
  1241     State1 = State #state { left = Left1, right = Right1,
  1242                             broadcast_buffer = Buffer1 },
  1243     ok = maybe_send_catchup(Right, State1),
  1244     State1.
  1245 
  1246 maybe_send_catchup(Right, #state { right = Right }) ->
  1247     ok;
  1248 maybe_send_catchup(_Right, #state { self  = Self,
  1249                                     right = {Self, undefined} }) ->
  1250     ok;
  1251 maybe_send_catchup(_Right, #state { members_state = undefined }) ->
  1252     ok;
  1253 maybe_send_catchup(_Right, #state { self          = Self,
  1254                                     right         = {Right, _MRef},
  1255                                     view          = View,
  1256                                     members_state = MembersState }) ->
  1257     send_right(Right, View,
  1258                {catchup, Self, prepare_members_state(MembersState)}).
  1259 
  1260 
  1261 %% ---------------------------------------------------------------------------
  1262 %% Catch_up delta detection
  1263 %% ---------------------------------------------------------------------------
  1264 
  1265 find_prefix_common_suffix(A, B) ->
  1266     {Prefix, A1} = find_prefix(A, B, queue:new()),
  1267     {Common, Suffix} = find_common(A1, B, queue:new()),
  1268     {Prefix, Common, Suffix}.
  1269 
  1270 %% Returns the elements of A that occur before the first element of B,
  1271 %% plus the remainder of A.
  1272 find_prefix(A, B, Prefix) ->
  1273     case {queue:out(A), queue:out(B)} of
  1274         {{{value, Val}, _A1}, {{value, Val}, _B1}} ->
  1275             {Prefix, A};
  1276         {{empty, A1}, {{value, _A}, _B1}} ->
  1277             {Prefix, A1};
  1278         {{{value, {NumA, _MsgA} = Val}, A1},
  1279          {{value, {NumB, _MsgB}}, _B1}} when NumA < NumB ->
  1280             find_prefix(A1, B, queue:in(Val, Prefix));
  1281         {_, {empty, _B1}} ->
  1282             {A, Prefix} %% Prefix well be empty here
  1283     end.
  1284 
  1285 %% A should be a prefix of B. Returns the commonality plus the
  1286 %% remainder of B.
  1287 find_common(A, B, Common) ->
  1288     case {queue:out(A), queue:out(B)} of
  1289         {{{value, Val}, A1}, {{value, Val}, B1}} ->
  1290             find_common(A1, B1, queue:in(Val, Common));
  1291         {{empty, _A}, _} ->
  1292             {Common, B}
  1293     end.
  1294 
  1295 
  1296 %% ---------------------------------------------------------------------------
  1297 %% Members helpers
  1298 %% ---------------------------------------------------------------------------
  1299 
  1300 with_member(Fun, Id, MembersState) ->
  1301     store_member(
  1302       Id, Fun(find_member_or_blank(Id, MembersState)), MembersState).
  1303 
  1304 with_member_acc(Fun, Id, {MembersState, Acc}) ->
  1305     {MemberState, Acc1} = Fun(find_member_or_blank(Id, MembersState), Acc),
  1306     {store_member(Id, MemberState, MembersState), Acc1}.
  1307 
  1308 find_member_or_blank(Id, MembersState) ->
  1309     case ?DICT:find(Id, MembersState) of
  1310         {ok, Result} -> Result;
  1311         error        -> blank_member()
  1312     end.
  1313 
  1314 erase_member(Id, MembersState) -> ?DICT:erase(Id, MembersState).
  1315 
  1316 blank_member() ->
  1317     #member { pending_ack = queue:new(), last_pub = -1, last_ack = -1 }.
  1318 
  1319 blank_member_state() -> ?DICT:new().
  1320 
  1321 store_member(Id, MemberState, MembersState) ->
  1322     ?DICT:store(Id, MemberState, MembersState).
  1323 
  1324 prepare_members_state(MembersState) -> ?DICT:to_list(MembersState).
  1325 
  1326 build_members_state(MembersStateList) -> ?DICT:from_list(MembersStateList).
  1327 
  1328 make_member(GroupName) ->
  1329    {case read_group(GroupName) of
  1330         #gm_group { version = Version } -> Version;
  1331         {error, not_found}              -> ?VERSION_START
  1332     end, self()}.
  1333 
  1334 remove_erased_members(MembersState, View) ->
  1335     lists:foldl(fun (Id, MembersState1) ->
  1336                     store_member(Id, find_member_or_blank(Id, MembersState),
  1337                                  MembersState1)
  1338                 end, blank_member_state(), all_known_members(View)).
  1339 
  1340 get_version({Version, _Pid}) -> Version.
  1341 
  1342 get_pid({_Version, Pid}) -> Pid.
  1343 
  1344 get_pids(Ids) -> [Pid || {_Version, Pid} <- Ids].
  1345 
  1346 %% ---------------------------------------------------------------------------
  1347 %% Activity assembly
  1348 %% ---------------------------------------------------------------------------
  1349 
  1350 activity_nil() -> queue:new().
  1351 
  1352 activity_cons(   _Id,   [],   [], Tail) -> Tail;
  1353 activity_cons(Sender, Pubs, Acks, Tail) -> queue:in({Sender, Pubs, Acks}, Tail).
  1354 
  1355 activity_finalise(Activity) -> queue:to_list(Activity).
  1356 
  1357 maybe_send_activity([], _State) ->
  1358     ok;
  1359 maybe_send_activity(Activity, #state { self  = Self,
  1360                                        right = {Right, _MRefR},
  1361                                        view  = View }) ->
  1362     send_right(Right, View, {activity, Self, Activity}).
  1363 
  1364 send_right(Right, View, Msg) ->
  1365     ok = gen_server2:cast(get_pid(Right), {?TAG, view_version(View), Msg}).
  1366 
  1367 callback(Args, Module, Activity) ->
  1368     Result =
  1369       lists:foldl(
  1370         fun ({Id, Pubs, _Acks}, {Args1, Module1, ok}) ->
  1371                 lists:foldl(fun ({_PubNum, Pub}, Acc = {Args2, Module2, ok}) ->
  1372                                     case Module2:handle_msg(
  1373                                            Args2, get_pid(Id), Pub) of
  1374                                         ok ->
  1375                                             Acc;
  1376                                         {become, Module3, Args3} ->
  1377                                             {Args3, Module3, ok};
  1378                                         {stop, _Reason} = Error ->
  1379                                             Error
  1380                                     end;
  1381                                 (_, Error = {stop, _Reason}) ->
  1382                                     Error
  1383                             end, {Args1, Module1, ok}, Pubs);
  1384             (_, Error = {stop, _Reason}) ->
  1385                 Error
  1386         end, {Args, Module, ok}, Activity),
  1387     case Result of
  1388         {Args, Module, ok}      -> ok;
  1389         {Args1, Module1, ok}    -> {become, Module1, Args1};
  1390         {stop, _Reason} = Error -> Error
  1391     end.
  1392 
  1393 callback_view_changed(Args, Module, OldView, NewView) ->
  1394     OldMembers = all_known_members(OldView),
  1395     NewMembers = all_known_members(NewView),
  1396     Births = NewMembers -- OldMembers,
  1397     Deaths = OldMembers -- NewMembers,
  1398     case {Births, Deaths} of
  1399         {[], []} -> ok;
  1400         _        -> Module:members_changed(
  1401                       Args, get_pids(Births), get_pids(Deaths))
  1402     end.
  1403 
  1404 handle_callback_result({Result, State}) ->
  1405     if_callback_success(
  1406       Result, fun no_reply_true/3, fun no_reply_false/3, undefined, State);
  1407 handle_callback_result({Result, Reply, State}) ->
  1408     if_callback_success(
  1409       Result, fun reply_true/3, fun reply_false/3, Reply, State).
  1410 
  1411 no_reply_true (_Result,        _Undefined, State) -> noreply(State).
  1412 no_reply_false({stop, Reason}, _Undefined, State) -> {stop, Reason, State}.
  1413 
  1414 reply_true (_Result,        Reply, State) -> reply(Reply, State).
  1415 reply_false({stop, Reason}, Reply, State) -> {stop, Reason, Reply, State}.
  1416 
  1417 handle_msg_true (_Result, Msg, State) -> handle_msg(Msg, State).
  1418 handle_msg_false(Result, _Msg, State) -> {Result, State}.
  1419 
  1420 activity_true(_Result, Activity, State = #state { module        = Module,
  1421                                                   callback_args = Args }) ->
  1422     {callback(Args, Module, Activity), State}.
  1423 activity_false(Result, _Activity, State) ->
  1424     {Result, State}.
  1425 
  1426 if_callback_success(ok, True, _False, Arg, State) ->
  1427     True(ok, Arg, State);
  1428 if_callback_success(
  1429   {become, Module, Args} = Result, True, _False, Arg, State) ->
  1430     True(Result, Arg, State #state { module        = Module,
  1431                                      callback_args = Args });
  1432 if_callback_success({stop, _Reason} = Result, _True, False, Arg, State) ->
  1433     False(Result, Arg, State).
  1434 
  1435 maybe_confirm(_Self, _Id, Confirms, []) ->
  1436     Confirms;
  1437 maybe_confirm(Self, Self, Confirms, [PubNum | PubNums]) ->
  1438     case queue:out(Confirms) of
  1439         {empty, _Confirms} ->
  1440             Confirms;
  1441         {{value, {PubNum, From}}, Confirms1} ->
  1442             gen_server2:reply(From, ok),
  1443             maybe_confirm(Self, Self, Confirms1, PubNums);
  1444         {{value, {PubNum1, _From}}, _Confirms} when PubNum1 > PubNum ->
  1445             maybe_confirm(Self, Self, Confirms, PubNums)
  1446     end;
  1447 maybe_confirm(_Self, _Id, Confirms, _PubNums) ->
  1448     Confirms.
  1449 
  1450 purge_confirms(Confirms) ->
  1451     [gen_server2:reply(From, ok) || {_PubNum, From} <- queue:to_list(Confirms)],
  1452     queue:new().
  1453 
  1454 
  1455 %% ---------------------------------------------------------------------------
  1456 %% Msg transformation
  1457 %% ---------------------------------------------------------------------------
  1458 
  1459 acks_from_queue(Q) -> [PubNum || {PubNum, _Msg} <- queue:to_list(Q)].
  1460 
  1461 pubs_from_queue(Q) -> queue:to_list(Q).
  1462 
  1463 queue_from_pubs(Pubs) -> queue:from_list(Pubs).
  1464 
  1465 apply_acks(  [], Pubs) -> Pubs;
  1466 apply_acks(List, Pubs) -> {_, Pubs1} = queue:split(length(List), Pubs),
  1467                           Pubs1.
  1468 
  1469 join_pubs(Q, [])   -> Q;
  1470 join_pubs(Q, Pubs) -> queue:join(Q, queue_from_pubs(Pubs)).
  1471 
  1472 last_ack(  [], LA) -> LA;
  1473 last_ack(List, LA) -> LA1 = lists:last(List),
  1474                       true = LA1 > LA, %% ASSERTION
  1475                       LA1.
  1476 
  1477 last_pub(  [], LP) -> LP;
  1478 last_pub(List, LP) -> {PubNum, _Msg} = lists:last(List),
  1479                       true = PubNum > LP, %% ASSERTION
  1480                       PubNum.