Flume 源碼閱讀

來源:互聯網
上載者:User

標籤:

 

Flume架構

主要由3個組件,分別是Source,Channel和Sink,3個組件組成Event在Flume中得資料流向或者說流水線,功能可以由Flume的介紹看出:When a Flume source receives an event, it stores it into one or more channels. The channel is a passive store that keeps the event until it’s consumed by a Flume sink. 

源碼中有對應的3個介面:

public interface Source extends LifecycleAware, NamedComponent {  /**   * Specifies which channel processor will handle this source‘s events.   *   * @param channelProcessor   */  public void setChannelProcessor(ChannelProcessor channelProcessor);  /**   * Returns the channel processor that will handle this source‘s events.   */  public ChannelProcessor getChannelProcessor();}

從Source介面看,Source並沒有與定義與Event有關的介面,它的介面只是對ChannelProcessor的get和set方法。Source通過擷取對應的ChannelProcessor來完成訊息的投遞。

public interface Sink extends LifecycleAware, NamedComponent {    public void setChannel(Channel channel);    public Channel getChannel();    public Status process() throws EventDeliveryException;    public static enum Status {        READY, BACKOFF    }}

Sink介面,也有與Channel有關的set和get方法,且是直接對應Channel,而不是Source那樣對應ChannelProcessor。ChannelProcessor其實是位於Source和Channel之間的東西,相當於一個Event分發器,實現Source的mapping、replicating,optional機制(需要進一步看看代碼)。 Sink之所以直接對應Channel,是因為任何一個Sink只從唯一的Channel中消費資料並發送到目標端。

public class ChannelProcessor implements Configurable {  private final ChannelSelector selector;  private final InterceptorChain interceptorChain;  public ChannelProcessor(ChannelSelector selector) {    this.selector = selector;    this.interceptorChain = new InterceptorChain();  }  public void initialize() {    interceptorChain.initialize();  }  public void close() {    interceptorChain.close();  }  /**   * The Context of the associated Source is passed.   * @param context   */  @Override  public void configure(Context context) {    configureInterceptors(context);  }  public ChannelSelector getSelector() {    return selector;  }  public void processEventBatch(List<Event> events) {   。。。  }  public void processEvent(Event event) {    。。。。  }

從ChannelProcessor簡略代碼看主要就是實現mapping、replicating和optional機制的資料分發,以及攔截機制。

再看下Channel的介面源碼:

public interface Channel extends LifecycleAware, NamedComponent {  public void put(Event event) throws ChannelException;  public Event take() throws ChannelException;  public Transaction getTransaction();}

再看看官方描述:

A channel connects a Source to a Sink. The source acts as producer while the sink acts as a consumer of events. The channel itself is the buffer between the two.

A channel exposes a Transaction interface that can be used by its clients to ensure atomic put and take semantics. This is necessary to guarantee single hop reliability between agents. For instance, a source will successfully produce an event if and only if that event can be committed to the source‘s associated channel. Similarly, a sink will consume an event if and only if its respective endpoint can accept the event. The extent of transaction support varies for different channel implementations ranging from strong to best-effort semantics.

Flume uses a transactional approach to guarantee the reliable delivery of the events. The sources and sinks encapsulate in a transaction the storage/retrieval, respectively, of the events placed in or provided by a transaction provided by the channel. This ensures that the set of events are reliably passed from point to point in the flow. In the case of a multi-hop flow, the sink from the previous hop and the source from the next hop both have their transactions running to ensure that the data is safely stored in the channel of the next hop.

