Spark內置框架rpc通訊機制及RpcEnv基礎設施-Spark商業環境實戰

版權聲明:本套技術專欄是作者(秦凱新)平時工作的總結和升華,通過從真實商業環境抽取案例進行總結和分享,并給出商業應用的調優建議和集群環境容量規劃等內容,請持續關注本套博客。版權聲明:禁止轉載,歡迎學習。

Spark商業環境實戰及調優進階系列

1. Spark 內置框架rpc通訊機制

TransportContext 內部握有創建TransPortClient和TransPortServer的方法實現,但卻屬于最底層的RPC通訊設施。為什么呢?

因為成員變量RPCHandler是抽象的,并沒有具體的消息處理,而且TransportContext功能也在于創建TransPortClient客戶端和TransPortServer服務端。具體解釋如下:

 Contains the context to create a {@link TransportServer}, {@link TransportClientFactory}, and to
 setup Netty Channel pipelines with a
 {@link org.apache.spark.network.server.TransportChannelHandler}.

所以TransportContext只能為最底層的通訊基礎。上層為NettyRPCEnv高層封裝,并持有TransportContext引用,在TransportContext中傳入NettyRpcHandler實體,來實現netty通訊回調Handler處理。TransportContext代碼片段如下:

 /* The TransportServer and TransportClientFactory both create a TransportChannelHandler for each
 * channel. As each TransportChannelHandler contains a TransportClient, this enables server
 * processes to send messages back to the client on an existing channel.
 */
  public class TransportContext {
  private final Logger logger = LoggerFactory.getLogger(TransportContext.class);
  private final TransportConf conf;
  private final RpcHandler rpcHandler;
  private final boolean closeIdleConnections;

  private final MessageEncoder encoder;
  private final MessageDecoder decoder;

  public TransportContext(TransportConf conf, RpcHandler rpcHandler) {
    this(conf, rpcHandler, false);
  }

1.1 客戶端和服務端統一的消息接收處理器 TransportChannelHandlerer

TransportClient 和TransportServer 在配置Netty的pipeLine的handler處理器時,均采用TransportChannelHandler, 來做統一的消息receive處理。為什么呢?在于統一消息處理入口,TransportChannelHandlerer根據消息類型執行不同的處理,代碼片段如下:

 public void channelRead(ChannelHandlerContext ctx, Object request) throws Exception {
    if (request instanceof RequestMessage) {
      requestHandler.handle((RequestMessage) request);
   } else if (request instanceof ResponseMessage) {
      responseHandler.handle((ResponseMessage) request);
   } else {
      ctx.fireChannelRead(request);
   }

}

TransportContext初始化Pipeline的代碼片段:

  public TransportChannelHandler initializePipeline(
  SocketChannel channel,
  RpcHandler channelRpcHandler) {
  try {
    
  TransportChannelHandler channelHandler = createChannelHandler(channel,
  
  channelRpcHandler);
  channel.pipeline()
    .addLast("encoder", ENCODER)
    .addLast(TransportFrameDecoder.HANDLER_NAME, NettyUtils.createFrameDecoder())
    .addLast("decoder", DECODER)
    .addLast("idleStateHandler", new IdleStateHandler(0, 0,   
                   conf.connectionTimeoutMs() / 1000))
                   
    .addLast("handler", channelHandler);
    
  return channelHandler;
} catch (RuntimeException e) {
  logger.error("Error while initializing Netty pipeline", e);
  throw e;
}

客戶端和服務端統一的消息接收處理器 TransportChannelHandlerer 是這個函數:createChannelHandler(channel, channelRpcHandler)實現的,也即統一了這個netty的消息接受處理,代碼片段如下:

    /**
    * Creates the server- and client-side handler which is used to handle both RequestMessages and
    * ResponseMessages. The channel is expected to have been successfully created, though certain
    * properties (such as the remoteAddress()) may not be available yet.
    */
    
    private TransportChannelHandler createChannelHandler(Channel channel,                                    RpcHandler rpcHandler) {
    
    TransportResponseHandler responseHandler = new                     
    TransportResponseHandler(channel);
    TransportClient client = new TransportClient(channel, responseHandler);
    
    TransportRequestHandler requestHandler = new TransportRequestHandler(channel, client,
    rpcHandler, conf.maxChunksBeingTransferred());
    
    return new TransportChannelHandler(client, responseHandler, requestHandler,
        conf.connectionTimeoutMs(), closeIdleConnections);
    }

不過transportClient對應的是TransportResponseHander,TransportServer對應的的是TransportRequestHander。
在進行消息處理時,首先會經過TransportChannelHandler根據消息類型進行處理器選擇,分別進行netty的消息生命周期管理:

  • exceptionCaught
  • channelActive
  • channelInactive
  • channelRead
  • userEventTriggered

1.2 transportClient對應的是ResponseMessage

客戶端一旦發送消息(均為Request消息),就會在

private final Map<Long, RpcResponseCallback> outstandingRpcs;

private final Map<StreamChunkId, ChunkReceivedCallback> outstandingFetches

中緩存,用于回調處理。

image

1.3 transportServer對應的是RequestMessage

服務端接收消息類型(均為Request消息)

  • ChunkFetchRequest
  • RpcRequest
  • OneWayMessage
  • StremRequest

服務端響應類型(均為Response消息):

  • ChunkFetchSucess
  • ChunkFetchFailure
  • RpcResponse
  • RpcFailure

2. Spark RpcEnv基礎設施

2.1 上層建筑NettyRPCEnv

上層建筑NettyRPCEnv,持有TransportContext引用,在TransportContext中傳入NettyRpcHandler實體,來實現netty通訊回調Handler處理

  • Dispatcher
  • TransportContext
  • TransPortClientFactroy
  • TransportServer
  • TransportConf

2.2 RpcEndPoint 與 RPCEndPointRef 端點

  • RpcEndPoint 為服務端
  • RPCEndPointRef 為客戶端

2.2 Dispacher 與 Inbox 與 Outbox

  • 一個端點對應一個Dispacher,一個Inbox , 多個OutBox
  1. RpcEndpoint:RPC端點 ,Spark針對于每個節點(Client/Master/Worker)都稱之一個Rpc端點 ,且都實現RpcEndpoint接口,內部根據不同端點的需求,設計不同的消息和不同的業務處理,如果需要發送(詢問)則調用Dispatcher
  2. RpcEnv:RPC上下文環境,每個Rpc端點運行時依賴的上下文環境稱之為RpcEnv
  3. Dispatcher:消息分發器,針對于RPC端點需要發送消息或者從遠程RPC接收到的消息,分發至對應的指令收件箱/發件箱。如果指令接收方是自己存入收件箱,如果指令接收方為非自身端點,則放入發件箱
  4. Inbox:指令消息收件箱,一個本地端點對應一個收件箱,Dispatcher在每次向Inbox存入消息時,都將對應EndpointData加入內部待Receiver Queue中,另外Dispatcher創建時會啟動一個單獨線程進行輪詢Receiver Queue,進行收件箱消息消費
  5. OutBox:指令消息發件箱,一個遠程端點對應一個發件箱,當消息放入Outbox后,緊接著將消息通過TransportClient發送出去。消息放入發件箱以及發送過程是在同一個線程中進行,這樣做的主要原因是遠程消息分為RpcOutboxMessage, OneWayOutboxMessage兩種消息,而針對于需要應答的消息直接發送且需要得到結果進行處理
  6. TransportClient:Netty通信客戶端,根據OutBox消息的receiver信息,請求對應遠程TransportServer
  7. TransportServer:Netty通信服務端,一個RPC端點一個TransportServer,接受遠程消息后調用Dispatcher分發消息至對應收發件箱
image

Spark在Endpoint的設計上核心設計即為Inbox與Outbox,其中Inbox核心要點為:

  1. 內部的處理流程拆分為多個消息指令(InboxMessage)存放入Inbox
  2. 當Dispatcher啟動最后,會啟動一個名為【dispatcher-event-loop】的線程掃描Inbox待處理InboxMessage,并調用Endpoint根據InboxMessage類型做相應處理
  3. 當Dispatcher啟動最后,默認會向Inbox存入OnStart類型的InboxMessage,Endpoint在根據OnStart指令做相關的額外啟動工作,端點啟動后所有的工作都是對OnStart指令處理衍生出來的,因此可以說OnStart指令是相互通信的源頭。
  • 注意: 一個端點對應一個Dispacher,一個Inbox , 多個OutBox,可以看到 inbox在Dispacher 中且在EndPointData內部:

     private final RpcHandler rpcHandler;
    /**
    * A message dispatcher, responsible for routing RPC messages to the appropriate endpoint(s).
    */
     private[netty] class Dispatcher(nettyEnv: NettyRpcEnv) extends Logging {
     private class EndpointData(
        val name: String,
        val endpoint: RpcEndpoint,
        val ref: NettyRpcEndpointRef) {
      val inbox = new Inbox(ref, endpoint)
    }
    private val endpoints = new ConcurrentHashMap[String, EndpointData]
    private val endpointRefs = new ConcurrentHashMap[RpcEndpoint, RpcEndpointRef]
    
    // Track the receivers whose inboxes may contain messages.
    private val receivers = new LinkedBlockingQueue[EndpointData]
    
image
  • 注意: 一個端點對應一個Dispacher,一個Inbox , 多個OutBox,可以看到 OutBox在NettyRpcEnv內部:

    private[netty] class NettyRpcEnv(
      val conf: SparkConf,
      javaSerializerInstance: JavaSerializerInstance,
      host: String,
      securityManager: SecurityManager) extends RpcEnv(conf) with Logging {
      
      private val dispatcher: Dispatcher = new Dispatcher(this)
      
      private val streamManager = new NettyStreamManager(this)
      private val transportContext = new TransportContext(transportConf,
      new NettyRpcHandler(dispatcher, this, streamManager))
      
    /**
     * A map for [[RpcAddress]] and [[Outbox]]. When we are connecting to a remote [[RpcAddress]],
     * we just put messages to its [[Outbox]] to implement a non-blocking `send` method.
     */
    private val outboxes = new ConcurrentHashMap[RpcAddress, Outbox]()
    

2.3 Dispacher 與 Inbox 與 Outbox

Dispatcher的代碼片段中,包含了核心的消息發送代碼邏輯,意思是:向服務端發送一條消息,也即同時放進Dispatcher中的receiverrs中,也放進inbox的messages中。這個高層封裝,如Master和Worker端點發送消息都是通過NettyRpcEnv中的 Dispatcher來實現的。在Dispatcher中有一個線程,叫做MessageLoop,實現消息的及時處理。

 /**
 * Posts a message to a specific endpoint.
 *
 * @param endpointName name of the endpoint.
 * @param message the message to post
  * @param callbackIfStopped callback function if the endpoint is stopped.
 */
 private def postMessage(
  endpointName: String,
  message: InboxMessage,
  callbackIfStopped: (Exception) => Unit): Unit = {
   val error = synchronized {
   val data = endpoints.get(endpointName)
   
  if (stopped) {
    Some(new RpcEnvStoppedException())
  } else if (data == null) {
    Some(new SparkException(s"Could not find $endpointName."))
  } else {
  
    data.inbox.post(message)
    receivers.offer(data)
    
    None
  }
 }

注意:默認第一條消息為onstart,為什么呢?看這里:

image
image

看到下面的 new EndpointData(name, endpoint, endpointRef) 了嗎?

def registerRpcEndpoint(name: String, endpoint: RpcEndpoint): NettyRpcEndpointRef = {
 val addr = RpcEndpointAddress(nettyEnv.address, name)
    val endpointRef = new NettyRpcEndpointRef(nettyEnv.conf, addr, nettyEnv)
    synchronized {
  if (stopped) {
    throw new IllegalStateException("RpcEnv has been stopped")
  }
  if (endpoints.putIfAbsent(name, new EndpointData(name, endpoint, endpointRef)) != null) {
    throw new IllegalArgumentException(s"There is already an RpcEndpoint called $name")
  }
  val data = endpoints.get(name)
  endpointRefs.put(data.endpoint, data.ref)
  receivers.offer(data)  // for the OnStart message
}
endpointRef

}

注意EndpointData里面包含了inbox,因此Inbox初始化的時候,放進了onstart

 private class EndpointData(
  val name: String,
  val endpoint: RpcEndpoint,
  val ref: NettyRpcEndpointRef) {
val inbox = new Inbox(ref, endpoint)

}

onstart在Inbox初始化時出現了,注意每一個端點只有一個inbox,比如:master 節點。


image

2.4 發送消息流程為分為兩種,一種端點(Master)自己把消息發送到本地Inbox,一種端點(Master)接收到消息后,通過TransPortRequestHander接收后處理,扔進Inbox

2.4.1 端點(Master)自己把消息發送到本地Inbox
- endpoint(Master) -> NettyRpcEnv-> Dispatcher ->  postMessage -> MessageLoop(Dispatcher) -> inbox -> process -> endpoint.receiveAndReply

解釋如下:端點通過自己的RPCEnv環境,向自己的Inbox中發送消息,然后交由Dispatch來進行消息的處理,調用了端點自己的receiveAndReply方法

  • 這里著重講一下MessageLoop是什么時候啟動的,參照Dispatcher的代碼段如下,一旦初始化就會啟動,因為是成員變量:

      private val threadpool: ThreadPoolExecutor = {
      val numThreads = nettyEnv.conf.getInt("spark.rpc.netty.dispatcher.numThreads",
        math.max(2, Runtime.getRuntime.availableProcessors()))
      val pool = ThreadUtils.newDaemonFixedThreadPool(numThreads, "dispatcher-event-loop")
      for (i <- 0 until numThreads) {
        pool.execute(new MessageLoop)
      }
       pool
     }
    
  • 接著講nettyRpcEnv是何時初始化的,Dispatcher是何時初始化的?

master初始化RpcEnv環境時,調用NettyRpcEnvFactory().create(config)進行初始化nettyRpcEnv,然后其成員變量Dispatcher開始初始化,然后Dispatcher內部成員變量threadpool開始啟動messageLoop,然后開始處理消息,可謂是一環套一環啊。如下是Master端點初始化RPCEnv。


image

在NettyRpcEnv中,NettyRpcEnvFactory的create方法如下:

image

其中nettyRpcEnv.startServer,代碼段如下,然后調用底層 transportContext.createServer來創建Server,并初始化netty 的 pipeline:

    server = transportContext.createServer(host, port, bootstraps)
    dispatcher.registerRpcEndpoint(
     RpcEndpointVerifier.NAME, new RpcEndpointVerifier(this, dispatcher))

最終端點開始不斷向自己的Inboxz中發送消息即可,代碼段如下:

    private def postMessage(
      endpointName: String,
      message: InboxMessage,
      callbackIfStopped: (Exception) => Unit): Unit = {
      error = synchronized {
      val data = endpoints.get(endpointName)
      if (stopped) {
           Some(new RpcEnvStoppedException())
      } else if (data == null) {
          Some(new SparkException(s"Could not find $endpointName."))
      } else {
      
         data.inbox.post(message)
         receivers.offer(data)
         
         None
      }
    }
2.4.2 端點(Master)接收到消息后,通過TransPortRequestHander接收后處理,扔進Inbox
- endpointRef(Worker) ->TransportChannelHandler -> channelRead0 -> TransPortRequestHander -> handle -> processRpcRequest ->NettyRpcHandler(在NettyRpcEnv中)  -> receive ->  internalReceive -> dispatcher.postToAll(RemoteProcessConnected(remoteEnvAddress)) (響應)-> dispatcher.postRemoteMessage(messageToDispatch, callback) (發送遠端來的消息放進inbox)-> postMessage -> inbox -> process

如下圖展示了整個消息接收到inbox的流程:


image

下圖展示了 TransportChannelHandler接收消息:

    @Override
 public void channelRead0(ChannelHandlerContext ctx, Message request) throws Exception {
 if (request instanceof RequestMessage) {
  requestHandler.handle((RequestMessage) request);
} else {
  responseHandler.handle((ResponseMessage) request);
}
 }

然后TransPortRequestHander來進行消息匹配處理:

image

最終交給inbox的process方法,實際上由端點 endpoint.receiveAndReply(context)方法處理:

 /**
 * Process stored messages.
 */
 def process(dispatcher: Dispatcher): Unit = {
  var message: InboxMessage = null
    inbox.synchronized {
  if (!enableConcurrent && numActiveThreads != 0) {
    return
  }
  message = messages.poll()
  if (message != null) {
    numActiveThreads += 1
  } else {
    return
  }
}
while (true) {
  safelyCall(endpoint) {
    message match {
      case RpcMessage(_sender, content, context) =>
        try {
          endpoint.receiveAndReply(context).applyOrElse[Any, Unit](content, { msg =>
            throw new SparkException(s"Unsupported message $message from ${_sender}")
          })
        } catch {
          case NonFatal(e) =>
            context.sendFailure(e)
            // Throw the exception -- this exception will be caught by the safelyCall function.
            // The endpoint's onError function will be called.
            throw e
        }

      case OneWayMessage(_sender, content) =>
        endpoint.receive.applyOrElse[Any, Unit](content, { msg =>
          throw new SparkException(s"Unsupported message $message from ${_sender}")
        })

      case OnStart =>
        endpoint.onStart()
        if (!endpoint.isInstanceOf[ThreadSafeRpcEndpoint]) {
          inbox.synchronized {
            if (!stopped) {
              enableConcurrent = true
            }
          }
        }

      case OnStop =>
        val activeThreads = inbox.synchronized { inbox.numActiveThreads }
        assert(activeThreads == 1,
          s"There should be only a single active thread but found $activeThreads threads.")
        dispatcher.removeRpcEndpointRef(endpoint)
        endpoint.onStop()
        assert(isEmpty, "OnStop should be the last message")

      case RemoteProcessConnected(remoteAddress) =>
        endpoint.onConnected(remoteAddress)

      case RemoteProcessDisconnected(remoteAddress) =>
        endpoint.onDisconnected(remoteAddress)

      case RemoteProcessConnectionError(cause, remoteAddress) =>
        endpoint.onNetworkError(cause, remoteAddress)
    }
  }

  inbox.synchronized {
    // "enableConcurrent" will be set to false after `onStop` is called, so we should check it
    // every time.
    if (!enableConcurrent && numActiveThreads != 1) {
      // If we are not the only one worker, exit
      numActiveThreads -= 1
      return
    }
    message = messages.poll()
    if (message == null) {
      numActiveThreads -= 1
      return
    }
  }
}

}

3 結語

本文花了將近兩天時間進行剖析Spark的 Rpc 工作原理,真是不容易,關鍵是你看懂了嗎?歡迎評論

秦凱新 于深圳 2018-10-28

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,316評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,481評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,241評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,939評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,697評論 6 409
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,182評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,247評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,406評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,933評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,772評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,973評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,516評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,638評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,866評論 1 285
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,644評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,953評論 2 373

推薦閱讀更多精彩內容