精华内容
下载资源
问答
  • was集群(笔记)

    千次阅读 2018-03-28 15:28:32
    1.什么是was WAS是webshpere application server的缩写,基于Java的web应用服务器,类IIS webshpere:IBM的软件平台 was:webshpere中的程序集成产品 webshpere>was 单元节点概念 单元:逻辑概念...

    1.什么是was

    WAS是webshpere application server的缩写,基于Java的web应用服务器,类IIS

    • webshpere:IBM的软件平台
    • was:webshpere中的程序集成产品

    webshpere>was


    1. 单元节点概念
      单元:逻辑概念(域)
      节点:对应唯一IP主机
      一个单元里有多个节点,一个节点里有多台服务器
    2. 概要文件(profile)
      二进制文件(安装文件)+用户数据文件(概要文件)
      默认目录:was安装目录/profiles/
    展开全文
  • RabbitMQ集群原理

    千次阅读 2020-06-23 11:55:15
    RabbitMQ是Erlang语言和平台实现的,其充分利用Erlang分布特性,实现集群功能非常容易。RabbitMQ集群分为普通模式和镜像模式,普通模式下存在单点故障,当队列创建时绑定的节点故障时,服务整体不可用。镜像队列...

    RabbitMQ是Erlang语言和平台实现的,其充分利用Erlang分布特性,实现集群功能非常容易。RabbitMQ集群分为普通模式和镜像模式,普通模式下存在单点故障,当队列创建时绑定的节点故障时,服务整体不可用。镜像队列(Mirrored queue)机制解决了RabbitMQ单点问题,保证了高可用(Highly Available)。

    重点讨论镜像模式RabbitMQ集群。

    通过镜像机制,RabbitMQ将队列放置于集群中的多个节点上,消息的生产和消费都会在节点间同步。镜像队列包含一个master和多个slave,当master退出时,最老的slave被提升为新的master。
    镜像队列中各节点的进程是独立的,进程间通过消息传递来通信。各节点之间通过GM协议保证消息原子性传递。

    在这里插入图片描述

    可靠多播 (Guaranteed Multicast)

    广播通常的实现方法是发送者将消息发给集群中的每个节点,这要求集群节点是全联通的(fully connected)。当发送节点挂掉时,消息可能没有发到集群中的每个节点,这就引入了集群中哪些节点要为已挂掉节点负责、继续发送消息的问题。

    为简化网络拓扑和实现复杂度,GM组将集群中的节点组成一个环。环中节点挂掉时,很容易知道哪些节点已收到消息、哪些节点没有收到:如果一个节点挂掉,其左右邻居节点将获悉其退出信息,然后最近的上游节点(upstream)负责将挂掉节点未转发的消息(in-flight messages)继续发给最近的下游节点(downstream)。
      
    在这里插入图片描述

    参考RabbitMQ源文件gm.erl

    %% 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
    %% https://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 Developer of the Original Code is GoPivotal, Inc.
    %% Copyright (c) 2007-2020 VMware, Inc. or its affiliates.  All rights reserved.
    %%
    
    -module(gm).
    
    %% Guaranteed Multicast
    %% ====================
    %%
    %% This module provides the ability to create named groups of
    %% processes to which members can be dynamically added and removed,
    %% and for messages to be broadcast within the group that are
    %% guaranteed to reach all members of the group during the lifetime of
    %% the message. The lifetime of a message is defined as being, at a
    %% minimum, the time from which the message is first sent to any
    %% member of the group, up until the time at which it is known by the
    %% member who published the message that the message has reached all
    %% group members.
    %%
    %% The guarantee given is that provided a message, once sent, makes it
    %% to members who do not all leave the group, the message will
    %% continue to propagate to all group members.
    %%
    %% Another way of stating the guarantee is that if member P publishes
    %% messages m and m', then for all members P', if P' is a member of
    %% the group prior to the publication of m, and P' receives m', then
    %% P' will receive m.
    %%
    %% Note that only local-ordering is enforced: i.e. if member P sends
    %% message m and then message m', then for-all members P', if P'
    %% receives m and m', then they will receive m' after m. Causality
    %% ordering is _not_ enforced. I.e. if member P receives message m
    %% and as a result publishes message m', there is no guarantee that
    %% other members P' will receive m before m'.
    %%
    %%
    %% API Use
    %% -------
    %%
    %% Mnesia must be started. Use the idempotent create_tables/0 function
    %% to create the tables required.
    %%
    %% start_link/3
    %% Provide the group name, the callback module name, and any arguments
    %% you wish to be passed into the callback module's functions. The
    %% joined/2 function will be called when we have joined the group,
    %% with the arguments passed to start_link and a list of the current
    %% members of the group. See the callbacks specs and the comments
    %% below for further details of the callback functions.
    %%
    %% leave/1
    %% Provide the Pid. Removes the Pid from the group. The callback
    %% handle_terminate/2 function will be called.
    %%
    %% broadcast/2
    %% Provide the Pid and a Message. The message will be sent to all
    %% members of the group as per the guarantees given above. This is a
    %% cast and the function call will return immediately. There is no
    %% guarantee that the message will reach any member of the group.
    %%
    %% confirmed_broadcast/2
    %% Provide the Pid and a Message. As per broadcast/2 except that this
    %% is a call, not a cast, and only returns 'ok' once the Message has
    %% reached every member of the group. Do not call
    %% confirmed_broadcast/2 directly from the callback module otherwise
    %% you will deadlock the entire group.
    %%
    %% info/1
    %% Provide the Pid. Returns a proplist with various facts, including
    %% the group name and the current group members.
    %%
    %% validate_members/2
    %% Check whether a given member list agrees with the chosen member's
    %% view. Any differences will be communicated via the members_changed
    %% callback. If there are no differences then there will be no reply.
    %% Note that members will not necessarily share the same view.
    %%
    %% forget_group/1
    %% Provide the group name. Removes its mnesia record. Makes no attempt
    %% to ensure the group is empty.
    %%
    %% Implementation Overview
    %% -----------------------
    %%
    %% One possible means of implementation would be a fan-out from the
    %% sender to every member of the group. This would require that the
    %% group is fully connected, and, in the event that the original
    %% sender of the message disappears from the group before the message
    %% has made it to every member of the group, raises questions as to
    %% who is responsible for sending on the message to new group members.
    %% In particular, the issue is with [ Pid ! Msg || Pid <- Members ] -
    %% if the sender dies part way through, who is responsible for
    %% ensuring that the remaining Members receive the Msg? In the event
    %% that within the group, messages sent are broadcast from a subset of
    %% the members, the fan-out arrangement has the potential to
    %% substantially impact the CPU and network workload of such members,
    %% as such members would have to accommodate the cost of sending each
    %% message to every group member.
    %%
    %% Instead, if the members of the group are arranged in a chain, then
    %% it becomes easier to reason about who within the group has received
    %% each message and who has not. It eases issues of responsibility: in
    %% the event of a group member disappearing, the nearest upstream
    %% member of the chain is responsible for ensuring that messages
    %% continue to propagate down the chain. It also results in equal
    %% distribution of sending and receiving workload, even if all
    %% messages are being sent from just a single group member. This
    %% configuration has the further advantage that it is not necessary
    %% for every group member to know of every other group member, and
    %% even that a group member does not have to be accessible from all
    %% other group members.
    %%
    %% Performance is kept high by permitting pipelining and all
    %% communication between joined group members is asynchronous. In the
    %% chain A -> B -> C -> D, if A sends a message to the group, it will
    %% not directly contact C or D. However, it must know that D receives
    %% the message (in addition to B and C) before it can consider the
    %% message fully sent. A simplistic implementation would require that
    %% D replies to C, C replies to B and B then replies to A. This would
    %% result in a propagation delay of twice the length of the chain. It
    %% would also require, in the event of the failure of C, that D knows
    %% to directly contact B and issue the necessary replies. Instead, the
    %% chain forms a ring: D sends the message on to A: D does not
    %% distinguish A as the sender, merely as the next member (downstream)
    %% within the chain (which has now become a ring). When A receives
    %% from D messages that A sent, it knows that all members have
    %% received the message. However, the message is not dead yet: if C
    %% died as B was sending to C, then B would need to detect the death
    %% of C and forward the message on to D instead: thus every node has
    %% to remember every message published until it is told that it can
    %% forget about the message. This is essential not just for dealing
    %% with failure of members, but also for the addition of new members.
    %%
    %% Thus once A receives the message back again, it then sends to B an
    %% acknowledgement for the message, indicating that B can now forget
    %% about the message. B does so, and forwards the ack to C. C forgets
    %% the message, and forwards the ack to D, which forgets the message
    %% and finally forwards the ack back to A. At this point, A takes no
    %% further action: the message and its acknowledgement have made it to
    %% every member of the group. The message is now dead, and any new
    %% member joining the group at this point will not receive the
    %% message.
    %%
    %% We therefore have two roles:
    %%
    %% 1. The sender, who upon receiving their own messages back, must
    %% then send out acknowledgements, and upon receiving their own
    %% acknowledgements back perform no further action.
    %%
    %% 2. The other group members who upon receiving messages and
    %% acknowledgements must update their own internal state accordingly
    %% (the sending member must also do this in order to be able to
    %% accommodate failures), and forwards messages on to their downstream
    %% neighbours.
    %%
    %%
    %% Implementation: It gets trickier
    %% --------------------------------
    %%
    %% Chain A -> B -> C -> D
    %%
    %% A publishes a message which B receives. A now dies. B and D will
    %% detect the death of A, and will link up, thus the chain is now B ->
    %% C -> D. B forwards A's message on to C, who forwards it to D, who
    %% forwards it to B. Thus B is now responsible for A's messages - both
    %% publications and acknowledgements that were in flight at the point
    %% at which A died. Even worse is that this is transitive: after B
    %% forwards A's message to C, B dies as well. Now C is not only
    %% responsible for B's in-flight messages, but is also responsible for
    %% A's in-flight messages.
    %%
    %% Lemma 1: A member can only determine which dead members they have
    %% inherited responsibility for if there is a total ordering on the
    %% conflicting additions and subtractions of members from the group.
    %%
    %% Consider the simultaneous death of B and addition of B' that
    %% transitions a chain from A -> B -> C to A -> B' -> C. Either B' or
    %% C is responsible for in-flight messages from B. It is easy to
    %% ensure that at least one of them thinks they have inherited B, but
    %% if we do not ensure that exactly one of them inherits B, then we
    %% could have B' converting publishes to acks, which then will crash C
    %% as C does not believe it has issued acks for those messages.
    %%
    %% More complex scenarios are easy to concoct: A -> B -> C -> D -> E
    %% becoming A -> C' -> E. Who has inherited which of B, C and D?
    %%
    %% However, for non-conflicting membership changes, only a partial
    %% ordering is required. For example, A -> B -> C becoming A -> A' ->
    %% B. The addition of A', between A and B can have no conflicts with
    %% the death of C: it is clear that A has inherited C's messages.
    %%
    %% For ease of implementation, we adopt the simple solution, of
    %% imposing a total order on all membership changes.
    %%
    %% On the death of a member, it is ensured the dead member's
    %% neighbours become aware of the death, and the upstream neighbour
    %% now sends to its new downstream neighbour its state, including the
    %% messages pending acknowledgement. The downstream neighbour can then
    %% use this to calculate which publishes and acknowledgements it has
    %% missed out on, due to the death of its old upstream. Thus the
    %% downstream can catch up, and continues the propagation of messages
    %% through the group.
    %%
    %% Lemma 2: When a member is joining, it must synchronously
    %% communicate with its upstream member in order to receive its
    %% starting state atomically with its addition to the group.
    %%
    %% New members must start with the same state as their nearest
    %% upstream neighbour. This ensures that it is not surprised by
    %% acknowledgements they are sent, and that should their downstream
    %% neighbour die, they are able to send the correct state to their new
    %% downstream neighbour to ensure it can catch up. Thus in the
    %% transition A -> B -> C becomes A -> A' -> B -> C becomes A -> A' ->
    %% C, A' must start with the state of A, so that it can send C the
    %% correct state when B dies, allowing C to detect any missed
    %% messages.
    %%
    %% If A' starts by adding itself to the group membership, A could then
    %% die, without A' having received the necessary state from A. This
    %% would leave A' responsible for in-flight messages from A, but
    %% having the least knowledge of all, of those messages. Thus A' must
    %% start by synchronously calling A, which then immediately sends A'
    %% back its state. A then adds A' to the group. If A dies at this
    %% point then A' will be able to see this (as A' will fail to appear
    %% in the group membership), and thus A' will ignore the state it
    %% receives from A, and will simply repeat the process, trying to now
    %% join downstream from some other member. This ensures that should
    %% the upstream die as soon as the new member has been joined, the new
    %% member is guaranteed to receive the correct state, allowing it to
    %% correctly process messages inherited due to the death of its
    %% upstream neighbour.
    %%
    %% The canonical definition of the group membership is held by a
    %% distributed database. Whilst this allows the total ordering of
    %% changes to be achieved, it is nevertheless undesirable to have to
    %% query this database for the current view, upon receiving each
    %% message. Instead, we wish for members to be able to cache a view of
    %% the group membership, which then requires a cache invalidation
    %% mechanism. Each member maintains its own view of the group
    %% membership. Thus when the group's membership changes, members may
    %% need to become aware of such changes in order to be able to
    %% accurately process messages they receive. Because of the
    %% requirement of a total ordering of conflicting membership changes,
    %% it is not possible to use the guaranteed broadcast mechanism to
    %% communicate these changes: to achieve the necessary ordering, it
    %% would be necessary for such messages to be published by exactly one
    %% member, which can not be guaranteed given that such a member could
    %% die.
    %%
    %% The total ordering we enforce on membership changes gives rise to a
    %% view version number: every change to the membership creates a
    %% different view, and the total ordering permits a simple
    %% monotonically increasing view version number.
    %%
    %% Lemma 3: If a message is sent from a member that holds view version
    %% N, it can be correctly processed by any member receiving the
    %% message with a view version >= N.
    %%
    %% Initially, let us suppose that each view contains the ordering of
    %% every member that was ever part of the group. Dead members are
    %% marked as such. Thus we have a ring of members, some of which are
    %% dead, and are thus inherited by the nearest alive downstream
    %% member.
    %%
    %% In the chain A -> B -> C, all three members initially have view
    %% version 1, which reflects reality. B publishes a message, which is
    %% forward by C to A. B now dies, which A notices very quickly. Thus A
    %% updates the view, creating version 2. It now forwards B's
    %% publication, sending that message to its new downstream neighbour,
    %% C. This happens before C is aware of the death of B. C must become
    %% aware of the view change before it interprets the message its
    %% received, otherwise it will fail to learn of the death of B, and
    %% thus will not realise it has inherited B's messages (and will
    %% likely crash).
    %%
    %% Thus very simply, we have that each subsequent view contains more
    %% information than the preceding view.
    %%
    %% However, to avoid the views growing indefinitely, we need to be
    %% able to delete members which have died _and_ for which no messages
    %% are in-flight. This requires that upon inheriting a dead member, we
    %% know the last publication sent by the dead member (this is easy: we
    %% inherit a member because we are the nearest downstream member which
    %% implies that we know at least as much than everyone else about the
    %% publications of the dead member), and we know the earliest message
    %% for which the acknowledgement is still in flight.
    %%
    %% In the chain A -> B -> C, when B dies, A will send to C its state
    %% (as C is the new downstream from A), allowing C to calculate which
    %% messages it has missed out on (described above). At this point, C
    %% also inherits B's messages. If that state from A also includes the
    %% last message published by B for which an acknowledgement has been
    %% seen, then C knows exactly which further acknowledgements it must
    %% receive (also including issuing acknowledgements for publications
    %% still in-flight that it receives), after which it is known there
    %% are no more messages in flight for B, thus all evidence that B was
    %% ever part of the group can be safely removed from the canonical
    %% group membership.
    %%
    %% Thus, for every message that a member sends, it includes with that
    %% message its view version. When a member receives a message it will
    %% update its view from the canonical copy, should its view be older
    %% than the view version included in the message it has received.
    %%
    %% The state held by each member therefore includes the messages from
    %% each publisher pending acknowledgement, the last publication seen
    %% from that publisher, and the last acknowledgement from that
    %% publisher. In the case of the member's own publications or
    %% inherited members, this last acknowledgement seen state indicates
    %% the last acknowledgement retired, rather than sent.
    %%
    %%
    %% Proof sketch
    %% ------------
    %%
    %% We need to prove that with the provided operational semantics, we
    %% can never reach a state that is not well formed from a well-formed
    %% starting state.
    %%
    %% Operational semantics (small step): straight-forward message
    %% sending, process monitoring, state updates.
    %%
    %% Well formed state: dead members inherited by exactly one non-dead
    %% member; for every entry in anyone's pending-acks, either (the
    %% publication of the message is in-flight downstream from the member
    %% and upstream from the publisher) or (the acknowledgement of the
    %% message is in-flight downstream from the publisher and upstream
    %% from the member).
    %%
    %% Proof by induction on the applicable operational semantics.
    %%
    %%
    %% Related work
    %% ------------
    %%
    %% The ring configuration and double traversal of messages around the
    %% ring is similar (though developed independently) to the LCR
    %% protocol by [Levy 2008]. However, LCR differs in several
    %% ways. Firstly, by using vector clocks, it enforces a total order of
    %% message delivery, which is unnecessary for our purposes. More
    %% significantly, it is built on top of a "group communication system"
    %% which performs the group management functions, taking
    %% responsibility away from the protocol as to how to cope with safely
    %% adding and removing members. When membership changes do occur, the
    %% protocol stipulates that every member must perform communication
    %% with every other member of the group, to ensure all outstanding
    %% deliveries complete, before the entire group transitions to the new
    %% view. This, in total, requires two sets of all-to-all synchronous
    %% communications.
    %%
    %% This is not only rather inefficient, but also does not explain what
    %% happens upon the failure of a member during this process. It does
    %% though entirely avoid the need for inheritance of responsibility of
    %% dead members that our protocol incorporates.
    %%
    %% In [Marandi et al 2010], a Paxos-based protocol is described. This
    %% work explicitly focuses on the efficiency of communication. LCR
    %% (and our protocol too) are more efficient, but at the cost of
    %% higher latency. The Ring-Paxos protocol is itself built on top of
    %% IP-multicast, which rules it out for many applications where
    %% point-to-point communication is all that can be required. They also
    %% have an excellent related work section which I really ought to
    %% read...
    %%
    %%
    %% [Levy 2008] The Complexity of Reliable Distributed Storage, 2008.
    %% [Marandi et al 2010] Ring Paxos: A High-Throughput Atomic Broadcast
    %% Protocol
    
    
    -behaviour(gen_server2).
    
    -export([create_tables/0, start_link/4, leave/1, broadcast/2, broadcast/3,
             confirmed_broadcast/2, info/1, validate_members/2, forget_group/1]).
    
    -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
             code_change/3, prioritise_info/3]).
    
    %% For INSTR_MOD callbacks
    -export([call/3, cast/2, monitor/1, demonitor/1]).
    
    -export([table_definitions/0]).
    
    -define(GROUP_TABLE, gm_group).
    -define(MAX_BUFFER_SIZE, 100000000). %% 100MB
    -define(BROADCAST_TIMER, 25).
    -define(FORCE_GC_TIMER, 250).
    -define(VERSION_START, 0).
    -define(SETS, ordsets).
    
    -record(state,
            { self,
              left,
              right,
              group_name,
              module,
              view,
              pub_count,
              members_state,
              callback_args,
              confirms,
              broadcast_buffer,
              broadcast_buffer_sz,
              broadcast_timer,
              force_gc_timer,
              txn_executor,
              shutting_down
            }).
    
    -record(gm_group, { name, version, members }).
    
    -record(view_member, { id, aliases, left, right }).
    
    -record(member, { pending_ack, last_pub, last_ack }).
    
    -define(TABLE, {?GROUP_TABLE, [{record_name, gm_group},
                                   {attributes, record_info(fields, gm_group)}]}).
    -define(TABLE_MATCH, {match, #gm_group { _ = '_' }}).
    
    -define(TAG, '$gm').
    
    -export_type([group_name/0]).
    
    -type group_name() :: any().
    -type txn_fun() :: fun((fun(() -> any())) -> any()).
    
    %% The joined, members_changed and handle_msg callbacks can all return
    %% any of the following terms:
    %%
    %% 'ok' - the callback function returns normally
    %%
    %% {'stop', Reason} - the callback indicates the member should stop
    %% with reason Reason and should leave the group.
    %%
    %% {'become', Module, Args} - the callback indicates that the callback
    %% module should be changed to Module and that the callback functions
    %% should now be passed the arguments Args. This allows the callback
    %% module to be dynamically changed.
    
    %% Called when we've successfully joined the group. Supplied with Args
    %% provided in start_link, plus current group members.
    -callback joined(Args :: term(), Members :: [pid()]) ->
        ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
    
    %% Supplied with Args provided in start_link, the list of new members
    %% and the list of members previously known to us that have since
    %% died. Note that if a member joins and dies very quickly, it's
    %% possible that we will never see that member appear in either births
    %% or deaths. However we are guaranteed that (1) we will see a member
    %% joining either in the births here, or in the members passed to
    %% joined/2 before receiving any messages from it; and (2) we will not
    %% see members die that we have not seen born (or supplied in the
    %% members to joined/2).
    -callback members_changed(Args :: term(),
                              Births :: [pid()], Deaths :: [pid()]) ->
        ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
    
    %% Supplied with Args provided in start_link, the sender, and the
    %% message. This does get called for messages injected by this member,
    %% however, in such cases, there is no special significance of this
    %% invocation: it does not indicate that the message has made it to
    %% any other members, let alone all other members.
    -callback handle_msg(Args :: term(), From :: pid(), Message :: term()) ->
        ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
    
    %% Called on gm member termination as per rules in gen_server, with
    %% the Args provided in start_link plus the termination Reason.
    -callback handle_terminate(Args :: term(), Reason :: term()) ->
        ok | term().
    
    -spec create_tables() -> 'ok' | {'aborted', any()}.
    
    create_tables() ->
        create_tables([?TABLE]).
    
    create_tables([]) ->
        ok;
    create_tables([{Table, Attributes} | Tables]) ->
        case mnesia:create_table(Table, Attributes) of
            {atomic, ok}                       -> create_tables(Tables);
            {aborted, {already_exists, Table}} -> create_tables(Tables);
            Err                                -> Err
        end.
    
    table_definitions() ->
        {Name, Attributes} = ?TABLE,
        [{Name, [?TABLE_MATCH | Attributes]}].
    
    -spec start_link(group_name(), atom(), any(), txn_fun()) ->
              rabbit_types:ok_pid_or_error().
    
    start_link(GroupName, Module, Args, TxnFun) ->
        gen_server2:start_link(?MODULE, [GroupName, Module, Args, TxnFun],
                           [{spawn_opt, [{fullsweep_after, 0}]}]).
    
    -spec leave(pid()) -> 'ok'.
    
    leave(Server) ->
        gen_server2:cast(Server, leave).
    
    -spec broadcast(pid(), any()) -> 'ok'.
    
    broadcast(Server, Msg) -> broadcast(Server, Msg, 0).
    
    broadcast(Server, Msg, SizeHint) ->
        gen_server2:cast(Server, {broadcast, Msg, SizeHint}).
    
    -spec confirmed_broadcast(pid(), any()) -> 'ok'.
    
    confirmed_broadcast(Server, Msg) ->
        gen_server2:call(Server, {confirmed_broadcast, Msg}, infinity).
    
    -spec info(pid()) -> rabbit_types:infos().
    
    info(Server) ->
        gen_server2:call(Server, info, infinity).
    
    -spec validate_members(pid(), [pid()]) -> 'ok'.
    
    validate_members(Server, Members) ->
        gen_server2:cast(Server, {validate_members, Members}).
    
    -spec forget_group(group_name()) -> 'ok'.
    
    forget_group(GroupName) ->
        {atomic, ok} = mnesia:sync_transaction(
                         fun () ->
                                 mnesia:delete({?GROUP_TABLE, GroupName})
                         end),
        ok.
    
    init([GroupName, Module, Args, TxnFun]) ->
        put(process_name, {?MODULE, GroupName}),
        Self = make_member(GroupName),
        gen_server2:cast(self(), join),
        {ok, #state { self                = Self,
                      left                = {Self, undefined},
                      right               = {Self, undefined},
                      group_name          = GroupName,
                      module              = Module,
                      view                = undefined,
                      pub_count           = -1,
                      members_state       = undefined,
                      callback_args       = Args,
                      confirms            = queue:new(),
                      broadcast_buffer    = [],
                      broadcast_buffer_sz = 0,
                      broadcast_timer     = undefined,
                      force_gc_timer      = undefined,
                      txn_executor        = TxnFun,
                      shutting_down       = false }}.
    
    
    handle_call({confirmed_broadcast, _Msg}, _From,
                State = #state { shutting_down = {true, _} }) ->
        reply(shutting_down, State);
    
    handle_call({confirmed_broadcast, _Msg}, _From,
                State = #state { members_state = undefined }) ->
        reply(not_joined, State);
    
    handle_call({confirmed_broadcast, Msg}, _From,
                State = #state { self          = Self,
                                 right         = {Self, undefined},
                                 module        = Module,
                                 callback_args = Args }) ->
        handle_callback_result({Module:handle_msg(Args, get_pid(Self), Msg),
                               ok, State});
    
    handle_call({confirmed_broadcast, Msg}, From, State) ->
        {Result, State1 = #state { pub_count = PubCount, confirms = Confirms }} =
            internal_broadcast(Msg, 0, State),
        Confirms1 = queue:in({PubCount, From}, Confirms),
        handle_callback_result({Result, flush_broadcast_buffer(
                                          State1 #state { confirms = Confirms1 })});
    
    handle_call(info, _From,
                State = #state { members_state = undefined }) ->
        reply(not_joined, State);
    
    handle_call(info, _From, State = #state { group_name = GroupName,
                                              module     = Module,
                                              view       = View }) ->
        reply([{group_name,    GroupName},
               {module,        Module},
               {group_members, get_pids(alive_view_members(View))}], State);
    
    handle_call({add_on_right, _NewMember}, _From,
                State = #state { members_state = undefined }) ->
        reply(not_ready, State);
    
    handle_call({add_on_right, NewMember}, _From,
                State = #state { self          = Self,
                                 group_name    = GroupName,
                                 members_state = MembersState,
                                 txn_executor  = TxnFun }) ->
        try
            Group = record_new_member_in_group(
                      NewMember, Self, GroupName, TxnFun),
            View1 = group_to_view(check_membership(Self, Group)),
            MembersState1 = remove_erased_members(MembersState, View1),
            ok = send_right(NewMember, View1,
                            {catchup, Self, prepare_members_state(MembersState1)}),
            {Result, State1} = change_view(View1, State #state {
                                                    members_state = MembersState1 }),
            handle_callback_result({Result, {ok, Group}, State1})
        catch
            lost_membership ->
                {stop, shutdown, State}
        end.
    
    %% add_on_right causes a catchup to be sent immediately from the left,
    %% so we can never see this from the left neighbour. However, it's
    %% possible for the right neighbour to send us a check_neighbours
    %% immediately before that. We can't possibly handle it, but if we're
    %% in this state we know a catchup is coming imminently anyway. So
    %% just ignore it.
    handle_cast({?TAG, _ReqVer, check_neighbours},
                State = #state { members_state = undefined }) ->
        noreply(State);
    
    handle_cast({?TAG, ReqVer, Msg},
                State = #state { view          = View,
                                 self          = Self,
                                 members_state = MembersState,
                                 group_name    = GroupName }) ->
        try
            {Result, State1} =
                case needs_view_update(ReqVer, View) of
                    true  ->
                        View1 = group_to_view(
                                  check_membership(Self,
                                                   dirty_read_group(GroupName))),
                        MemberState1 = remove_erased_members(MembersState, View1),
                        change_view(View1, State #state {
                                             members_state = MemberState1 });
                    false -> {ok, State}
                end,
            handle_callback_result(
              if_callback_success(
                Result, fun handle_msg_true/3, fun handle_msg_false/3, Msg, State1))
        catch
            lost_membership ->
                {stop, shutdown, State}
        end;
    
    handle_cast({broadcast, _Msg, _SizeHint},
                State = #state { shutting_down = {true, _} }) ->
        noreply(State);
    
    handle_cast({broadcast, _Msg, _SizeHint},
                State = #state { members_state = undefined }) ->
        noreply(State);
    
    handle_cast({broadcast, Msg, _SizeHint},
                State = #state { self          = Self,
                                 right         = {Self, undefined},
                                 module        = Module,
                                 callback_args = Args }) ->
        handle_callback_result({Module:handle_msg(Args, get_pid(Self), Msg),
                                State});
    
    handle_cast({broadcast, Msg, SizeHint}, State) ->
        {Result, State1} = internal_broadcast(Msg, SizeHint, State),
        handle_callback_result({Result, maybe_flush_broadcast_buffer(State1)});
    
    handle_cast(join, State = #state { self          = Self,
                                       group_name    = GroupName,
                                       members_state = undefined,
                                       module        = Module,
                                       callback_args = Args,
                                       txn_executor  = TxnFun }) ->
        try
    	View = join_group(Self, GroupName, TxnFun),
    	MembersState =
    	    case alive_view_members(View) of
    		[Self] -> blank_member_state();
    		_      -> undefined
    	    end,
    	State1 = check_neighbours(State #state { view          = View,
    						 members_state = MembersState }),
    	handle_callback_result(
    	  {Module:joined(Args, get_pids(all_known_members(View))), State1})
        catch
            lost_membership ->
                {stop, shutdown, State}
        end;
    
    handle_cast({validate_members, OldMembers},
                State = #state { view          = View,
                                 module        = Module,
                                 callback_args = Args }) ->
        NewMembers = get_pids(all_known_members(View)),
        Births = NewMembers -- OldMembers,
        Deaths = OldMembers -- NewMembers,
        case {Births, Deaths} of
            {[], []}  -> noreply(State);
            _         -> Result = Module:members_changed(Args, Births, Deaths),
                         handle_callback_result({Result, State})
        end;
    
    handle_cast(leave, State) ->
        {stop, normal, State}.
    
    
    handle_info(force_gc, State) ->
        garbage_collect(),
        noreply(State #state { force_gc_timer = undefined });
    
    handle_info(flush, State) ->
        noreply(
          flush_broadcast_buffer(State #state { broadcast_timer = undefined }));
    
    handle_info(timeout, State) ->
        noreply(flush_broadcast_buffer(State));
    
    handle_info({'DOWN', _MRef, process, _Pid, _Reason},
                State = #state { shutting_down =
                                     {true, {shutdown, ring_shutdown}} }) ->
        noreply(State);
    handle_info({'DOWN', MRef, process, _Pid, Reason},
                State = #state { self          = Self,
                                 left          = Left,
                                 right         = Right,
                                 group_name    = GroupName,
                                 confirms      = Confirms,
                                 txn_executor  = TxnFun }) ->
        try
            check_membership(GroupName),
            Member = case {Left, Right} of
                         {{Member1, MRef}, _} -> Member1;
                         {_, {Member1, MRef}} -> Member1;
                         _                    -> undefined
                     end,
            case {Member, Reason} of
                {undefined, _} ->
                    noreply(State);
                {_, {shutdown, ring_shutdown}} ->
                    noreply(State);
                _ ->
                    %% In the event of a partial partition we could see another member
                    %% go down and then remove them from Mnesia. While they can
                    %% recover from this they'd have to restart the queue - not
                    %% ideal. So let's sleep here briefly just in case this was caused
                    %% by a partial partition; in which case by the time we record the
                    %% member death in Mnesia we will probably be in a full
                    %% partition and will not be assassinating another member.
                    timer:sleep(100),
                    View1 = group_to_view(record_dead_member_in_group(Self,
                                            Member, GroupName, TxnFun, true)),
                    handle_callback_result(
                      case alive_view_members(View1) of
                          [Self] -> maybe_erase_aliases(
                                      State #state {
                                        members_state = blank_member_state(),
                                        confirms      = purge_confirms(Confirms) },
                                      View1);
                          _      -> change_view(View1, State)
                      end)
            end
        catch
            lost_membership ->
                {stop, shutdown, State}
        end;
    handle_info(_, State) ->
        %% Discard any unexpected messages, such as late replies from neighbour_call/2
        %% TODO: For #gm_group{} related info messages, it could be worthwhile to
        %% change_view/2, as this might reflect an alteration in the gm group, meaning
        %% we now need to update our state. see rabbitmq-server#914.
        noreply(State).
    
    terminate(Reason, #state { module = Module, callback_args = Args }) ->
        Module:handle_terminate(Args, Reason).
    
    code_change(_OldVsn, State, _Extra) ->
        {ok, State}.
    
    prioritise_info(flush, _Len, _State) ->
        1;
    %% DOWN messages should not overtake initial catchups; if they do we
    %% will receive a DOWN we do not know what to do with.
    prioritise_info({'DOWN', _MRef, process, _Pid, _Reason}, _Len,
                    #state { members_state = undefined }) ->
        0;
    %% We should not prioritise DOWN messages from our left since
    %% otherwise the DOWN can overtake any last activity from the left,
    %% causing that activity to be lost.
    prioritise_info({'DOWN', _MRef, process, LeftPid, _Reason}, _Len,
                    #state { left = {{_LeftVer, LeftPid}, _MRef2} }) ->
        0;
    %% But prioritise all other DOWNs - we want to make sure we are not
    %% sending activity into the void for too long because our right is
    %% down but we don't know it.
    prioritise_info({'DOWN', _MRef, process, _Pid, _Reason}, _Len, _State) ->
        1;
    prioritise_info(_, _Len, _State) ->
        0.
    
    
    handle_msg(check_neighbours, State) ->
        %% no-op - it's already been done by the calling handle_cast
        {ok, State};
    
    handle_msg({catchup, Left, MembersStateLeft},
               State = #state { self          = Self,
                                left          = {Left, _MRefL},
                                right         = {Right, _MRefR},
                                view          = View,
                                members_state = undefined }) ->
        ok = send_right(Right, View, {catchup, Self, MembersStateLeft}),
        MembersStateLeft1 = build_members_state(MembersStateLeft),
        {ok, State #state { members_state = MembersStateLeft1 }};
    
    handle_msg({catchup, Left, MembersStateLeft},
               State = #state { self = Self,
                                left = {Left, _MRefL},
                                view = View,
                                members_state = MembersState })
      when MembersState =/= undefined ->
        MembersStateLeft1 = build_members_state(MembersStateLeft),
        AllMembers = lists:usort(maps:keys(MembersState) ++
                                     maps:keys(MembersStateLeft1)),
        {MembersState1, Activity} =
            lists:foldl(
              fun (Id, MembersStateActivity) ->
                      #member { pending_ack = PALeft, last_ack = LA } =
                          find_member_or_blank(Id, MembersStateLeft1),
                      with_member_acc(
                        fun (#member { pending_ack = PA } = Member, Activity1) ->
                                case is_member_alias(Id, Self, View) of
                                    true ->
                                        {_AcksInFlight, Pubs, _PA1} =
                                            find_prefix_common_suffix(PALeft, PA),
                                        {Member #member { last_ack = LA },
                                         activity_cons(Id, pubs_from_queue(Pubs),
                                                       [], Activity1)};
                                    false ->
                                        {Acks, _Common, Pubs} =
                                            find_prefix_common_suffix(PA, PALeft),
                                        {Member,
                                         activity_cons(Id, pubs_from_queue(Pubs),
                                                       acks_from_queue(Acks),
                                                       Activity1)}
                                end
                        end, Id, MembersStateActivity)
              end, {MembersState, activity_nil()}, AllMembers),
        handle_msg({activity, Left, activity_finalise(Activity)},
                   State #state { members_state = MembersState1 });
    
    handle_msg({catchup, _NotLeft, _MembersState}, State) ->
        {ok, State};
    
    handle_msg({activity, Left, Activity},
               State = #state { self          = Self,
                                group_name    = GroupName,
                                left          = {Left, _MRefL},
                                view          = View,
                                members_state = MembersState,
                                confirms      = Confirms })
      when MembersState =/= undefined ->
        try
            %% If we have to stop, do it asap so we avoid any ack confirmation
            %% Membership must be checked again by erase_members_in_group, as the
            %% node can be marked as dead on the meanwhile
            check_membership(GroupName),
            {MembersState1, {Confirms1, Activity1}} =
                calculate_activity(MembersState, Confirms, Activity, Self, View),
            State1 = State #state { members_state = MembersState1,
                                    confirms      = Confirms1 },
            Activity3 = activity_finalise(Activity1),
            ok = maybe_send_activity(Activity3, State1),
            {Result, State2} = maybe_erase_aliases(State1, View),
            if_callback_success(
              Result, fun activity_true/3, fun activity_false/3, Activity3, State2)
        catch
            lost_membership ->
                {{stop, shutdown}, State}
        end;
    
    handle_msg({activity, _NotLeft, _Activity}, State) ->
        {ok, State}.
    
    
    noreply(State) ->
        {noreply, ensure_timers(State), flush_timeout(State)}.
    
    reply(Reply, State) ->
        {reply, Reply, ensure_timers(State), flush_timeout(State)}.
    
    ensure_timers(State) ->
        ensure_force_gc_timer(ensure_broadcast_timer(State)).
    
    flush_timeout(#state{broadcast_buffer = []}) -> infinity;
    flush_timeout(_)                             -> 0.
    
    ensure_force_gc_timer(State = #state { force_gc_timer = TRef })
      when is_reference(TRef) ->
        State;
    ensure_force_gc_timer(State = #state { force_gc_timer = undefined }) ->
        TRef = erlang:send_after(?FORCE_GC_TIMER, self(), force_gc),
        State #state { force_gc_timer = TRef }.
    
    ensure_broadcast_timer(State = #state { broadcast_buffer = [],
                                            broadcast_timer  = undefined }) ->
        State;
    ensure_broadcast_timer(State = #state { broadcast_buffer = [],
                                            broadcast_timer  = TRef }) ->
        _ = erlang:cancel_timer(TRef),
        State #state { broadcast_timer = undefined };
    ensure_broadcast_timer(State = #state { broadcast_timer = undefined }) ->
        TRef = erlang:send_after(?BROADCAST_TIMER, self(), flush),
        State #state { broadcast_timer = TRef };
    ensure_broadcast_timer(State) ->
        State.
    
    internal_broadcast(Msg, SizeHint,
                       State = #state { self                = Self,
                                        pub_count           = PubCount,
                                        module              = Module,
                                        callback_args       = Args,
                                        broadcast_buffer    = Buffer,
                                        broadcast_buffer_sz = BufferSize }) ->
        PubCount1 = PubCount + 1,
        {Module:handle_msg(Args, get_pid(Self), Msg),
         State #state { pub_count           = PubCount1,
                        broadcast_buffer    = [{PubCount1, Msg} | Buffer],
                        broadcast_buffer_sz = BufferSize + SizeHint}}.
    
    %% The Erlang distribution mechanism has an interesting quirk - it
    %% will kill the VM cold with "Absurdly large distribution output data
    %% buffer" if you attempt to send a message which serialises out to
    %% more than 2^31 bytes in size. It's therefore a very good idea to
    %% make sure that we don't exceed that size!
    %%
    %% Now, we could figure out the size of messages as they come in using
    %% size(term_to_binary(Msg)) or similar. The trouble is, that requires
    %% us to serialise the message only to throw the serialised form
    %% away. Hard to believe that's a sensible thing to do. So instead we
    %% accept a size hint from the application, via broadcast/3. This size
    %% hint can be the size of anything in the message which we expect
    %% could be large, and we just ignore the size of any small bits of
    %% the message term. Therefore MAX_BUFFER_SIZE is set somewhat
    %% conservatively at 100MB - but the buffer is only to allow us to
    %% buffer tiny messages anyway, so 100MB is plenty.
    
    maybe_flush_broadcast_buffer(State = #state{broadcast_buffer_sz = Size}) ->
        case Size > ?MAX_BUFFER_SIZE of
            true  -> flush_broadcast_buffer(State);
            false -> State
        end.
    
    flush_broadcast_buffer(State = #state { broadcast_buffer = [] }) ->
        State;
    flush_broadcast_buffer(State = #state { self             = Self,
                                            members_state    = MembersState,
                                            broadcast_buffer = Buffer,
                                            pub_count        = PubCount }) ->
        [{PubCount, _Msg}|_] = Buffer, %% ASSERTION match on PubCount
        Pubs = lists:reverse(Buffer),
        Activity = activity_cons(Self, Pubs, [], activity_nil()),
        ok = maybe_send_activity(activity_finalise(Activity), State),
        MembersState1 = with_member(
                          fun (Member = #member { pending_ack = PA }) ->
                                  PA1 = queue:join(PA, queue:from_list(Pubs)),
                                  Member #member { pending_ack = PA1,
                                                   last_pub = PubCount }
                          end, Self, MembersState),
        State #state { members_state       = MembersState1,
                       broadcast_buffer    = [],
                       broadcast_buffer_sz = 0 }.
    
    %% ---------------------------------------------------------------------------
    %% View construction and inspection
    %% ---------------------------------------------------------------------------
    
    needs_view_update(ReqVer, {Ver, _View}) -> Ver < ReqVer.
    
    view_version({Ver, _View}) -> Ver.
    
    is_member_alive({dead, _Member}) -> false;
    is_member_alive(_)               -> true.
    
    is_member_alias(Self, Self, _View) ->
        true;
    is_member_alias(Member, Self, View) ->
        ?SETS:is_element(Member,
                         ((fetch_view_member(Self, View)) #view_member.aliases)).
    
    dead_member_id({dead, Member}) -> Member.
    
    store_view_member(VMember = #view_member { id = Id }, {Ver, View}) ->
        {Ver, maps:put(Id, VMember, View)}.
    
    with_view_member(Fun, View, Id) ->
        store_view_member(Fun(fetch_view_member(Id, View)), View).
    
    fetch_view_member(Id, {_Ver, View}) -> maps:get(Id, View).
    
    find_view_member(Id, {_Ver, View}) -> maps:find(Id, View).
    
    blank_view(Ver) -> {Ver, maps:new()}.
    
    alive_view_members({_Ver, View}) -> maps:keys(View).
    
    all_known_members({_Ver, View}) ->
        maps:fold(
           fun (Member, #view_member { aliases = Aliases }, Acc) ->
                   ?SETS:to_list(Aliases) ++ [Member | Acc]
           end, [], View).
    
    group_to_view(#gm_group { members = Members, version = Ver }) ->
        Alive = lists:filter(fun is_member_alive/1, Members),
        [_|_] = Alive, %% ASSERTION - can't have all dead members
        add_aliases(link_view(Alive ++ Alive ++ Alive, blank_view(Ver)), Members).
    
    link_view([Left, Middle, Right | Rest], View) ->
        case find_view_member(Middle, View) of
            error ->
                link_view(
                  [Middle, Right | Rest],
                  store_view_member(#view_member { id      = Middle,
                                                   aliases = ?SETS:new(),
                                                   left    = Left,
                                                   right   = Right }, View));
            {ok, _} ->
                View
        end;
    link_view(_, View) ->
        View.
    
    add_aliases(View, Members) ->
        Members1 = ensure_alive_suffix(Members),
        {EmptyDeadSet, View1} =
            lists:foldl(
              fun (Member, {DeadAcc, ViewAcc}) ->
                      case is_member_alive(Member) of
                          true ->
                              {?SETS:new(),
                               with_view_member(
                                 fun (VMember =
                                          #view_member { aliases = Aliases }) ->
                                         VMember #view_member {
                                           aliases = ?SETS:union(Aliases, DeadAcc) }
                                 end, ViewAcc, Member)};
                          false ->
                              {?SETS:add_element(dead_member_id(Member), DeadAcc),
                               ViewAcc}
                      end
              end, {?SETS:new(), View}, Members1),
        0 = ?SETS:size(EmptyDeadSet), %% ASSERTION
        View1.
    
    ensure_alive_suffix(Members) ->
        queue:to_list(ensure_alive_suffix1(queue:from_list(Members))).
    
    ensure_alive_suffix1(MembersQ) ->
        {{value, Member}, MembersQ1} = queue:out_r(MembersQ),
        case is_member_alive(Member) of
            true  -> MembersQ;
            false -> ensure_alive_suffix1(queue:in_r(Member, MembersQ1))
        end.
    
    
    %% ---------------------------------------------------------------------------
    %% View modification
    %% ---------------------------------------------------------------------------
    
    join_group(Self, GroupName, TxnFun) ->
        join_group(Self, GroupName, dirty_read_group(GroupName), TxnFun).
    
    join_group(Self, GroupName, {error, not_found}, TxnFun) ->
        join_group(Self, GroupName,
                   prune_or_create_group(Self, GroupName, TxnFun), TxnFun);
    join_group(Self, _GroupName, #gm_group { members = [Self] } = Group, _TxnFun) ->
        group_to_view(Group);
    join_group(Self, GroupName, #gm_group { members = Members } = Group, TxnFun) ->
        case lists:member(Self, Members) of
            true ->
                group_to_view(Group);
            false ->
                case lists:filter(fun is_member_alive/1, Members) of
                    [] ->
                        join_group(Self, GroupName,
                                   prune_or_create_group(Self, GroupName, TxnFun),
                                   TxnFun);
                    Alive ->
                        Left = lists:nth(rand:uniform(length(Alive)), Alive),
                        Handler =
                            fun () ->
                                    join_group(
                                      Self, GroupName,
                                      record_dead_member_in_group(Self,
                                        Left, GroupName, TxnFun, false),
                                      TxnFun)
                            end,
                        try
                            case neighbour_call(Left, {add_on_right, Self}) of
                                {ok, Group1} -> group_to_view(Group1);
                                not_ready    -> join_group(Self, GroupName, TxnFun)
                            end
                        catch
                            exit:{R, _}
                              when R =:= noproc; R =:= normal; R =:= shutdown ->
                                Handler();
                            exit:{{R, _}, _}
                              when R =:= nodedown; R =:= shutdown ->
                                Handler()
                        end
                end
        end.
    
    dirty_read_group(GroupName) ->
        case mnesia:dirty_read(?GROUP_TABLE, GroupName) of
            []      -> {error, not_found};
            [Group] -> Group
        end.
    
    read_group(GroupName) ->
        case mnesia:read({?GROUP_TABLE, GroupName}) of
            []      -> {error, not_found};
            [Group] -> Group
        end.
    
    write_group(Group) -> mnesia:write(?GROUP_TABLE, Group, write), Group.
    
    prune_or_create_group(Self, GroupName, TxnFun) ->
        TxnFun(
          fun () ->
                  GroupNew = #gm_group { name    = GroupName,
                                         members = [Self],
                                         version = get_version(Self) },
                  case read_group(GroupName) of
                      {error, not_found} ->
                          write_group(GroupNew);
                      Group = #gm_group { members = Members } ->
                          case lists:any(fun is_member_alive/1, Members) of
                              true  -> Group;
                              false -> write_group(GroupNew)
                          end
                  end
          end).
    
    record_dead_member_in_group(Self, Member, GroupName, TxnFun, Verify) ->
        Fun =
            fun () ->
                    try
                        Group = #gm_group { members = Members, version = Ver } =
                            case Verify of
                                true ->
                                    check_membership(Self, read_group(GroupName));
                                false ->
                                    check_group(read_group(GroupName))
                            end,
                        case lists:splitwith(
                               fun (Member1) -> Member1 =/= Member end, Members) of
                            {_Members1, []} -> %% not found - already recorded dead
                                Group;
                            {Members1, [Member | Members2]} ->
                                Members3 = Members1 ++ [{dead, Member} | Members2],
                                write_group(Group #gm_group { members = Members3,
                                                              version = Ver + 1 })
                        end
                    catch
                        lost_membership ->
                            %% The transaction must not be abruptly crashed, but
                            %% leave the gen_server to stop normally
                            {error, lost_membership}
                    end
            end,
        handle_lost_membership_in_txn(TxnFun, Fun).
    
    handle_lost_membership_in_txn(TxnFun, Fun) ->
        case TxnFun(Fun)  of
            {error, lost_membership = T} ->
                throw(T);
            Any ->
                Any
        end.
    
    record_new_member_in_group(NewMember, Left, GroupName, TxnFun) ->
        Fun =
            fun () ->
                    try
                        Group = #gm_group { members = Members, version = Ver } =
                            check_membership(Left, read_group(GroupName)),
                        case lists:member(NewMember, Members) of
                            true ->
                                %% This avois duplicates during partial partitions,
                                %% as inconsistent views might happen during them
                                rabbit_log:warning("(~p) GM avoiding duplicate of ~p",
                                                   [self(), NewMember]),
                                Group;
                            false ->
                                {Prefix, [Left | Suffix]} =
                                    lists:splitwith(fun (M) -> M =/= Left end, Members),
                                write_group(Group #gm_group {
                                              members = Prefix ++ [Left, NewMember | Suffix],
                                              version = Ver + 1 })
                        end
                    catch
                        lost_membership ->
                            %% The transaction must not be abruptly crashed, but
                            %% leave the gen_server to stop normally
                            {error, lost_membership}
                    end
            end,
        handle_lost_membership_in_txn(TxnFun, Fun).
    
    erase_members_in_group(Self, Members, GroupName, TxnFun) ->
        DeadMembers = [{dead, Id} || Id <- Members],
        Fun =
            fun () ->
                    try
                        Group = #gm_group { members = [_|_] = Members1, version = Ver } =
                            check_membership(Self, read_group(GroupName)),
                        case Members1 -- DeadMembers of
                            Members1 -> Group;
                            Members2 -> write_group(
                                          Group #gm_group { members = Members2,
                                                            version = Ver + 1 })
                        end
                  catch
                      lost_membership ->
                          %% The transaction must not be abruptly crashed, but
                          %% leave the gen_server to stop normally
                          {error, lost_membership}
                  end
            end,
        handle_lost_membership_in_txn(TxnFun, Fun).
    
    maybe_erase_aliases(State = #state { self          = Self,
                                         group_name    = GroupName,
                                         members_state = MembersState,
                                         txn_executor  = TxnFun }, View) ->
        #view_member { aliases = Aliases } = fetch_view_member(Self, View),
        {Erasable, MembersState1}
            = ?SETS:fold(
                 fun (Id, {ErasableAcc, MembersStateAcc} = Acc) ->
                         #member { last_pub = LP, last_ack = LA } =
                             find_member_or_blank(Id, MembersState),
                         case can_erase_view_member(Self, Id, LA, LP) of
                             true  -> {[Id | ErasableAcc],
                                       erase_member(Id, MembersStateAcc)};
                             false -> Acc
                         end
                 end, {[], MembersState}, Aliases),
        View1 = case Erasable of
                    [] -> View;
                    _  -> group_to_view(
                            erase_members_in_group(Self, Erasable, GroupName, TxnFun))
                end,
        change_view(View1, State #state { members_state = MembersState1 }).
    
    can_erase_view_member(Self, Self, _LA, _LP) -> false;
    can_erase_view_member(_Self, _Id,   N,   N) -> true;
    can_erase_view_member(_Self, _Id, _LA, _LP) -> false.
    
    neighbour_cast(N, Msg) -> ?INSTR_MOD:cast(get_pid(N), Msg).
    neighbour_call(N, Msg) -> ?INSTR_MOD:call(get_pid(N), Msg, infinity).
    
    %% ---------------------------------------------------------------------------
    %% View monitoring and maintenance
    %% ---------------------------------------------------------------------------
    
    ensure_neighbour(_Ver, Self, {Self, undefined}, Self) ->
        {Self, undefined};
    ensure_neighbour(Ver, Self, {Self, undefined}, RealNeighbour) ->
        ok = neighbour_cast(RealNeighbour, {?TAG, Ver, check_neighbours}),
        {RealNeighbour, maybe_monitor(RealNeighbour, Self)};
    ensure_neighbour(_Ver, _Self, {RealNeighbour, MRef}, RealNeighbour) ->
        {RealNeighbour, MRef};
    ensure_neighbour(Ver, Self, {RealNeighbour, MRef}, Neighbour) ->
        true = ?INSTR_MOD:demonitor(MRef),
        Msg = {?TAG, Ver, check_neighbours},
        ok = neighbour_cast(RealNeighbour, Msg),
        ok = case Neighbour of
                 Self -> ok;
                 _    -> neighbour_cast(Neighbour, Msg)
             end,
        {Neighbour, maybe_monitor(Neighbour, Self)}.
    
    maybe_monitor( Self,  Self) -> undefined;
    maybe_monitor(Other, _Self) -> ?INSTR_MOD:monitor(get_pid(Other)).
    
    check_neighbours(State = #state { self             = Self,
                                      left             = Left,
                                      right            = Right,
                                      view             = View,
                                      broadcast_buffer = Buffer }) ->
        #view_member { left = VLeft, right = VRight }
            = fetch_view_member(Self, View),
        Ver = view_version(View),
        Left1 = ensure_neighbour(Ver, Self, Left, VLeft),
        Right1 = ensure_neighbour(Ver, Self, Right, VRight),
        Buffer1 = case Right1 of
                      {Self, undefined} -> [];
                      _                 -> Buffer
                  end,
        State1 = State #state { left = Left1, right = Right1,
                                broadcast_buffer = Buffer1 },
        ok = maybe_send_catchup(Right, State1),
        State1.
    
    maybe_send_catchup(Right, #state { right = Right }) ->
        ok;
    maybe_send_catchup(_Right, #state { self  = Self,
                                        right = {Self, undefined} }) ->
        ok;
    maybe_send_catchup(_Right, #state { members_state = undefined }) ->
        ok;
    maybe_send_catchup(_Right, #state { self          = Self,
                                        right         = {Right, _MRef},
                                        view          = View,
                                        members_state = MembersState }) ->
        send_right(Right, View,
                   {catchup, Self, prepare_members_state(MembersState)}).
    
    
    %% ---------------------------------------------------------------------------
    %% Catch_up delta detection
    %% ---------------------------------------------------------------------------
    
    find_prefix_common_suffix(A, B) ->
        {Prefix, A1} = find_prefix(A, B, queue:new()),
        {Common, Suffix} = find_common(A1, B, queue:new()),
        {Prefix, Common, Suffix}.
    
    %% Returns the elements of A that occur before the first element of B,
    %% plus the remainder of A.
    find_prefix(A, B, Prefix) ->
        case {queue:out(A), queue:out(B)} of
            {{{value, Val}, _A1}, {{value, Val}, _B1}} ->
                {Prefix, A};
            {{empty, A1}, {{value, _A}, _B1}} ->
                {Prefix, A1};
            {{{value, {NumA, _MsgA} = Val}, A1},
             {{value, {NumB, _MsgB}}, _B1}} when NumA < NumB ->
                find_prefix(A1, B, queue:in(Val, Prefix));
            {_, {empty, _B1}} ->
                {A, Prefix} %% Prefix well be empty here
        end.
    
    %% A should be a prefix of B. Returns the commonality plus the
    %% remainder of B.
    find_common(A, B, Common) ->
        case {queue:out(A), queue:out(B)} of
            {{{value, Val}, A1}, {{value, Val}, B1}} ->
                find_common(A1, B1, queue:in(Val, Common));
            {{empty, _A}, _} ->
                {Common, B};
            %% Drop value from B.
            %% Match value to avoid infinite loop, since {empty, B} = queue:out(B).
            {_, {{value, _}, B1}} ->
                find_common(A, B1, Common);
            %% Drop value from A. Empty A should be matched by second close.
            {{{value, _}, A1}, _} ->
                find_common(A1, B, Common)
        end.
    
    
    %% ---------------------------------------------------------------------------
    %% Members helpers
    %% ---------------------------------------------------------------------------
    
    with_member(Fun, Id, MembersState) ->
        store_member(
          Id, Fun(find_member_or_blank(Id, MembersState)), MembersState).
    
    with_member_acc(Fun, Id, {MembersState, Acc}) ->
        {MemberState, Acc1} = Fun(find_member_or_blank(Id, MembersState), Acc),
        {store_member(Id, MemberState, MembersState), Acc1}.
    
    find_member_or_blank(Id, MembersState) ->
        case maps:find(Id, MembersState) of
            {ok, Result} -> Result;
            error        -> blank_member()
        end.
    
    erase_member(Id, MembersState) -> maps:remove(Id, MembersState).
    
    blank_member() ->
        #member { pending_ack = queue:new(), last_pub = -1, last_ack = -1 }.
    
    blank_member_state() -> maps:new().
    
    store_member(Id, MemberState, MembersState) ->
        maps:put(Id, MemberState, MembersState).
    
    prepare_members_state(MembersState) -> maps:to_list(MembersState).
    
    build_members_state(MembersStateList) -> maps:from_list(MembersStateList).
    
    make_member(GroupName) ->
       {case dirty_read_group(GroupName) of
            #gm_group { version = Version } -> Version;
            {error, not_found}              -> ?VERSION_START
        end, self()}.
    
    remove_erased_members(MembersState, View) ->
        lists:foldl(fun (Id, MembersState1) ->
                        store_member(Id, find_member_or_blank(Id, MembersState),
                                     MembersState1)
                    end, blank_member_state(), all_known_members(View)).
    
    get_version({Version, _Pid}) -> Version.
    
    get_pid({_Version, Pid}) -> Pid.
    
    get_pids(Ids) -> [Pid || {_Version, Pid} <- Ids].
    
    %% ---------------------------------------------------------------------------
    %% Activity assembly
    %% ---------------------------------------------------------------------------
    
    activity_nil() -> queue:new().
    
    activity_cons(   _Id,   [],   [], Tail) -> Tail;
    activity_cons(Sender, Pubs, Acks, Tail) -> queue:in({Sender, Pubs, Acks}, Tail).
    
    activity_finalise(Activity) -> queue:to_list(Activity).
    
    maybe_send_activity([], _State) ->
        ok;
    maybe_send_activity(Activity, #state { self  = Self,
                                           right = {Right, _MRefR},
                                           view  = View }) ->
        send_right(Right, View, {activity, Self, Activity}).
    
    send_right(Right, View, Msg) ->
        ok = neighbour_cast(Right, {?TAG, view_version(View), Msg}).
    
    calculate_activity(MembersState, Confirms, Activity, Self, View) ->
        lists:foldl(
          fun ({Id, Pubs, Acks}, MembersStateConfirmsActivity) ->
                  with_member_acc(
                    fun (Member = #member { pending_ack = PA,
                                            last_pub    = LP,
                                            last_ack    = LA },
                         {Confirms2, Activity2}) ->
                            case is_member_alias(Id, Self, View) of
                                true ->
                                    {ToAck, PA1} =
                                        find_common(queue_from_pubs(Pubs), PA,
                                                    queue:new()),
                                    LA1 = last_ack(Acks, LA),
                                    AckNums = acks_from_queue(ToAck),
                                    Confirms3 = maybe_confirm(
                                                  Self, Id, Confirms2, AckNums),
                                    {Member #member { pending_ack = PA1,
                                                      last_ack    = LA1 },
                                     {Confirms3,
                                      activity_cons(
                                        Id, [], AckNums, Activity2)}};
                                false ->
                                    PA1 = apply_acks(Acks, join_pubs(PA, Pubs)),
                                    LA1 = last_ack(Acks, LA),
                                    LP1 = last_pub(Pubs, LP),
                                    {Member #member { pending_ack = PA1,
                                                      last_pub    = LP1,
                                                      last_ack    = LA1 },
                                     {Confirms2,
                                      activity_cons(Id, Pubs, Acks, Activity2)}}
                            end
                    end, Id, MembersStateConfirmsActivity)
          end, {MembersState, {Confirms, activity_nil()}}, Activity).
    
    callback(Args, Module, Activity) ->
        Result =
          lists:foldl(
            fun ({Id, Pubs, _Acks}, {Args1, Module1, ok}) ->
                    lists:foldl(fun ({_PubNum, Pub}, Acc = {Args2, Module2, ok}) ->
                                        case Module2:handle_msg(
                                               Args2, get_pid(Id), Pub) of
                                            ok ->
                                                Acc;
                                            {become, Module3, Args3} ->
                                                {Args3, Module3, ok};
                                            {stop, _Reason} = Error ->
                                                Error
                                        end;
                                    (_, Error = {stop, _Reason}) ->
                                        Error
                                end, {Args1, Module1, ok}, Pubs);
                (_, Error = {stop, _Reason}) ->
                    Error
            end, {Args, Module, ok}, Activity),
        case Result of
            {Args, Module, ok}      -> ok;
            {Args1, Module1, ok}    -> {become, Module1, Args1};
            {stop, _Reason} = Error -> Error
        end.
    
    change_view(View, State = #state { view          = View0,
                                       module        = Module,
                                       callback_args = Args }) ->
        OldMembers = all_known_members(View0),
        NewMembers = all_known_members(View),
        Births = NewMembers -- OldMembers,
        Deaths = OldMembers -- NewMembers,
        Result = case {Births, Deaths} of
                     {[], []} -> ok;
                     _        -> Module:members_changed(
                                   Args, get_pids(Births), get_pids(Deaths))
                 end,
        {Result, check_neighbours(State #state { view = View })}.
    
    handle_callback_result({Result, State}) ->
        if_callback_success(
          Result, fun no_reply_true/3, fun no_reply_false/3, undefined, State);
    handle_callback_result({Result, Reply, State}) ->
        if_callback_success(
          Result, fun reply_true/3, fun reply_false/3, Reply, State).
    
    no_reply_true (_Result,        _Undefined, State) -> noreply(State).
    no_reply_false({stop, Reason}, _Undefined, State) -> {stop, Reason, State}.
    
    reply_true (_Result,        Reply, State) -> reply(Reply, State).
    reply_false({stop, Reason}, Reply, State) -> {stop, Reason, Reply, State}.
    
    handle_msg_true (_Result, Msg, State) -> handle_msg(Msg, State).
    handle_msg_false(Result, _Msg, State) -> {Result, State}.
    
    activity_true(_Result, Activity, State = #state { module        = Module,
                                                      callback_args = Args }) ->
        {callback(Args, Module, Activity), State}.
    activity_false(Result, _Activity, State) ->
        {Result, State}.
    
    if_callback_success(Result, True, False, Arg, State) ->
        {NewResult, NewState} = maybe_stop(Result, State),
        if_callback_success1(NewResult, True, False, Arg, NewState).
    
    if_callback_success1(ok, True, _False, Arg, State) ->
        True(ok, Arg, State);
    if_callback_success1(
      {become, Module, Args} = Result, True, _False, Arg, State) ->
        True(Result, Arg, State #state { module        = Module,
                                         callback_args = Args });
    if_callback_success1({stop, _Reason} = Result, _True, False, Arg, State) ->
        False(Result, Arg, State).
    
    maybe_stop({stop, Reason}, #state{ shutting_down = false } = State) ->
        ShuttingDown = {true, Reason},
        case has_pending_messages(State) of
            true  -> {ok, State #state{ shutting_down = ShuttingDown }};
            false -> {{stop, Reason}, State #state{ shutting_down = ShuttingDown }}
        end;
    maybe_stop(Result, #state{ shutting_down = false } = State) ->
        {Result, State};
    maybe_stop(Result, #state{ shutting_down = {true, Reason} } = State) ->
        case has_pending_messages(State) of
            true  -> {Result, State};
            false -> {{stop, Reason}, State}
        end.
    
    has_pending_messages(#state{ broadcast_buffer = Buffer })
      when Buffer =/= [] ->
        true;
    has_pending_messages(#state{ members_state = MembersState }) ->
        MembersWithPubAckMismatches = maps:filter(fun(_Id, #member{last_pub = LP, last_ack = LA}) ->
                                                          LP =/= LA
                                                  end, MembersState),
        0 =/= maps:size(MembersWithPubAckMismatches).
    
    maybe_confirm(_Self, _Id, Confirms, []) ->
        Confirms;
    maybe_confirm(Self, Self, Confirms, [PubNum | PubNums]) ->
        case queue:out(Confirms) of
            {empty, _Confirms} ->
                Confirms;
            {{value, {PubNum, From}}, Confirms1} ->
                gen_server2:reply(From, ok),
                maybe_confirm(Self, Self, Confirms1, PubNums);
            {{value, {PubNum1, _From}}, _Confirms} when PubNum1 > PubNum ->
                maybe_confirm(Self, Self, Confirms, PubNums)
        end;
    maybe_confirm(_Self, _Id, Confirms, _PubNums) ->
        Confirms.
    
    purge_confirms(Confirms) ->
        _ = [gen_server2:reply(From, ok) || {_PubNum, From} <- queue:to_list(Confirms)],
        queue:new().
    
    
    %% ---------------------------------------------------------------------------
    %% Msg transformation
    %% ---------------------------------------------------------------------------
    
    acks_from_queue(Q) -> [PubNum || {PubNum, _Msg} <- queue:to_list(Q)].
    
    pubs_from_queue(Q) -> queue:to_list(Q).
    
    queue_from_pubs(Pubs) -> queue:from_list(Pubs).
    
    apply_acks(  [], Pubs) -> Pubs;
    apply_acks(List, Pubs) -> {_, Pubs1} = queue:split(length(List), Pubs),
                              Pubs1.
    
    join_pubs(Q, [])   -> Q;
    join_pubs(Q, Pubs) -> queue:join(Q, queue_from_pubs(Pubs)).
    
    last_ack(  [], LA) -> LA;
    last_ack(List, LA) -> LA1 = lists:last(List),
                          true = LA1 > LA, %% ASSERTION
                          LA1.
    
    last_pub(  [], LP) -> LP;
    last_pub(List, LP) -> {PubNum, _Msg} = lists:last(List),
                          true = PubNum > LP, %% ASSERTION
                          PubNum.
    
    %% ---------------------------------------------------------------------------
    
    %% Uninstrumented versions
    
    call(Pid, Msg, Timeout) -> gen_server2:call(Pid, Msg, Timeout).
    cast(Pid, Msg)          -> gen_server2:cast(Pid, Msg).
    monitor(Pid)            -> erlang:monitor(process, Pid).
    demonitor(MRef)         -> erlang:demonitor(MRef).
    
    check_membership(Self, #gm_group{members = M} = Group) ->
        case lists:member(Self, M) of
            true ->
                Group;
            false ->
                throw(lost_membership)
        end;
    check_membership(_Self, {error, not_found}) ->
        throw(lost_membership).
    
    check_membership(GroupName) ->
        case dirty_read_group(GroupName) of
            #gm_group{members = M} ->
                case lists:keymember(self(), 2, M) of
                    true ->
                        ok;
                    false ->
                        throw(lost_membership)
                end;
            {error, not_found} ->
                throw(lost_membership)
        end.
    
    check_group({error, not_found}) ->
        throw(lost_membership);
    check_group(Any) ->
        Any.
    
    

    故障节点消息同步

    当闭环中某个节点故障,需要故障节点上游节点经信息同步到故障节点的下游节点,需要决定哪个节点上的信息是最新的,RabbitMQ在每个节点设置view变量,

    如A->B->C->D->E变为A->E,假设A、B、C、D、E最初都有view值x。B、C、D同时退出时,A获悉B的退出消息,view值更新为x+1;E获悉D的退出消息,view值更新为x+2;然后A监控C,获悉C退出,view值更新为x+3;A继续获取下游节点E,向E发送自身状态,E的view值小于A,所以E先更新自身view(view值将更新为x+3),然后处理消息。(这是一种可能的顺序,真实的顺序按照节点收到退出消息顺序确定。)

    GM的实现可直接查看源码,有很好的代码注释:
      https://github.com/rabbitmq/rabbitmq-server/blob/stable/src/gm.erl

    Master提升

    GM保证了集群中slave节点挂掉时,消息不会丢失。当master节点挂掉时,最老的slave节点将被提升为master,此时channel发给原master的消息可能并没有通过原master的GM广播出来,所以该场景下需要额外的机制来确保消息不丢失。

    在这里插入图片描述
    RabbitMQ通过以下方法解决该问题:channel进程在收到生产者消息后,将消息发送给所有的队列进程,队列进程缓存从channel收到的消息(amqqueue缓存队列)。当队列进程从gm收到该消息后,将消息入BQ队列,并删除缓存消息。当master挂掉时,新的master通过对比gm缓存和amqqueue缓存,获取上述channel已发出、原master未通过gm转发的消息。新master此时会将未确认(consume ack)的消费消息退回BQ队列(requeue),然后将上面获取的原master未转发消息入BQ队列(同时在gm广播进行同步)。

    对于消费消息,channel只用与master通信,master将消费信息在集群中同步。当master挂掉时,新提升的master将未确认的消费消息退回BQ队列(由于新master不知道消费者是否ack,所以只能将消息退回队列);已确认的消费消息由新master继续在集群中同步,不用退回队列。

    该机制确保了RabbitMQ的可靠交付(at-least-once delivery)。

    该部分代码在slave中:https://github.com/rabbitmq/rabbitmq-server/blob/stable/src/rabbit_mirror_queue_slave.erl#L551

    展开全文
  • GSXZGLJ系统WAS集群架构设计说明

    千次阅读 2014-03-15 19:00:47
     前端负载分发基于硬件F5以NAT地址转发路由机制在分发Web请求,的确可以很好的降低Web负载,但由于系统未采用IHS作为独立的Web容器,以致WAS同时处理Web容器、J2EE容器、Servlet容器、缓存服务器等多种角色于一身,...

     

     

    一、 系统容错及可靠性设计

     

    现有的架构设计存在以下问题:

    1.  前端负载分发基于硬件F5NAT地址转发路由机制在分发Web请求,的确可以很好的降低Web负载,但由于系统未采用IHS作为独立的Web容器,以致WAS同时处理Web容器、J2EE容器、Servlet容器、缓存服务器等多种角色于一身,虽然便于管理,但WAS的容错性和可靠性却很差,但某一容器出现J2EE常见的GC垃圾回收失败时,会导致内存溢出,产生宕机风险。而面对这样的宕机产生,管理员除了重启服务无法保证业务连续性。

    2.  虽然多台WAS看似以集群形式存在,但实际上并不能起到水平扩展的作用,这是一个似是而非的集群,并非IBM推荐的系统集成架构,这是一个危险且浪费资源的设计。

    3.  会话无法被复制,不能支持页面会话级故障转移,这是大集中式的业务系统所不允许的。

    4.  系统容错和可靠性设计对于应用程序的部署也有对应的讲究,否则无法达到高可靠性的要求。

     

    我的设计主要表现在可靠性设计和系统容错上,设计的目的就是解决以上这4个问题。最终达到如下效果:

    1.  水平垂直集群设计,解决横向扩展负载均衡和纵向故障转移的设计要求,达到会话级别的故障转移。

    2.  基于session DB设计,让会话和web请求具备可追溯的映射关联关系,这是一切安全性可审计的前提。

    3.  独立设计的Web容器集群、缓存集群、JSP/servlet集群、EJB集群,缩小了故障产生的影响面,可以有把握有效的解决问题。

     

    二、设计说明

     

    IBM WebSphere应用服务器具有容错和错误恢复能力的保障,主要是通过以下途径来实现容错和故障恢复。

    1.  多层的集群技术

    2.  内置HA管理器

    3.  Nanny(保姆)守护服务 

    4.  支持Session级故障恢复

    5.  备份和恢复应用服务器的功能,以支持人为操作错误的容错能力

     

    下面从这几个方面做详细说明

    1多层的集群技术

    IBM WebSphere Application Server完全提供端到端的多层的集群。包括Web服务器层、应用服务器(Web容器层和EJB容器层)的群集功能,在每个层次上实现不同组件的群集服务。

    1.1 Web服务器层的集群

    IBM WebSphere Application Server内置Edge Component组件,其中所含部件Network Dispatcher能够支持不同操作系统下的WEB服务器级的负载平衡,如下图所示

    Web服务器级的负载平衡

    1.2 应用服务器层的集群

    为了实现应用的扩展能力和保证应用的高可用性,WebSphere应用服务器采用多服务器群集的方式来提供应用的分布式部署、负载均衡、组件级的失效即时恢复(Fail Over)。在N层应用架构下,应用服务器群集可以为每一层逻辑的应用提供良好的扩展性和可用性,可提供高效率的负载均衡算法,提供一个可伸缩的负载平衡方案。在应用服务器层面,支持群集的部署,并且要具有很好的灵活性。可以为Servlet会话(Session)为用户提供透明的状态备份机制和快速的失效切换,同时服务器群集的管理简单方便,使关键应用具有高性能和高可用性。

    WebSphere应用完全提供了独立于硬件系统的集群功能。在WebSphere应用服务器中,提供了两种方式的Cluster:垂直的方式和水平的方式。它们分别是为了适应不同的应用环境而设置的,垂直的Cluster允许在一台机器上实现动态负载均衡;而水平的Cluster允许在多台机器上实现动态的负载均衡。二者可以有机的协调工作,为复杂环境的应用实现负载均衡提供了强有力的保证。

    单机环境下的应用级动态的负载平衡:

     

     

    多机环境下的应用级动态的负载平衡:

    水平集群和垂直集群的综合负载均衡解决方案:

     

    IBM WebSphere Application Server支持当硬件平台或操作系统不是同一产品时的异构Cluster技术。在WebSphere中提供了简单的菜单设置方法来实现异构的Cluster技术。从用户来的角度来看,他根本不用关心怎样在一个平台上实现Cluster技术,只需要通过简单的菜单,按照App Server-Server Group-Cloning的简单流程就可以复制出自己想要的异构集群环境,轻松实现应用的扩展。

    2内置HA管理器

    内置的HA管理器,对关键服务进行监控,如负载路由(WLM, JMS消息,事务管理器等,自动侦测出现的问题。为关键业务的JAVA应用提供24×的运行保障。使DM不再成为一个单点故障。

    基于HA管理器的统一集群框架提高了应用服务器的高可靠性。自动安装应用模式,保证了快速、简单的管理复杂动态的IT环境。

    3Nanny(保姆)守护服务

    IBM WebSphere Application Server完全保证用户的程序在一个高可靠的环境内运行。 WebSphere使用的是一种Nanny 服务的体系结构,使用该结构,所有的Application Server (应用服务器将由一个Administration Server(管理服务器)来监视管理,一旦由于一个特殊的原因(例如进程被杀掉)导致应用服务器停止,管理服务器将自动重新启动该应用服务器;同样,Administration Server (管理服务器由一个"Nanny(保姆)守护服务,该"保姆"服务一旦检测到管理服务器停止也将自动重新启动它。这样WebSphere从体系结构上就最大限度地保证服务器程序的可靠稳定运行。另外,就象我们在前面多次提到多的,WebSphere支持两种方式的复制技术:水平克隆和垂直克隆,它们都能保证应用系统的可靠性。

    4支持Session级故障恢复

    IBM WebSphere Application Server会话管理负责管理 HTTP 会话,提供会话数据的存储器,分配会话标识,并通过使用 cookie 或 URL 重写技巧来跟踪与每个客户机请求相关的会话标识。会话管理可以以多种方法存储会话相关的信息:

    应用程序服务器内存(缺省值)。此信息无法与其它应用程序服务器共享。 

    在数据库中。此存储选项称为数据库持久会话。 

    在另一个 WebSphere Application Server 实例中。此存储选项称为内存到内存会话复制。 

    IBM WebSphere 应用服务器采用内存到内存复制和数据库持久的方式作为分布式会话引用。当应用程序服务器接收与当前内存中不存在的会话标识相关联的请求时,它可以通过访问外部存储(数据库或内存到内存)获取必需的会话状态,从而支持Session级故障恢复

    5备份和恢复应用服务器的功能

    WebSpher应用服务器提供备份和恢复应用服务器的功能(备份和恢复命令)。人为操作错误后,可使用已经备份的文件来恢复应用服务器的环境。

    另外,集成到WebSphere 应用服务器管理控制台中的TPV可以动态监控各种性能参数,并用图表的方式显示,能快速发现和定位性能问题。

    6总结

    IBM WebSphere Application Server可以通过透明的集群技术为所有的服务器(包括异构的平台)实现智能的工作负载均衡,保证整个应用系统在即使某台服务器出现故障的情况下仍然能够保证事务处理能够顺利地进行下去;内置HA管理器对关键性服务进行监控,保证了管理集群的组件DM的高可用性;备份集群的技术保证了用户的关键业务的不间断运行;会话故障恢复机制,保证了故障转移时用户会话数据的恢复;应用服务器提供的备份恢复功能,加强了人为操作错误的容错,保证了关键业务24x7x365的高可用性。

    三、完成设计后的应用程序部署及维护说明

    环境说明

    单机环境(Base/stand alone environment):只有1个应用程序服务器进程的环境,安装的产品是WAS Base。

    网络部署环境(Network Deployment environment):多个WAS进程、多结点的环境,由Deployment Manager统一管理,组成了一个Cell(类似于Windows中Domain的概念),安装的产品是WAS ND。也称为ND环境、Cell环境、集群环境等等。下面为了叙述和理解方便,简称为集群环境,注意,更严谨的叫法应该称为ND环境或者Cell环境。

    以前为单机环境,现在扩展为集群环境。

    当前环境举例为Linux系统,M1机器上安装了WAS5 ND, M2机器上安装了WAS5 Base,并已配置成cell环境。edge1和edge2机器上安装并配置了edge server。

    集群系统拓扑图 vs.单机系统拓扑图

    单机环境和集群环境在系统拓扑、管理方式上都有变化。下面的系统架构图是指客户发出请求访问系统时,涉及到的系统组件。WAS进程拓扑图则是针对不同系统架构中的WAS进程,给出的详细的WAS进程描述图。

    单机系统

     

    集群系统

     

     

    上图虚线分割开的两部分是两台真实的物理机器。其中,M1机器上有进程Node agent、server1、Myc1。M2机器上有进程Depolyment Manager(以后简称dmgr)、Node agent、server1、Myc2。Myc1和Myc2组成了一个集群Mycluster。

    从功能上,可以把这些WAS进程分为3类:

    DMGR:管理整个cell环境,对cell中每个WAS进程配置的修改都需要通过dmgr进行,每个cell环境只有1个。

    node agent:可以理解为中间通讯/监控代理,每个结点有一个。

    应用程序服务器进程:我们把server1/ Myc*这样的进程称为应用程序服务器进程,应用是运行在这些应用程序服务器进程上的。在客户访问请求时,这些进程中必须至少有1个是active的。

    启动/停止系统的变化

    单机系统

    M1:

    cd /opt/WebSphere/AppServer/bin

    启动:>./startServer.sh server1

    停止:>./stopServer.sh server1

    集群系统

    一般来说如果启动/停止整个系统需要启动/停止dmgrnode agent、应用程序服务器进程server1Myc1、Myc2)。在我们的配置中,如果修改了应用的配置或某个应用程序服务器进程的配置,一般只需要启动/停止集群,或者启停相应的的应用程序服务器进程,server1进程一般都是停止的(因为我们没有在server1上面部署应用,应用都部署在集群上了)。

    请注意下面的命令都分别是在哪台机器上发出的。

    集群系统的启动停止分为几种类型,它们一般都可以通过管理控制台或者命令行的方式来完成:

    启动/停止Dmgr:

    M2:

    cd /opt/WebSphere/DeploymentManager/bin

    启动:>./startManager.sh

    停止:>./stopManager.sh

     

    启动/停止node agent:

    如果需要停止哪台服务器上的node agent,就到哪台服务器上去发命令:

    cd /opt/WebSphere/AppServer/bin

    启动:>./startNode.sh

    停止:>./stopNode.sh

     

    启动/停止集群:

    有3种方法:

    第一种方法:到管理控制台(后面会讲到怎么进集群系统的控制台),找到集群,如图5

     

     

     

    第二种方法:到管理控制台(后面会讲到怎么进集群系统的控制台),通过管理控制台直接控制启停集群成员。如图6

     

     

     

    第三种方法:到集群成员(如Myc1,或者Myc2)所在机器上,stopServer.sh 集群成员名字。以启停M1上的Myc1为例:

    cd /opt/WebSphere/AppServer/bin

    启动:>./startServer.sh Myc1

    停止>./stopServer.sh Myc1

     

    启动/停止单个应用程序服务器进程:

    方法与前面启停集群成员相同,有两种方法:

    第一种方法:到管理控制台(后面会讲到怎么进集群系统的控制台),通过管理控制台直接控制启停。如图6

     

    第二种方法:到应用程序服务器进程(如server1Myc1,或者Myc2)所在机器上,startServer.sh 应用程序服务器进程。以启停M1上的Myc1为例:

    cd /opt/WebSphere/AppServer/bin

    启动:>./startServer.sh Myc1

    停止>./stopServer.sh Myc1

     

    集群系统中web serveredge server的启停

    1.  启停Web服务器

    M1或者M2机器上,

    cd /opt/IBMHttpServer/bin

    ./apachectl start

    ./apchectl stop

     

    2.  启停edge server

    edge1或者edge2机器上,

    dsserver

    lbadmin  //启动图形配置界面,需要查看edge server运行状况或者更改edge server配置时用

    不过,在安装了新应用、修改了应用服务器配置时,大多数情况下不需要重启web服务器或者edge server

     

    管理系统的变化

    单机系统

    http://M1:9090/admin

    集群系统

    http://M2:9091/admin

     

    配置JDBC资源的变化

    单机系统

    资源配置只局限于单个WAS进程(server1)内

    集群系统

    需要考虑资源的scope。资源的scope分为3级:Cell, Node, Server。如果不同scope的资源有重名,运行时取local的资源。因此,如果有同名的资源,则Server级别的资源会覆盖Node级别的,Node的会覆盖cell的。一般在集群下,为简便,可把资源的scope配置成cell级别(可以理解为全局的)。如图7

     

     

    部署应用的变化

    单机系统

    到管理控制台,安装应用 -> next -> next

    集群系统

    分为如下几步进行:

    1. 到管理控制台,安装应用-> next  ->目标映射到服务器->

    “映射模块到目标服务器”切记选择应用部署到“Mycluster”,而不是server1。最后应该看到应用右面的服务器栏中只出现了Mycluster,如图8,图9:

     

     

     

     

     

     

    2.保存时,记得选择“与结点同步更改”,如图10:

     

     

     

    3.选择“环境 ->更新Web服务器插件”,如图11

     

     

     

    4.M2机器上的

    /opt/WebSphere/DeploymentManager/config/cells/plugin-cfg.xml拷贝到M1/opt目录下

    M1机器上,发出以下命令:

    scp M2: /opt/WebSphere/DeploymentManager/config/cells/plugin-cfg.xml /opt

     

    5.以前在单机环境下启动server1之前,某些应用需要执行一段脚本,对应集群环境下,在启动单个的应用服务器进程(如Myc1Myc2)之前,也执行该段脚本即可。例如

    cd /opt/WebSphere/AppServer/bin

    source /home/oracle/.bash_profile_back

    ./startServer.sh Myc1

     

    系统日志位置的变化

    单机系统

    M1下,

    /opt/WebSphere/AppServer/logs/server1目录

    集群系统

    希望看到进程在哪台机器,就到哪台机器下去看。

    如果是Myc1,到M1机器的

    /opt/WebSphere/AppServer/logs/Myc1目录

    如果是Myc2, M2机器的

    /opt/WebSphere/AppServer/logs/Myc2目录;

    如果是dmgrM2机器的

    /opt/WebSphere/DeploymentManager/logs/dmgr目录

     

    正常运行时,通常情况下组件的状态

    active:

    edge1edge2机器上的edge server

    M1M2机器上的web server

    M1M2机器上的Myc*进程。

     

    可以active也可以不active

    node agent,

    dmgr

    但是在部署应用、修改WAS进程的配置时,node agentdmgr必须active

     

    active

    M1M2机器上的server1进程。因为我们没把应用部署在server1进程上,所以如果开着server1是白白浪费资源。

     

    查看各个进程的状态

    web serverps ef |grep httpd

    WAS进程:./serverStatus.sh可以看状态

    展开全文
  • kafka集群原理介绍

    千次阅读 2017-08-14 09:58:20
    kafka集群原理介绍@(KAFKA)[kafka, 大数据]kafka集群原理介绍 一基础理论 二配置文件 一java调优 二参数说明 三错误处理 四zookeeper中的内容1brokers中的信息 2consumer的信息 offset中的这个值表示什么意思不是...

    kafka集群原理介绍

    @(KAFKA)[kafka, 大数据]

    (一)基础理论

    1、相关资料
    官方资料,非常详细:
    http://kafka.apache.org/documentation.html#quickstart

    以下部分内容来源于此文档。

    2、kafka是什么?

    (1)Kafka is a distributed, partitioned, replicated commit log service. It provides the functionality of a messaging system, but with a unique design.

    Kafka是一个 分布式的、可分区的、可复制的消息系统。它提供了普通消息系统的功能,但具有自己独特的设计。

    (2)可以简单的理解为:kafka是一个日志集群,各种各样的服务器将它们自身的日志发送到集群中进行统一汇总和存储,然后其它机器从集群中拉取消息进行分析处理,如ELT、数据挖掘等。

    (3)kafka使用scala语言实现,提供了JAVA API,同时对多种语言都提供了支持。

    3、几个关键术语

    topic: Kafka将消息以topic为单位进行归纳。

    producer: 将向Kafka topic发布消息的程序称为producers.

    consumer: 将预订topics并消费消息的程序称为consumer.

    broker: Kafka以集群的方式运行,可以由一个或多个服务组成,每个服务叫做一个broker.

    4、分区与副本

    (1)一个topic是对一组消息的归纳。对每个topic,Kafka 对它的日志进行了分区。

    (2)一般而言,一个topic会有多个分区,每个分区会有多个副本。

    分区是分了将一个topic分到多个地方存储,提高并行处理的能力。副本是为了容错,保证数据不丢失。

    (3)对于每一个分区,都会选取一个leader,这个分区的所有读取都在这个leader中进行,而其它副本会同步leader中的数据,且只做备份。

    即leader只是针对一个分区而言,而非整个集群。一个服务器对于某个分区是leader,对于其它分区可能是follower。

    (4) Producer将消息发布到它指定的topic中,并负责决定发布到哪个分区。通常简单的由负载均衡机制随机选择分区,但也可以通过特定的分区函数选择分区。

    (5)发布消息通常有两种模式:队列模式(queuing)和发布-订阅模式(publish-subscribe)。队列模式中,consumers可以同时从服务端读取消息,每个消息只被其中一个consumer读到;发布-订阅模式中消息被广播到所有的consumer中。

    Consumers可以加入一个consumer 组,共同竞争一个topic,topic中的消息将被分发到组中的一个成员中。同一组中的consumer可以在不同的程序中,也可以在不同的机器上。如果所有的consumer都在一个组中,这就成为了传统的队列模式,在各consumer中实现负载均衡。

    如果所有的consumer都不在不同的组中,这就成为了发布-订阅模式,所有的消息都被分发到所有的consumer中。

    更常见的是,每个topic都有若干数量的consumer组,每个组都是一个逻辑上的“订阅者”,为了容错和更好的稳定性,每个组由若干consumer组成。这其实就是一个发布-订阅模式,只不过订阅者是个组而不是单个consumer。

    (6)有序性

    相比传统的消息系统,Kafka可以很好的保证有序性。

    传统的队列在服务器上保存有序的消息,如果多个consumers同时从这个服务器消费消息,服务器就会以消息存储的顺序向consumer分 发消息。虽然服务器按顺序发布消息,但是消息是被异步的分发到各consumer上,所以当消息到达时可能已经失去了原来的顺序,这意味着并发消费将导致 顺序错乱。为了避免故障,这样的消息系统通常使用“专用consumer”的概念,其实就是只允许一个消费者消费消息,当然这就意味着失去了并发性。

    在这方面Kafka做的更好,通过分区的概念,Kafka可以在多个consumer组并发的情况下提供较好的有序性和负载均衡。将每个分区分 只分发给一个consumer组,这样一个分区就只被这个组的一个consumer消费,就可以顺序的消费这个分区的消息。因为有多个分区,依然可以在多 个consumer组之间进行负载均衡。注意consumer组的数量不能多于分区的数量,也就是有多少分区就允许多少并发消费。

    Kafka只能保证一个分区之内消息的有序性,在不同的分区之间是不可以的,这已经可以满足大部分应用的需求。如果需要topic中所有消息的有序性,那就只能让这个topic只有一个分区,当然也就只有一个consumer组消费它。

    5、数据持久化(本部分内容直接翻译自官方文档)

    不要畏惧文件系统!

    Kafka大量依赖文件系统去存储和缓存消息。对于硬盘有个传统的观念是硬盘总是很慢,这使很多人怀疑基于文件系统的架构能否提供优异的性能。实际上硬盘的快慢完全取决于使用它的方式。设计良好的硬盘架构可以和内存一样快。

    在6块7200转的SATA RAID-5磁盘阵列的线性写速度差不多是600MB/s,但是随即写的速度却是100k/s,差了差不多6000倍。现代的操作系统都对次做了大量的优化,使用了 read-ahead 和 write-behind的技巧,读取的时候成块的预读取数据,写的时候将各种微小琐碎的逻辑写入组织合并成一次较大的物理写入。对此的深入讨论可以查看这里,它们发现线性的访问磁盘,很多时候比随机的内存访问快得多。

    为了提高性能,现代操作系统往往使用内存作为磁盘的缓存,现代操作系统乐于把所有空闲内存用作磁盘缓存,虽然这可能在缓存回收和重新分配时牺牲一些性能。所有的磁盘读写操作都会经过这个缓存,这不太可能被绕开除非直接使用I/O。所以虽然每个程序都在自己的线程里只缓存了一份数据,但在操作系统的缓存里还有一份,这等于存了两份数据。

    另外再来讨论一下JVM,以下两个事实是众所周知的:

    •Java对象占用空间是非常大的,差不多是要存储的数据的两倍甚至更高。

    •随着堆中数据量的增加,垃圾回收回变的越来越困难。

    基于以上分析,如果把数据缓存在内存里,因为需要存储两份,不得不使用两倍的内存空间,Kafka基于JVM,又不得不将空间再次加倍,再加上要避免GC带来的性能影响,在一个32G内存的机器上,不得不使用到28-30G的内存空间。并且当系统重启的时候,又必须要将数据刷到内存中( 10GB 内存差不多要用10分钟),就算使用冷刷新(不是一次性刷进内存,而是在使用数据的时候没有就刷到内存)也会导致最初的时候新能非常慢。但是使用文件系统,即使系统重启了,也不需要刷新数据。使用文件系统也简化了维护数据一致性的逻辑。

    所以与传统的将数据缓存在内存中然后刷到硬盘的设计不同,Kafka直接将数据写到了文件系统的日志中。

    常量时间的操作效率

    在大多数的消息系统中,数据持久化的机制往往是为每个cosumer提供一个B树或者其他的随机读写的数据结构。B树当然是很棒的,但是也带了一些代价:比如B树的复杂度是O(log N),O(log N)通常被认为就是常量复杂度了,但对于硬盘操作来说并非如此。磁盘进行一次搜索需要10ms,每个硬盘在同一时间只能进行一次搜索,这样并发处理就成了问题。虽然存储系统使用缓存进行了大量优化,但是对于树结构的性能的观察结果却表明,它的性能往往随着数据的增长而线性下降,数据增长一倍,速度就会降低一倍。

    直观的讲,对于主要用于日志处理的消息系统,数据的持久化可以简单的通过将数据追加到文件中实现,读的时候从文件中读就好了。这样做的好处是读和写都是 O(1) 的,并且读操作不会阻塞写操作和其他操作。这样带来的性能优势是很明显的,因为性能和数据的大小没有关系了。

    既然可以使用几乎没有容量限制(相对于内存来说)的硬盘空间建立消息系统,就可以在没有性能损失的情况下提供一些一般消息系统不具备的特性。比如,一般的消息系统都是在消息被消费后立即删除,Kafka却可以将消息保存一段时间(比如一星期),这给consumer提供了很好的机动性和灵活性。

    6、事务性

    之前讨论了consumer和producer是怎么工作的,现在来讨论一下数据传输方面。数据传输的事务定义通常有以下三种级别:

    最多一次: 消息不会被重复发送,最多被传输一次,但也有可能一次不传输。

    最少一次: 消息不会被漏发送,最少被传输一次,但也有可能被重复传输.

    精确的一次(Exactly once): 不会漏传输也不会重复传输,每个消息都传输被一次而且仅仅被传输一次,这是大家所期望的。

    大多数消息系统声称可以做到“精确的一次”,但是仔细阅读它们的的文档可以看到里面存在误导,比如没有说明当consumer或producer失败时怎么样,或者当有多个consumer并行时怎么样,或写入硬盘的数据丢失时又会怎么样。kafka的做法要更先进一些。当发布消息时,Kafka有一个“committed”的概念,一旦消息被提交了,只要消息被写入的分区的所在的副本broker是活动的,数据就不会丢失。关于副本的活动的概念,下节文档会讨论。现在假设broker是不会down的。

    如果producer发布消息时发生了网络错误,但又不确定实在提交之前发生的还是提交之后发生的,这种情况虽然不常见,但是必须考虑进去,现在Kafka版本还没有解决这个问题,将来的版本正在努力尝试解决。

    并不是所有的情况都需要“精确的一次”这样高的级别,Kafka允许producer灵活的指定级别。比如producer可以指定必须等待消息被提交的通知,或者完全的异步发送消息而不等待任何通知,或者仅仅等待leader声明它拿到了消息(followers没有必要)。

    现在从consumer的方面考虑这个问题,所有的副本都有相同的日志文件和相同的offset,consumer维护自己消费的消息的offset,如果consumer不会崩溃当然可以在内存中保存这个值,当然谁也不能保证这点。如果consumer崩溃了,会有另外一个consumer接着消费消息,它需要从一个合适的offset继续处理。这种情况下可以有以下选择:

    consumer可以先读取消息,然后将offset写入日志文件中,然后再处理消息。这存在一种可能就是在存储offset后还没处理消息就crash了,新的consumer继续从这个offset处理,那么就会有些消息永远不会被处理,这就是上面说的“最多一次”。

    consumer可以先读取消息,处理消息,最后记录offset,当然如果在记录offset之前就crash了,新的consumer会重复的消费一些消息,这就是上面说的“最少一次”。

    “精确一次”可以通过将提交分为两个阶段来解决:保存了offset后提交一次,消息处理成功之后再提交一次。但是还有个更简单的做法:将消息的offset和消息被处理后的结果保存在一起。比如用Hadoop ETL处理消息时,将处理后的结果和offset同时保存在HDFS中,这样就能保证消息和offser同时被处理了

    7、关于性能优化

    Kafka在提高效率方面做了很大努力。Kafka的一个主要使用场景是处理网站活动日志,吞吐量是非常大的,每个页面都会产生好多次写操作。读方面,假设每个消息只被消费一次,读的量的也是很大的,Kafka也尽量使读的操作更轻量化。

    我们之前讨论了磁盘的性能问题,线性读写的情况下影响磁盘性能问题大约有两个方面:太多的琐碎的I/O操作和太多的字节拷贝。I/O问题发生在客户端和服务端之间,也发生在服务端内部的持久化的操作中。
    消息集(message set)
    为了避免这些问题,Kafka建立了“消息集(message set)”的概念,将消息组织到一起,作为处理的单位。以消息集为单位处理消息,比以单个的消息为单位处理,会提升不少性能。Producer把消息集一块发送给服务端,而不是一条条的发送;服务端把消息集一次性的追加到日志文件中,这样减少了琐碎的I/O操作。consumer也可以一次性的请求一个消息集。
    另外一个性能优化是在字节拷贝方面。在低负载的情况下这不是问题,但是在高负载的情况下它的影响还是很大的。为了避免这个问题,Kafka使用了标准的二进制消息格式,这个格式可以在producer,broker和producer之间共享而无需做任何改动。
    zero copy
    Broker维护的消息日志仅仅是一些目录文件,消息集以固定队的格式写入到日志文件中,这个格式producer和consumer是共享的,这使得Kafka可以一个很重要的点进行优化:消息在网络上的传递。现代的unix操作系统提供了高性能的将数据从页面缓存发送到socket的系统函数,在linux中,这个函数是sendfile.
    为了更好的理解sendfile的好处,我们先来看下一般将数据从文件发送到socket的数据流向:

    操作系统把数据从文件拷贝内核中的页缓存中
    应用程序从页缓存从把数据拷贝自己的内存缓存中
    应用程序将数据写入到内核中socket缓存中
    操作系统把数据从socket缓存中拷贝到网卡接口缓存,从这里发送到网络上。

    这显然是低效率的,有4次拷贝和2次系统调用。Sendfile通过直接将数据从页面缓存发送网卡接口缓存,避免了重复拷贝,大大的优化了性能。
    在一个多consumers的场景里,数据仅仅被拷贝到页面缓存一次而不是每次消费消息的时候都重复的进行拷贝。这使得消息以近乎网络带宽的速率发送出去。这样在磁盘层面你几乎看不到任何的读操作,因为数据都是从页面缓存中直接发送到网络上去了。

    8、数据压缩
    很多时候,性能的瓶颈并非CPU或者硬盘而是网络带宽,对于需要在数据中心之间传送大量数据的应用更是如此。当然用户可以在没有Kafka支持的情况下各自压缩自己的消息,但是这将导致较低的压缩率,因为相比于将消息单独压缩,将大量文件压缩在一起才能起到最好的压缩效果。
    Kafka采用了端到端的压缩:因为有“消息集”的概念,客户端的消息可以一起被压缩后送到服务端,并以压缩后的格式写入日志文件,以压缩的格式发送到consumer,消息从producer发出到consumer拿到都被是压缩的,只有在consumer使用的时候才被解压缩,所以叫做“端到端的压缩”。
    Kafka支持GZIP和Snappy压缩协议。

    9、producer和consumer

    Kafka Producer

    消息发送

    producer直接将数据发送到broker的leader(主节点),不需要在多个节点进行分发。为了帮助producer做到这点,所有的Kafka节点都可以及时的告知:哪些节点是活动的,目标topic目标分区的leader在哪。这样producer就可以直接将消息发送到目的地了。

    客户端控制消息将被分发到哪个分区。可以通过负载均衡随机的选择,或者使用分区函数。Kafka允许用户实现分区函数,指定分区的key,将消息hash到不同的分区上(当然有需要的话,也可以覆盖这个分区函数自己实现逻辑).比如如果你指定的key是user id,那么同一个用户发送的消息都被发送到同一个分区上。经过分区之后,consumer就可以有目的的消费某个分区的消息。

    异步发送

    批量发送可以很有效的提高发送效率。Kafka producer的异步发送模式允许进行批量发送,先将消息缓存在内存中,然后一次请求批量发送出去。这个策略可以配置的,比如可以指定缓存的消息达到某个量的时候就发出去,或者缓存了固定的时间后就发送出去(比如100条消息就发送,或者每5秒发送一次)。这种策略将大大减少服务端的I/O次数。

    既然缓存是在producer端进行的,那么当producer崩溃时,这些消息就会丢失。Kafka0.8.1的异步发送模式还不支持回调,就不能在发送出错时进行处理。Kafka 0.9可能会增加这样的回调函数。见Proposed Producer API.

    Kafka Consumer

    Kafa consumer消费消息时,向broker发出”fetch”请求去消费特定分区的消息。consumer指定消息在日志中的偏移量(offset),就可以消费从这个位置开始的消息。customer拥有了offset的控制权,可以向后回滚去重新消费之前的消息,这是很有意义的。

    10、推还是拉?

    Kafka最初考虑的问题是,customer应该从brokes拉取消息还是brokers将消息推送到consumer,也就是pull还push。在这方面,Kafka遵循了一种大部分消息系统共同的传统的设计:producer将消息推送到broker,consumer从broker拉取消息。
    一些消息系统比如Scribe和Apache Flume采用了push模式,将消息推送到下游的consumer。这样做有好处也有坏处:由broker决定消息推送的速率,对于不同消费速率的consumer就不太好处理了。消息系统都致力于让consumer以最大的速率最快速的消费消息,但不幸的是,push模式下,当broker推送的速率远大于consumer消费的速率时,consumer恐怕就要崩溃了。最终Kafka还是选取了传统的pull模式。
    Pull模式的另外一个好处是consumer可以自主决定是否批量的从broker拉取数据。Push模式必须在不知道下游consumer消费能力和消费策略的情况下决定是立即推送每条消息还是缓存之后批量推送。如果为了避免consumer崩溃而采用较低的推送速率,将可能导致一次只推送较少的消息而造成浪费。Pull模式下,consumer就可以根据自己的消费能力去决定这些策略。
    Pull有个缺点是,如果broker没有可供消费的消息,将导致consumer不断在循环中轮询,直到新消息到t达。为了避免这点,Kafka有个参数可以让consumer阻塞知道新消息到达(当然也可以阻塞知道消息的数量达到某个特定的量这样就可以批量发送)。

    11、消费状态跟踪

    对消费消息状态的记录也是很重要的。
    大部分消息系统在broker端的维护消息被消费的记录:一个消息被分发到consumer后broker就马上进行标记或者等待customer的通知后进行标记。这样也可以在消息在消费后立马就删除以减少空间占用。
    但是这样会不会有什么问题呢?如果一条消息发送出去之后就立即被标记为消费过的,一旦consumer处理消息时失败了(比如程序崩溃)消息就丢失了。为了解决这个问题,很多消息系统提供了另外一个个功能:当消息被发送出去之后仅仅被标记为已发送状态,当接到consumer已经消费成功的通知后才标记为已被消费的状态。这虽然解决了消息丢失的问题,但产生了新问题,首先如果consumer处理消息成功了但是向broker发送响应时失败了,这条消息将被消费两次。第二个问题时,broker必须维护每条消息的状态,并且每次都要先锁住消息然后更改状态然后释放锁。这样麻烦又来了,且不说要维护大量的状态数据,比如如果消息发送出去但没有收到消费成功的通知,这条消息将一直处于被锁定的状态,
    Kafka采用了不同的策略。Topic被分成了若干分区,每个分区在同一时间只被一个consumer消费。这意味着每个分区被消费的消息在日志中的位置仅仅是一个简单的整数:offset。这样就很容易标记每个分区消费状态就很容易了,仅仅需要一个整数而已。这样消费状态的跟踪就很简单了。
    这带来了另外一个好处:consumer可以把offset调成一个较老的值,去重新消费老的消息。这对传统的消息系统来说看起来有些不可思议,但确实是非常有用的,谁规定了一条消息只能被消费一次呢?consumer发现解析数据的程序有bug,在修改bug后再来解析一次消息,看起来是很合理的额呀!

    12、离线处理消息

    高级的数据持久化允许consumer每个隔一段时间批量的将数据加载到线下系统中比如Hadoop或者数据仓库。这种情况下,Hadoop可以将加载任务分拆,拆成每个broker或每个topic或每个分区一个加载任务。Hadoop具有任务管理功能,当一个任务失败了就可以重启而不用担心数据被重新加载,只要从上次加载的位置继续加载消息就可以了。

    13、副本与主从关系(本部分直接翻译自官方文档)

    Kafka允许topic的分区拥有若干副本,这个数量是可以配置的,你可以为每个topci配置副本的数量。Kafka会自动在每个个副本上备份数据,所以当一个节点down掉时数据依然是可用的。

    Kafka的副本功能不是必须的,你可以配置只有一个副本,这样其实就相当于只有一份数据。

    创建副本的单位是topic的分区,每个分区都有一个leader和零或多个followers.所有的读写操作都由leader处理,一般分区的数量都比broker的数量多的多,各分区的leader均匀的分布在brokers中。所有的followers都复制leader的日志,日志中的消息和顺序都和leader中的一致。flowers向普通的consumer那样从leader那里拉取消息并保存在自己的日志文件中。
    许多分布式的消息系统自动的处理失败的请求,它们对一个节点是否
    着(alive)”有着清晰的定义。Kafka判断一个节点是否活着有两个条件:

    节点必须可以维护和ZooKeeper的连接,Zookeeper通过心跳机制检查每个节点的连接。
    如果节点是个follower,他必须能及时的同步leader的写操作,延时不能太久。
    符合以上条件的节点准确的说应该是“同步中的(in sync)”,而不是模糊的说是“活着的”或是“失败的”。Leader会追踪所有“同步中”的节点,一旦一个down掉了,或是卡住了,或是延时太久,leader就会把它移除。至于延时多久算是“太久”,是由参数replica.lag.max.messages决定的,怎样算是卡住了,怎是由参数replica.lag.time.max.ms决定的。
    只有当消息被所有的副本加入到日志中时,才算是“committed”,只有committed的消息才会发送给consumer,这样就不用担心一旦leader down掉了消息会丢失。Producer也可以选择是否等待消息被提交的通知,这个是由参数request.required.acks决定的。

    Kafka保证只要有一个“同步中”的节点,“committed”的消息就不会丢失。

    14、Leader的选择

    Kafka的核心是日志文件,日志文件在集群中的同步是分布式数据系统最基础的要素。

    如果leaders永远不会down的话我们就不需要followers了!一旦leader down掉了,需要在followers中选择一个新的leader.但是followers本身有可能延时太久或者crash,所以必须选择高质量的follower作为leader.必须保证,一旦一个消息被提交了,但是leader down掉了,新选出的leader必须可以提供这条消息。大部分的分布式系统采用了多数投票法则选择新的leader,对于多数投票法则,就是根据所有副本节点的状况动态的选择最适合的作为leader.Kafka并不是使用这种方法。

    Kafaka动态维护了一个同步状态的副本的集合(a set of in-sync replicas),简称ISR,在这个集合中的节点都是和leader保持高度一致的,任何一条消息必须被这个集合中的每个节点读取并追加到日志中了,才回通知外部这个消息已经被提交了。因此这个集合中的任何一个节点随时都可以被选为leader.ISR在ZooKeeper中维护。ISR中有f+1个节点,就可以允许在f个节点down掉的情况下不会丢失消息并正常提供服。ISR的成员是动态的,如果一个节点被淘汰了,当它重新达到“同步中”的状态时,他可以重新加入ISR.这种leader的选择方式是非常快速的,适合kafka的应用场景。

    一个邪恶的想法:如果所有节点都down掉了怎么办?Kafka对于数据不会丢失的保证,是基于至少一个节点是存活的,一旦所有节点都down了,这个就不能保证了。
    实际应用中,当所有的副本都down掉时,必须及时作出反应。可以有以下两种选择:

    等待ISR中的任何一个节点恢复并担任leader。
    选择所有节点中(不只是ISR)第一个恢复的节点作为leader.
    这是一个在可用性和连续性之间的权衡。如果等待ISR中的节点恢复,一旦ISR中的节点起不起来或者数据都是了,那集群就永远恢复不了了。如果等待ISR意外的节点恢复,这个节点的数据就会被作为线上数据,有可能和真实的数据有所出入,因为有些数据它可能还没同步到。Kafka目前选择了第二种策略,在未来的版本中将使这个策略的选择可配置,可以根据场景灵活的选择。

    这种窘境不只Kafka会遇到,几乎所有的分布式数据系统都会遇到。

    15、副本管理

    以上仅仅以一个topic一个分区为例子进行了讨论,但实际上一个Kafka将会管理成千上万的topic分区.Kafka尽量的使所有分区均匀的分布到集群所有的节点上而不是集中在某些节点上,另外主从关系也尽量均衡这样每个几点都会担任一定比例的分区的leader.

    优化leader的选择过程也是很重要的,它决定了系统发生故障时的空窗期有多久。Kafka选择一个节点作为“controller”,当发现有节点down掉的时候它负责在游泳分区的所有节点中选择新的leader,这使得Kafka可以批量的高效的管理所有分区节点的主从关系。如果controller down掉了,活着的节点中的一个会备切换为新的controller.

    16、消息格式

    (1)消息格式

    消息由一个固定长度的头部和可变长度的字节数组组成。头部包含了一个版本号和CRC32校验码。

    /** 
    * 具有N个字节的消息的格式如下    
    *   
    * 如果版本号是0   
    *   
    * 1. 1个字节的 "magic" 标记   
    *   
    * 2. 4个字节的CRC32校验码
    *   
    * 3. N - 5个字节的具体信息  
    *   
    * 如果版本号是1   
    *   
    * 1. 1个字节的 "magic" 标记   
    *   
    * 2.1个字节的参数允许标注一些附加的信息比如是否压缩了,解码类型等
    *   
    * 3.4个字节的CRC32校验码   
    *   
    * 4. N - 6 个字节的具体信息 
    *   
    */
    

    (2)日志

    一个叫做“my_topic”且有两个分区的的topic,它的日志有两个文件夹组成,my_topic_0和my_topic_1,每个文件夹里放着具体的数据文件,每个数据文件都是一系列的日志实体,每个日志实体有一个4个字节的整数N标注消息的长度,后边跟着N个字节的消息。每个消息都可以由一个64位的整数offset标注,offset标注了这条消息在发送到这个分区的消息流中的起始位置。每个日志文件的名称都是这个文件第一条日志的offset.所以第一个日志文件的名字就是00000000000.kafka.所以每相邻的两个文件名字的差就是一个数字S,S差不多就是配置文件中指定的日志文件的最大容量。

    消息的格式都由一个统一的接口维护,所以消息可以在producer,broker和consumer之间无缝的传递。存储在硬盘上的消息格式如下所示:

    消息长度: 4 bytes (value: 1+4+n)
    
    版本号: 1 byte
    
    CRC校验码: 4 bytes
    
    具体的消息: n bytes
    

    (3)写操作

    消息被不断的追加到最后一个日志的末尾,当日志的大小达到一个指定的值时就会产生一个新的文件。对于写操作有两个参数,一个规定了消息的数量达到这个值时必须将数据刷新到硬盘上,另外一个规定了刷新到硬盘的时间间隔,这对数据的持久性是个保证,在系统崩溃的时候只会丢失一定数量的消息或者一个时间段的消息。

    (4)读操作

    读操作需要两个参数:一个64位的offset和一个S字节的最大读取量。S通常比单个消息的大小要大,但在一些个别消息比较大的情况下,S会小于单个消息的大小。这种情况下读操作会不断重试,每次重试都会将读取量加倍,直到读取到一个完整的消息。可以配置单个消息的最大值,这样服务器就会拒绝大小超过这个值的消息。也可以给客户端指定一个尝试读取的最大上限,避免为了读到一个完整的消息而无限次的重试。

    在实际执行读取操纵时,首先需要定位数据所在的日志文件,然后根据offset计算出在这个日志中的offset(前面的的offset是整个分区的offset),然后在这个offset的位置进行读取。定位操作是由二分查找法完成的,Kafka在内存中为每个文件维护了offset的范围。

    下面是发送给consumer的结果的格式:

    MessageSetSend (fetch result)   
    total length     : 4 bytes  
    error code       : 2 bytes  
    message 1        : x bytes  
    ... 
    message n        : x bytes  
    MultiMessageSetSend (multiFetch result) 
    total length       : 4 bytes    
    error code         : 2 bytes    
    messageSetSend 1    
    ...
    messageSetSend n
    

    (5)删除

    日志管理器允许定制删除策略。目前的策略是删除修改时间在N天之前的日志(按时间删除),也可以使用另外一个策略:保留最后的N GB数据的策略(按大小删除)。为了避免在删除时阻塞读操作,采用了copy-on-write形式的实现,删除操作进行时,读取操作的二分查找功能实际是在一个静态的快照副本上进行的,这类似于Java的CopyOnWriteArrayList。

    (6)可靠性保证

    日志文件有一个可配置的参数M,缓存超过这个数量的消息将被强行刷新到硬盘。一个日志矫正线程将循环检查最新的日志文件中的消息确认每个消息都是合法的。合法的标准为:所有文件的大小的和最大的offset小于日志文件的大小,并且消息的CRC32校验码与存储在消息实体中的校验码一致。如果在某个offset发现不合法的消息,从这个offset到下一个合法的offset之间的内容将被移除。

    有两种情况必须考虑:1,当发生崩溃时有些数据块未能写入。2,写入了一些空白数据块。第二种情况的原因是,对于每个文件,操作系统都有一个inode(inode是指在许多“类Unix文件系统”中的一种数据结构。每个inode保存了文件系统中的一个文件系统对象,包括文件、目录、大小、设备文件、socket、管道, 等等),但无法保证更新inode和写入数据的顺序,当inode保存的大小信息被更新了,但写入数据时发生了崩溃,就产生了空白数据块。CRC校验码可以检查这些块并移除,当然因为崩溃而未写入的数据块也就丢失了

    二、配置文件

    (一)java调优

    特别说明一下JVM配置 在bin/kafka-server-start.sh中添加以下内容:

    export KAFKA_HEAP_OPTS=”-Xmx4G -Xms4G”

    官方的推荐使用G1GC,但感觉还不稳定,还是先用CMS算了。以下为官方推荐内容

    Xms4g -Xmx4g -XX:PermSize=48m -XX:MaxPermSize=48m -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35
    

    好像有问题,G1还是慎用吧,先用CMS够了。

    目前的配置如下:

    -Xmx30G -Xms30G -XX:+UseCompressedOops -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:+CMSParallelRemarkEnabled -XX:+DisableExplicitGC -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=75 -Xnoclassgc
    

    For reference, here are the stats on one of LinkedIn’s busiest clusters (at peak): - 15 brokers - 15.5k partitions (replication factor 2) - 400k messages/sec in - 70 MB/sec inbound, 400 MB/sec+ outbound The tuning looks fairly aggressive, but all of the brokers in that cluster have a 90% GC pause time of about 21ms, and they’re doing less than 1 young GC per second.

    另关于jmx
    配置jmx服务
    kafka server中默认是不启动jmx端口的,需要用户自己配置

    vim bin/kafka-run-class.sh
    最前面添加一行
    JMX_PORT=8060

    (二)参数说明

    kafka中有很多的配置参数,大致可以分为以下4类:

    Broker Configs
    Consumer Configs
    Producer Configs
    New Producer Configs

    以下仅对部分重要参数说明并不断完善,全部的参数说明请参考http://kafka.apache.org/documentation.html#consumerconfigs

    broker中的配置只有3个参数是必须提供的:broker.id,log,dir, zookeeper.connect.

    1、broker.id=0

    用于区分broker,确保每台机器不同,要求是正数。当该服务器的IP地址发生改变时,broker.id没有变化,则不会影响consumers的消息情况

    2、log.dirs=/home/data/kafka

    kafka用于放置消息的目录,默认为/tmp/kafka-logs。它可以是以逗号分隔的多个目录,创建新分区时,默认会选择存在最少分区的目录。

    3、zookeeper.connect=192.168.169.91:2181,192.168.169.92:2181,192.168.169.93:2181/kafka zk

    用于放置kafka信息的地方。注意一般情况下,直接使用192.168.169.91:2181,192.168.169.92:2181,192.168.169.93:2181即可,此时kafka的相关信息会放在zk的根目录下,但如果这个zk集群同时为多个kafka集群,或者其它集群服务,则信息会很混乱,甚至有冲突。因此一般会建一个目录用于放置kafka集群信息的目录,此处的目录为/kafka。注意,这个目录必须手工创建,kafka不会自动创建这个目录。此外,在conusmer中也必须使用192.168.169.91:2181,192.168.169.92:2181,192.168.169.93:2181/kafka来读取topic内容。

    4、num.partitions=1

    创建topic时,默认的分区数

    5、num.network.threads=25

    broker用于处理网络请求的线程数,如不配置默认为3。主要处理网络io,读写缓冲区数据,基本没有io等待,配置线程数量为cpu核数加1.

    6、zookeeper.connection.timeout.ms=6000

    7、num.replica.fetchers=4
    用于follower从leader复制消息的线程数,默认为1。
    这个参数与下面介绍的replica.fetch.max.bytes决定了kafka副本从leader复制的速率,如果过小,则集群重启时同步很慢。如果过大,则会导致这个线程消耗过多的IO,导致集群响应很慢。目前建议为:

    num.replica.fetchers=5
    replica.fetch.max.bytes=10000000
    

    参考:http://grokbase.com/t/kafka/users/14chm1f1mg/increase-in-kafka-replication-fetcher-thread-not-reducing-log-replication

    7、message.max.bytes=10000000

    replica.fetch.max.bytes=10000000

    一条消息的最大字节数,说明如下:

    kafka中出现以下异常:

    [2015-06-09 17:03:05,094] ERROR [KafkaApi-0] Error processing ProducerRequest with correlation id 616 from client kafka-client on partition [test3,0] (kafka.server.KafkaApis)
    kafka.common.MessageSizeTooLargeException: Message size is 2211366 bytes which exceeds the maximum configured message size of 1000012.

    原因是集群默认每次只能接受约1M的消息,如果客户端一次发送的消息大于这个数值则会导致异常。
    在server.properties中添加以下参数

    message.max.bytes=10000000
    replica.fetch.max.bytes=10000000
    

    同时在consumer.properties中添加以下参数:

    fetch.message.max.bytes=10000000
    

    然后重启kafka进程即可,现在每次最大可接收10M的消息。

    8、delete.topic.enable=true

    默认为false,即delete topic时只是marked for deletion,但并不会真正删除topic。

    9、关于日志的保存时间或量:
    (1)log.retention.hours=24 消息被删除前保存多少小时,默认1周168小时
    (2)log.retention.bytes 默认为-1,即不限制大小。注意此外的大小是指一个topic的一个分区的最大字节数。
    当超出上述2个限制的任何一个时,日志均会被删除。

    也可以在topic级别定义这个参数:

    retention.bytes=3298534883328   #3T
    retention.bytes与retention.ms
    

    10、同步发送还是异步发送,异步吞吐量较大,但可能引入错误,默认为sync

        producer.type=sync|async
    

    This parameter specifies whether the messages are sent asynchronously in a background thread. Valid values are (1) async for asynchronous send and (2) sync for synchronous send. By setting the producer to async we allow batching together of requests (which is great for throughput) but open the possibility of a failure of the client machine dropping unsent data.

    11、batch.size 默认值为16384

    在async模式下,producer缓存多少个消息后再一起发送

    12、compression.type 默认值为none,可选gzip snappy

    The compression type for all data generated by the producer. The default is none (i.e. no compression). Valid values are none, gzip, or snappy. Compression is of full batches of data, so the efficacy of batching will also impact the compression ratio (more batching means better compression).

    13、default.replication.factor 消息副本的数量,默认为1,即没有副本

    14、 num.io.threads=48
    主要进行磁盘io操作,高峰期可能有些io等待,因此配置需要大些。配置线程数量为cpu核数2倍,最大不超过3倍.

    15、这2个参数慎用,研究一下再改动

    为了大幅度提高producer写入吞吐量,需要定期批量写文件。
    建议配置:
    * 每当producer写入10000条消息时,刷数据到磁盘
    log.flush.interval.messages=10000
    * 每间隔1秒钟时间,刷数据到磁盘
    log.flush.interval.ms=1000

    但官方的建议是:
    The maximum time between fsync calls on the log. If used in conjuction with log.flush.interval.messages the log will be flushed when either criteria is met.

    The number of messages written to a log partition before we force an fsync on the log. Setting this lower will sync data to disk more often but will have a major impact on performance. We generally recommend that people make use of replication for durability rather than depending on single-server fsync, however this setting can be used to be extra certain.

    且二者的默认值均为Long.MaxValue

    还有一些需要关注的配置项:

    Replication configurations

    用于follower从leader复制消息的线程数,默认为1

    replica.fetch.max.bytes=1048576

    当follow向leader发送数据请求后,最大的等待时长,默认为500ms

    replica.fetch.wait.max.ms=500

    每隔多久,follower会将其复制的highwater写到磁盘中,以便出错时恢复。

    replica.high.watermark.checkpoint.interval.ms=5000

    follower与leader之间的time out时长,默认为30秒 replica.socket.timeout.ms=30000

    socket每次的buffer字节数 replica.socket.receive.buffer.bytes=65536

    如果一个follower在这段时长内都没有向leader发出复制请求,则leader会认为其已经
    down掉,并从ISR中去掉。

    replica.lag.time.max.ms=10000

    如果一个follower比leader落后超过这个数据的消息数,则leader会将其从isr中去掉。

    replica.lag.max.messages=4000 partition management controller 与replica之间的超时时

    长 controller.socket.timeout.ms=30000

    The buffer size for controller-to-broker-channels

    controller.message.queue.size=10

    Log configuration

    如果在创建topic时没有指定分区大小,默认的分区大小如下 num.partitions=8

    kafka集群可以接收的最大消息字节数,默认为1M.注意,如果增大了这个数值,在

    consumer中也必须增大这个数值,否则consumer将无法消费这个消息。

    message.max.bytes=1000000

    当向一个不存在的topic发送消息时,是否允许自动创建topic

    auto.create.topics.enable=true

    kafka保存多久的数据,单位是小时

    log.retention.hours=72

    The number of messages written to a log partition before we force an fsync on the log.

    Setting this lower will sync data to disk more
    often but will have a major impact on performance. We generally recommend that
    people make use of replication for durability rather
    than depending on single-server fsync, however this setting can be used to be extra certain.

    下面2个值默认都是Long.MaxValue。
    log.flush.interval.ms=10000 log.flush.interval.messages=20000

    log.flush.scheduler.interval.ms=2000

    log.roll.hours=168

    log.retention.check.interval.ms=300000

    log.segment.bytes=1073741824 # ZK configuration zookeeper.connection.timeout.ms=6000 zookeeper.sync.time.ms=2000 # Socket server configuration
    执行请求的线程数,至少与你的磁盘数量相同。

    服务器允许最大的请求大小。它可以预防out of memory,而且应该小于java 堆大小。

    socket.request.max.bytes=104857600 socket.receive.buffer.bytes=1048576

    socket.send.buffer.bytes=1048576 queued.max.requests=16

    fetch.purgatory.purge.interval.requests=100

    producer.purgatory.purge.interval.requests=100

    14、自动创建topic
    当有消息发送到一个不存在的topic时,是否允许自动创建topic

    auto.create.topics.enable=false

    默认值为true

    三、错误处理

    1、配置kafka时,如果使用zookeeper create /kafka创建了节点,kafka与storm集成时new ZkHosts(zks) 需要改成 new ZkHosts(zks,”/kafka/brokers”),不然会报

    java.lang.RuntimeException: java.lang.RuntimeException:     org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /brokers/topics/my-replicated-topic5/partitions。
    

    storm-kafka插件默认kafka的 zk_path如下:

    public class ZkHosts implements BrokerHosts {
    private static final String DEFAULT_ZK_PATH = “/brokers”;
    

    2、如果出现以下问题,代表偏移量出错,建议重新开一个topic

    ERROR [KafkaApi-3] Error when processing fetch request for partition [xxxxx,1] offset 112394 from consumer with correlation id 0 (kafka.server.KafkaApis)
    kafka.common.OffsetOutOfRangeException: Request for offset 112394 but we only have log segments in the range 0 to 665.  
    

    3、当没有某个topic,或者是某个topic的node放置不在默认位置时,会有以下异常:

    java.lang.RuntimeException: java.lang.RuntimeException: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /kafka/brokers/topics/mytest/partitions at storm.kafka.Dynam         
    

    4、kafka中出现以下异常:

    [2015-06-09 17:03:05,094] ERROR [KafkaApi-0] Error processing ProducerRequest with correlation id 616 from client kafka-client on partition [test3,0] (kafka.server.KafkaApis)
    kafka.common.MessageSizeTooLargeException: Message size is 2211366 bytes which exceeds the maximum configured message size of 1000012.
    

    原因是集群默认每次只能接受约1M的消息,如果客户端一次发送的消息大于这个数值则会导致异常。
    在server.properties中添加以下参数

    message.max.bytes=1000000000
    replica.fetch.max.bytes=1073741824
    

    同时在consumer.properties中添加以下参数:

    fetch.message.max.bytes=1073741824
    

    然后重启kafka进程即可,现在每次最大可接收100M的消息。

    5、open too many files
    kafka出现异常,日志提示open too many file
    查找文件打开数量
    lsof -p 30353 | wc
    如果在1000以上,一般都是不正常,走过65535就会出错。
    原因打开了太多producer,没关闭,调用producer.close()即可。

    6、 Error while fetching metadata

    不小心修改了机器的hostname,但没有重启storm。

        [2015-07-02 15:15:39,295] WARN Error while fetching metadata [{TopicMetadata for topic datadog-dev -> 
        No partition metadata for topic datadog-dev due to kafka.common.LeaderNotAvailableException}] for topic [datadog-dev]: class kafka.common.LeaderNotAvailableException  (kafka.producer.BrokerPartitionInfo)
        [2015-07-02 15:15:39,295] ERROR Failed to collate messages by topic, partition due to: Failed to fetch topic metadata for topic: datadog-dev (kafka.producer.async.DefaultEventHandler)
        [2015-07-02 15:15:39,399] WARN Error while fetching metadata [{TopicMetadata for topic datadog-dev -> 
        No partition metadata for topic datadog-dev due to kafka.common.LeaderNotAvailableException}] for topic [datadog-dev]: class kafka.common.LeaderNotAvailableException  (kafka.producer.BrokerPartitionInfo)
        [2015-07-02 15:15:39,399] ERROR Failed to send requests for topics datadog-dev with correlation ids in [9,16] (kafka.producer.async.DefaultEventHandler)
        [2015-07-02 15:15:39,399] ERROR Error in handling batch of 4 events (kafka.producer.async.ProducerSendThread)
        kafka.common.FailedToSendMessageException: Failed to send messages after 3 tries.
          at kafka.producer.async.DefaultEventHandler.handle(DefaultEventHandler.scala:90)
          at kafka.producer.async.ProducerSendThread.tryToHandle(ProducerSendThread.scala:104)
          at kafka.producer.async.ProducerSendThread$$anonfun$processEvents$3.apply(ProducerSendThread.scala:87)
    		  at kafka.producer.async.ProducerSendThread$$anonfun$processEvents$3.apply(ProducerSendThread.scala:67)
          at scala.collection.immutable.Stream.foreach(Stream.scala:547)
          at kafka.producer.async.ProducerSendThread.processEvents(ProducerSendThread.scala:66)
          at kafka.producer.async.ProducerSendThread.run(ProducerSendThread.scala:44)
    

    解决方法其实很简单,只需要在Kafka的配置文件server.properties中,设置好主机名即可:

        # Hostname the broker will bind to. If not set, the server will bind to all interfaces
        host.name=kafka01
    

    或者是指定某个ip地址,如机器有2个ip,且希望使用内网ip,则需要设置为

     host.name=10.120.1.1
    

    7、netty reconnect

    出现大量的以下异常:

        2015-09-16T09:43:48.701+0800 b.s.m.n.Client [ERROR] connection attempt 60 to Netty-Client-gdc-storm03-storm./192.168.172.120:6727 failed: java.lang.RuntimeException: Returned channel was actually not established
        2015-09-16T09:43:48.701+0800 b.s.m.n.Client [INFO] connection attempt 61 to Netty-Client-gdc-storm05-storm./192.168.172.122:6718 scheduled to run in 1174 ms
        2015-09-16T09:43:48.701+0800 b.s.m.n.Client [INFO] connection attempt 61 to Netty-Client-gdc-storm03-storm./192.168.172.120:6727 scheduled to run in 1174 ms
        2015-09-16T09:43:49.383+0800 b.s.m.n.StormClientErrorHandler [INFO] Connection failed Netty-Client-gdc-storm02-storm./192.168.172.119:6720
                at org.apache.storm.netty.channel.socket.nio.NioWorker.read(NioWorker.java:64) [storm-core-0.9.4.jar:0.9.4]
                at org.apache.storm.netty.channel.socket.nio.AbstractNioWorker.process(AbstractNioWorker.java:108) [storm-core-0.9.4.jar:0.9.4]
                at org.apache.storm.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:318) [storm-core-0.9.4.jar:0.9.4]
                at org.apache.storm.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89) [storm-core-0.9.4.jar:0.9.4]
                at org.apache.storm.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) [storm-core-0.9.4.jar:0.9.4]
                at org.apache.storm.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [storm-core-0.9.4.jar:0.9.4]
                at org.apache.storm.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) [storm-core-0.9.4.jar:0.9.4]
        2015-09-16T09:43:49.534+0800 b.s.m.n.Client [ERROR] connection attempt 11 to Netty-Client-gdc-storm04-storm./192.168.172.121:6726 failed: java.lang.RuntimeException: Returned channel was actually not established
    

    其实就是storm的supervisor和worker之间进行netty通信时,netty无反应,原因可能是很多种:
    如果是一直出现,从开始就没正常过,很有可能是hostname的配置有问题。
    如果是之前好好的,突然出现了,那有可能是各方面的原因了,比如:
    (1)网络突然有问题
    (2)防火墙
    (3)要升级到0.9.5
    反正网上各种各样的说法都有,没有明确答案。

    我们还遇到了一种情况,就是在supervisor机器上执行rm和wc,导致IO非常的高,机器接近没有反应,同时出现大量的netty 连接失败。
    解决办法,把大IO操作停掉,部分拓扑会自动恢复(但有一些拓扑不会,filter类的全部恢复了)。

    还有人建议:https://gist.github.com/amontalenti/8ff0c31a7b95a6dea3d2

    执行这个命令:sudo ethtool -K eth0 sg off

    最后还可以搜索一下storm的maillist “netty reconnect”

    四、zookeeper中的内容

    默认情况,kafka在zk的/brokers目录下记录topic相关的信息,但如果在创建topic时,指定了路径,则放置到固定的路径中,如:

    bin/kafka-topics.sh --create --zookeeper 192.168.169.91:2181,192.168.169.92:2181,192.168.169.93:2181/kafka --replication-factor 3 --partitions 5 --topic test_topic
    

    1、/brokers中的信息

    创建的topic,其相关信息会放置到/kafka/brokers中,这个目录中主要包括2个子目录:ids 和 topics
    1、ids:记录这个kafka集群中有多少个broker
    如:

    ls /kafka/brokers/ids/
    3   2   5   4
    

    这个集群有4个节点,节点id分别为2,3,4,5。 我们看一下内容

    [zk: localhost:2181(CONNECTED) 27] get  /kafka/brokers/ids/2
    {"jmx_port":-1,"timestamp":"1435833841290","host":"kafka02-log.i.nease.net","version":1,"port":9092}
    cZxid = 0x1000e8a68
    ctime = Thu Jul 02 18:44:01 HKT 2015
    mZxid = 0x1000e8a68
    mtime = Thu Jul 02 18:44:01 HKT 2015
    pZxid = 0x1000e8a68
    cversion = 0
    dataVersion = 0
    aclVersion = 0
    ephemeralOwner = 0x44e440d0bdf06eb
    dataLength = 104
    numChildren = 0
    

    记录着这个节点的一些基本情况。

    2、topics
    先看一下有哪些内容:

        [zk: localhost:2181(CONNECTED) 29] ls /kafka/brokers/topics/test30/partitions
    [3, 2, 1, 0, 4]
    [zk: localhost:2181(CONNECTED) 30] ls /kafka/brokers/topics/test30/partitions/0
    [state]
    [zk: localhost:2181(CONNECTED) 1] get /kafka/brokers/topics/test30/partitions/0/state
    {"controller_epoch":4,"leader":5,"version":1,"leader_epoch":2,"isr":[5]}
    cZxid = 0x100017c5e
    ctime = Wed Jul 01 14:54:24 HKT 2015
    mZxid = 0x1000e8a84
    mtime = Thu Jul 02 18:44:01 HKT 2015
    pZxid = 0x100017c5e
    cversion = 0
    dataVersion = 2
    aclVersion = 0
    ephemeralOwner = 0x0
    dataLength = 72
    numChildren = 0
    

    可以看某个分区的leader是哪个,从而读取kafka消息时,可以从这个leader中读取数据。

    以下内容来自官方文档:

    下面给出了zk中用于保存consumber与brokers相关信息的目录结构与算法介绍。

    关于目录结构的前提说明:默认情况下,kafka相关的信息放在zk根目录下的某个路径中,但也可以设置为单独的路径,设置方法见配置选项部分。在我们的集群中,我们建立了一个目录/kafka作为所有kafka相关信息的保存位置。因此我们在这里所列的/kafka/xyz,对于默认情况应该是/xyz。

    broker节点的注册

    [zk: localhost:2181(CONNECTED) 140] get /kafka/brokers/ids/2
    {"jmx_port":-1,"timestamp":"1437460315901","host":"gdc-kafka02-log.i.nease.net","version":1,"port":9092}
    

    在zk中,有一个broker节点的列表,列表中的每一项表示一个逻辑broker。在启动时,broker节点会在zk中的/kafka/broker/ids/目录下创建一个znode,名称为配置文件中定义的broker id,如上面所示的/kafka/brokers/ids/2。建立逻辑broker id的目的是允许一个broker节点迁移到另一台机器上,而不会影响到consumer的消费。如果想注册一个已经存在的broker id会引起错误(比如说有2个broker的配置文件都写了同一个broker id)。

    由于broker在zk中注册的是一个ephemeral znodes,因此当这个broker关机或者挂掉的时候,这个注册信息会自动删除,从而会通知consumer这个节点已经不可用。

    Topic注册

    ls /kafka/brokers/topics/testtopic/partitions/
    
    3   2   1   0   4
    
    get /kafka/brokers/topics/testtopic/partitions/0/state
    
    {"controller_epoch":9,"leader":5,"version":1,"leader_epoch":26,"isr":[5]}
    

    每个topic都会在zk中注册,如上面的testtopic有5个分区。

    2、consumer的信息

    consumer与consumer组
    为了彼此协调以及平衡数据的消费,consumer也会在zk中注册信息。通过设置offsets.storage=zookeeper,可以将consumer的offset保存在zk中,不过这种做法会被逐步淘汰。现在推荐使用kafka作为offset的保存。

    一个组内的consumer可以共同消费一个topic,它们拥有同一个group_id。组内的consumer会尽可能公平的将topic的分区切分。

    关于conumser的信息储存在/consumer目录下,然后是consumer group的名称,然后分成3个子目录,分别为id, offset与owner。

    consumer id注册
    每一个consumer都会在zk注册信息,如:

    get /kafka/consumers/console-consumer-30094/ids/console-consumer-30094_gdc-kafka03-log.i.nease.net-1437029151314-d7cdc855
    {"version":1,"subscription":{"streaming_ma30_sdc":1},"pattern":"white_list","timestamp":"1437459282749"}
    

    consumer offset
    conusumer会根据它已经消费的最大的offset,默念会存储在zk的目录下(也可以设置为kafka)。

    get /kafka/consumers/testtopic/offsets/testtopic/0
    1413950858
    

    注意这是一个永久节点,因此当consumer挂掉重启时可以继续读取。

    offset中的这个值表示什么意思?不是时间?是batch?先看看simple levele api,然后再考虑mail list

    分区owner注册
    每一个broker分区会被一个consumer组里的一个consumer消费,这个consumer必须建立它对这个分区的占有(ownership),再开始消费。为了建立这个占有关系,consumer会在zk中建立相关的信息。

    /kafka/consumers/[group_id]/owners/[topic]/[broker_id-partition_id] --> consumer_node_id (ephemeral node) 
    

    3、controller和controller_epoch

    见控制器的介绍

    展开全文
  • 仅供本人学习参考, 如有侵权, 请联系删除, 多谢! Redis哨兵模式(sentinel)学习总结及部署记录(主从复制、读写分离、主从...Redis的集群方案大致有三种:1)redis cluster集群方案;2)master/slave主从方案;3...
  • WebSphere集群原理

    2011-10-24 16:18:40
    WAS集群由一组应用服务器组成,每个服务器上部署了同样的应用程序。通过集群可以实现可扩展性(服务更多客户,提高吞吐量),负载均衡(平衡负载资源,使资源得以有效利用),高可用性(提供故障恢复和补偿机制,在...
  • Tomcat集群原理

    万次阅读 2014-07-28 22:02:16
    对于WEB应用集群的技术实现而言,最大的难点就是如何能在集群中的多个节点之间保持数据的一致性,会话(Session)信息是这些数据中最重要的一块。要实现这一点,大体上有两种方式,一种是把所有Session数据放到一台...
  • 通过前面四章内容,已经完成了对环境的配置、DM、App、IHS的安装和配置,本文就对DM、App、IHS进行一个整合配置,让集群环境运行起来 1、App节点中,命令模式添加App节点到DM管理中 1.1命令行模式添加节点,在App...
  • 1、Quartz任务调度的基本实现原理  Quartz是OpenSymphony开源组织在任务调度领域的一个开源项目,完全基于Java实现。作为一个优秀的开源调度框架,Quartz具有以下特点:  (1)强大的调度功能,例如支持丰富多样...
  • tomcat 集群原理

    2014-06-20 09:36:22
    对于WEB应用集群的技术实现而言,最大的难点就是如何能在集群中的多个节点之间保持数据的一致性,会话(Session)信息是这些数据中最重要的一块。要实现这一点,大体上有两种方式,一种是把所有Session数据放到一台...
  • 主要围绕运维层面展开论述,主要包括集群搭建、日志查看、故障恢复、集群迁移、集群监控这几个方面。 RabbitMQ集群搭建 RabbitMQ日志查看 RabbitMQ故障恢复 RabbitMQ集群迁移 RabbitMQ集群监控 ...
  • 1、前面我们分析了eureka服务端实现原理、客户端实现原理,今天我们来分析一下eureka集群同步的原理,如何搭建以及使用eureka集群我们在前面以及演示过了,此处不在过多累赘。 2、eureka服务端也是客户端: 前面...
  • zookeeper 集群原理

    2017-11-12 16:04:00
    应用集群中,我们常常需要让每一个机器知道集群中(或依赖的其他某一个集群)哪些机器是活着的,并且在集群机器因为宕机,网络断链等原因能够不在人工介入的情况下迅速通知到每一个机器。 Zookeeper 同样很容易实现...
  • Redis集群提供一种方式自动将数据分布在多个Redis节点上。 Redis Cluster provides a way to run a Redis installation where data is automatically sharded across multiple Redis nodes. 1、Redis集群TCP端口...
  • WAS6.0 ND中实现集群

    千次阅读 2016-03-17 16:07:15
    1. 介绍 当前,越来越多的企业用户基于WebSphere应用服务器和DB2数据库环境...通过WAS ND集群,可以实现包含多个应用服务器的分布式环境,确保系统的吞吐量和高可用性。本文通过两个实际场景,介绍如何从头搭建一个WAS
  • 主从集群、分布式集群。 前者主要是为了高可用或是读写分离,后者为了更好的存储数据,负载均衡。 2.为什么使用Redis集群 1、处理高并发:安装分片规则,将数据自动切分(split)到多个节点 2、高可用:当集群中...
  • 1、配置信息数据结构 Redis Cluster中的每个节点都保存了集群的配置信息,并且存储在clusterState中,结构如下: 上图的各个变量语义如下: clusterState 记录了从集群中某个节点视角,来看集群配置状态;...
  • 1. Redis集群方案 Redis Cluster 集群模式通常具有 高可用、可扩展性、分布式、容错 等特性。Redis 分布式方案一般有两种: 1.1 客户端分区方案 客户端 就已经决定数据会被 存储 到哪个 redis 节点或者从哪个 redis ...
  • 对于WEB应用集群的技术实现而言,最大的难点就是如何能在集群中的多个节点之间保持数据的一致性,会话(Session)信息是这些数据中最重要的一块。要实现这一点,大体上有两种方式,一种是把所有Session数据放到一台...
  • openfire 集群原理说明

    2014-10-20 09:22:37
    openfire,做为一个实现xmpp的即时通信服务器端,自身提供了集群的实现,目前,理论上,能支持N个节点的集群,即节点无限制 看了下他集群的实现,他是用到了oracle 的coherence的中间件,关于...
  • 深入剖析Redis - Redis集群模式搭建与原理详解 1. Redis集群方案 Redis Cluster 集群模式通常具有 高可用、可扩展性、分布式、容错 等特性。Redis 分布式方案一般有两种: 1.1 客户端分区方案 客户端 就已经决定数据...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 6,185
精华内容 2,474
关键字:

was集群原理

友情链接: WSAM-06-Parsing.rar