 從以上看出,Channel主要是儲存Event,Event的存和取操作由Transaction控制。 後面再重點學習下Transaction

 

Transaction

Flume中的事務用來保證訊息的可靠傳遞。

同樣也先看下官方注釋中關於Transaction的使用例子和介紹:

org.apache.flume.Transaction Provides the transaction boundary while accessing a channelA Transaction instance is used to encompass channel access via the following idiom: Channel ch = ... Transaction tx = ch.getTransaction(); try {   tx.begin();   ...   // ch.put(event) or ch.take()   ...   tx.commit(); } catch (ChannelException ex) {   tx.rollback();   ... } finally {   tx.close(); } Depending upon the implementation of the channel, the transaction semantics may be strong, or best-effort only.Transactions must be thread safe. To provide a guarantee of thread safe access to Transactions, see BasicChannelSemantics and BasicTransactionSemantics.

使用繼承來自BasicChannelSemantics的Channel時,Flume強制在操作Channel時採用特定的程式結構,並且強制channel實現特定的方法以使得Channel本身可以應對存入或取出失敗的情況,並且使得channel的使用者有可能根據操作是否成功採取適當的方法。

Channel好比是資料庫,而事務類就好比為資料庫事務,於是Flume通過事務來確保Source和Sink採用特定的方式訪問Channel,以保證Channel狀態的一致性。例如當一個事務中需要把一個batch的event全放入Channel時,需要確保這個操作是原子的,要不全放進去,要不一個不放。

MemoryChannel實現的關係圖:

AbstractChannel主要實現了NamedComponent、LifecycleAware和Configurable這幾個基本的介面,還並沒有與事務有關。

BasicChannelSemantics實現在在local-thread中儲存一個BasicTransactionSemantics對象的功能。它對Channel介面中take和put方法的實現為:確保當前的線程中有Transaction的一個可用的執行個體,然後把take和put代理給本線程transaction對象的同名方法。

BasicTransactionSemantics確保了事務相關的操作只有按正確的順序執行才可以。即tx.begin =》 channel.take/put =》 tx.commit =》  tx.close。它只保證了對Channel操作的順序,由子類實現doBegin, doTake, doPut, doCommit, doRollback, doClose等方法。

因此BasicChannelSemantic類和BasicTransactionSemantics類一起保證了操作Channel的邏輯。提供了所有Channel的父類。事務中的各個操作的語義,則由BasicTransactionSemantics的子類去實現,即它的子類來說明事務開始時幹嘛,交易回復時幹嘛,取出訊息時幹嘛、放入訊息時幹嘛等等。

 

BasicTransactionSemantic類

BasicChannelSemantics實現了基礎的Channel文法,包括了Transaction的thread-local文法。每個線程都包括了一個唯一的Transaction對象,保證了事務的隔離性:

private ThreadLocal<BasicTransactionSemantics> currentTransaction      = new ThreadLocal<BasicTransactionSemantics>();

線上程中擷取當前線程中的事務通過getTransaction方法,它會調用BasicChannelSemantics中定義的的抽象方法createTransaction()來擷取BasicTransactionSemantics的執行個體。

/**   * <p>   * Initializes the channel if it is not already, then checks to see   * if there is an open transaction for this thread, creating a new   * one via <code>createTransaction</code> if not.   * @return the current <code>Transaction</code> object for the   *     calling thread   * </p>   */  @Override  public Transaction getTransaction() {    if (!initialized) {      synchronized (this) {        if (!initialized) {          initialize();          initialized = true;        }      }    }    BasicTransactionSemantics transaction = currentTransaction.get();    if (transaction == null || transaction.getState().equals(            BasicTransactionSemantics.State.CLOSED)) {      transaction = createTransaction();      currentTransaction.set(transaction);    }    return transaction;  }
@Override  public void put(Event event) throws ChannelException {    BasicTransactionSemantics transaction = currentTransaction.get();    Preconditions.checkState(transaction != null,        "No transaction exists for this thread");    transaction.put(event);  }  @Override  public Event take() throws ChannelException {    BasicTransactionSemantics transaction = currentTransaction.get();    Preconditions.checkState(transaction != null,        "No transaction exists for this thread");    return transaction.take();  }

真正的存取Event,是由其代理的BaseTransactionSemantics對象完成。

 

BaseTransactionSemantics類

也先看官方描述:

org.apache.flume.channel.BasicTransactionSemantics

An implementation of basic Transaction semantics designed to work in concert with BasicChannelSemantics to simplify creation of robust Channel implementations. This class ensures that each transaction implementation method is called only while the transaction is in the correct state for that method, and only by the thread that created the transaction. Nested calls to begin()and close() are supported as long as they are balanced.

Subclasses need only implement doPut, doTake, doCommit, and doRollback, and the developer can rest assured that those methods are called only after transaction state preconditions have been properly met. doBegin and doClose may also be implemented if there is work to be done at those points.

All InterruptedException exceptions thrown from the implementations of the doXXX methods are automatically wrapped to become ChannelExceptions, but only after restoring the interrupted status of the thread so that any subsequent blocking method calls will themselves throw InterruptedException rather than blocking. The exception to this rule is doTake, which simply returns null instead of wrapping and propagating the InterruptedException, though it still first restores the interrupted status of the thread.

主要成員函數有:begin,commit,close, doBegin,doCommit,doClose,doPut,doTake,doRollback,getState,toString,put,take,rollback

其中put take begin close commit rollback 的結構都很相似。主要結構都是確保這些操作時Transaction在正確的對應狀態,然後調用doXXX方法。如果當前的線程不擁有當前的事務或者事務的狀態不對,就拋出異常。如果doXXX方法拋出InterruptedException就通過Thread.currentThread.interrupt()方法恢複當前線程的interrupted狀態,然後將捕獲的InterruptedException封裝成一個ChannelException拋出:

 @Override  public void rollback() {    Preconditions.checkState(Thread.currentThread().getId() == initialThreadId,        "rollback() called from different thread than getTransaction()!");    Preconditions.checkState(state.equals(State.OPEN),        "rollback() called when transaction is %s!", state);    state = State.COMPLETED;    try {      doRollback();    } catch (InterruptedException e) {      Thread.currentThread().interrupt();      throw new ChannelException(e.toString(), e);    }  }

之前說過BasicChannelSemantic類對Channel介面定義的put和take的實現是代理給了自己線程中的BasicTransactionSemantic的put和get方法。而BasicTransactionSemantic中這兩個方法,可以看看take實現:

  protected Event take() {    Preconditions.checkState(Thread.currentThread().getId() == initialThreadId,        "take() called from different thread than getTransaction()!");    Preconditions.checkState(state.equals(State.OPEN),        "take() called when transaction is %s!", state);    try {      return doTake();    } catch (InterruptedException e) {      Thread.currentThread().interrupt();      return null;    }  }

從代碼中顯然看到需要子類要實現的doTake和doPut方法。因此一個Channel的具體實現,其訊息的處理邏輯是由自己的getTransaction()方法返回的Trasaction對象來實現的。具體可以再閱讀MemoryChannel的內部類MemoryTransaction代碼。

Flume 源碼閱讀

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.