Spark详解(08) - Spark(3.0)内核解析和源码欣赏

源码全流程

Spark提交流程(YarnCluster)

Spark通讯架构

Spark任务划分

Task任务调度

Shuffle原理

HashShuffle流程

优化后的HashShuffle流程

假设前提:每个Executor只有1个CPU core,也就是说,无论这个Executor上分配多少个task线程,同一时间都只能执行一个task线程

SortShuffle流程

bypassShuffle流程

环境准备及提交流程

程序起点

1)spark-3.0.0-bin-hadoop3.2\bin\spark-submit.cmd => cmd /V /E /C ""%~dp0spark-submit2.cmd" %*"

2)spark-submit2.cmd => set CLASS=org.apache.spark.deploy.SparkSubmit "%~dp0spark-class2.cmd" %CLASS% %*

3)spark-class2.cmd => %SPARK_CMD%

4)在spark-class2.cmd文件中增加打印%SPARK_CMD%语句

echo %SPARK_CMD%

%SPARK_CMD%

5)在spark-3.0.0-bin-hadoop3.2\bin目录上执行cmd命令

6)进入命令行窗口,输入

spark-submit --class org.apache.spark.examples.SparkPi --master local[2] ../examples/jars/spark-examples_2.12-3.0.0.jar 10

7)发现底层执行的命令为

java -cp org.apache.spark.deploy.SparkSubmit

说明:java -cp和 -classpath一样,是指定类运行所依赖其他类的路径。

8)执行java -cp 就会开启JVM虚拟机,在虚拟机上开启SparkSubmit进程,然后开始执行main方法

java -cp =》开启JVM虚拟机 =》开启Process(SparkSubmit)=》程序入口SparkSubmit.main

9)在IDEA中全局查找(ctrl + n):org.apache.spark.deploy.SparkSubmit,找到SparkSubmit的伴生对象,并找到main方法

  1. override def main(args: Array[String]): Unit = {
  2.     val submit = new SparkSubmit() {
  3.         ... ...
  4.     }
  5. }

创建Yarn Client客户端并提交

程序入口

SparkSubmit.scala

  1. override def main(args: Array[String]): Unit = {
  2.     val submit = new SparkSubmit() {
  3.     ... ...
  4.         override def doSubmit(args: Array[String]): Unit = {
  5.           super.doSubmit(args)
  6.         }
  7.     }
  8.     submit.doSubmit(args)
  9. }

def doSubmit()方法

  1. def doSubmit(args: Array[String]): Unit = {
  2.     val uninitLog = initializeLogIfNecessary(true, silent = true)
  3.     // 解析参数
  4.     val appArgs = parseArguments(args)
  5.     … …
  6.     appArgs.action match {
  7.         // 提交作业
  8.         case SparkSubmitAction.SUBMIT => submit(appArgs, uninitLog)
  9.         case SparkSubmitAction.KILL => kill(appArgs)
  10.         case SparkSubmitAction.REQUEST_STATUS => requestStatus(appArgs)
  11.         case SparkSubmitAction.PRINT_VERSION => printVersion()   
  12.     }
  13. }

解析输入参数

  1. protected def parseArguments(args: Array[String]): SparkSubmitArguments = {
  2.     new SparkSubmitArguments(args)
  3. }

SparkSubmitArguments.scala

  1. private[deploy] class SparkSubmitArguments(args: Seq[String], env: Map[String, String] = sys.env)
  2.     extends SparkSubmitArgumentsParser with Logging {
  3.     ... ...
  4.     parse(args.asJava)
  5.     ... ...
  6. }

SparkSubmitOptionParser.java

  1. protected final void parse(List<String> args) {
  2.  
  3.     Pattern eqSeparatedOpt = Pattern.compile("(--[^=]+)=(.+)");
  4.     
     
  5.     int idx = 0;
  6.     for (idx = 0; idx < args.size(); idx++) {
  7.         String arg = args.get(idx);
  8.         String value = null;
  9.     
     
  10.         Matcher m = eqSeparatedOpt.matcher(arg);
  11.         if (m.matches()) {
  12.             arg = m.group(1);
  13.             value = m.group(2);
  14.         }
  15.     
     
  16.         String name = findCliOption(arg, opts);
  17.         if (name != null) {
  18.             if (value == null) {
  19.                 … …
  20.             }
  21.             // handle的实现类(ctrl + h)是SparkSubmitArguments.scala中
  22.             if (!handle(name, value)) {
  23.                 break;
  24.             }
  25.             continue;
  26.         }
  27.         … …
  28.     }
  29.     handleExtraArgs(args.subList(idx, args.size()));
  30. }

SparkSubmitArguments.scala

  1. override protected def handle(opt: String, value: String): Boolean = {
  2.     opt match {
  3.         case NAME =>
  4.             name = value
  5.         // protected final String MASTER = "--master";  SparkSubmitOptionParser.java
  6.         case MASTER =>
  7.             master = value
  8.         
     
  9.         case CLASS =>
  10.             mainClass = value
  11.         ... ...
  12.         case _ =>
  13.             error(s"Unexpected argument '$opt'.")
  14.     }
  15.     action != SparkSubmitAction.PRINT_VERSION
  16. }
  17.  
  18. private[deploy] class SparkSubmitArguments(args: Seq[String], env: Map[String, String] = sys.env)
  19.   extends SparkSubmitArgumentsParser with Logging {
  20.     ... ...
  21.     var action: SparkSubmitAction = null
  22.     ... ...
  23.     
     
  24.     private def loadEnvironmentArguments(): Unit = {
  25.         ... ...
  26.         // Action should be SUBMIT unless otherwise specified
  27.         // action默认赋值submit
  28.         action = Option(action).getOrElse(SUBMIT)
  29.     }
  30.     ... ...
  31. }

选择创建哪种类型的客户端

SparkSubmit.scala

  1. private[spark] class SparkSubmit extends Logging {
  2.     ... ...
  3.     def doSubmit(args: Array[String]): Unit = {
  4.  
  5.         val uninitLog = initializeLogIfNecessary(true, silent = true)
  6.         // 解析参数
  7.         val appArgs = parseArguments(args)
  8.         if (appArgs.verbose) {
  9.           logInfo(appArgs.toString)
  10.         }
  11.         appArgs.action match {
  12.           // 提交作业
  13.           case SparkSubmitAction.SUBMIT => submit(appArgs, uninitLog)
  14.           case SparkSubmitAction.KILL => kill(appArgs)
  15.           case SparkSubmitAction.REQUEST_STATUS => requestStatus(appArgs)
  16.           case SparkSubmitAction.PRINT_VERSION => printVersion()
  17.         }
  18.     }
  19.     
     
  20.     private def submit(args: SparkSubmitArguments, uninitLog: Boolean): Unit = {
  21.     
     
  22.         def doRunMain(): Unit = {
  23.             if (args.proxyUser != null) {
  24.                 … …
  25.             } else {
  26.                 runMain(args, uninitLog)
  27.             }
  28.         }
  29.  
  30.         if (args.isStandaloneCluster && args.useRest) {
  31.             … …
  32.         } else {
  33.             doRunMain()
  34.         }
  35.     }    
  36.     
     
  37.     private def runMain(args: SparkSubmitArguments, uninitLog: Boolean): Unit = {
  38.         // 选择创建什么应用:YarnClusterApplication
  39.         val (childArgs, childClasspath, sparkConf, childMainClass) = prepareSubmitEnvironment(args)
  40.         ... ...
  41.         var mainClass: Class[_] = null
  42.         
     
  43.         try {
  44.             mainClass = Utils.classForName(childMainClass)
  45.         } catch {
  46.             ... ...
  47.         }
  48.         // 反射创建应用:YarnClusterApplication
  49.         val app: SparkApplication = if (classOf[SparkApplication].isAssignableFrom(mainClass)) {
  50.             mainClass.getConstructor().newInstance().asInstanceOf[SparkApplication]
  51.         } else {
  52.             new JavaMainApplication(mainClass)
  53.         }
  54.         ... ...
  55.         try {
  56.             //启动应用
  57.             app.start(childArgs.toArray, sparkConf)
  58.         } catch {
  59.         case t: Throwable =>
  60.             throw findCause(t)
  61.         }
  62.     }
  63.     ... ... 
  64. }

SparkSubmit.scala

  1. private[deploy] def prepareSubmitEnvironment(
  2.       args: SparkSubmitArguments,
  3.       conf: Option[HadoopConfiguration] = None)
  4.       : (Seq[String], Seq[String], SparkConf, String) = {
  5.  
  6.     var childMainClass = ""
  7.     ... ...
  8.     // yarn集群模式
  9.     if (isYarnCluster) {
  10. // YARN_CLUSTER_SUBMIT_CLASS="org.apache.spark.deploy.yarn.YarnClusterApplication"
  11.         childMainClass = YARN_CLUSTER_SUBMIT_CLASS
  12.         ... ...
  13.     }
  14.     ... ...
  15.     (childArgs, childClasspath, sparkConf, childMainClass)
  16. }

Yarn客户端参数解析

1)在pom.xml文件中添加依赖spark-yarn

  1. <dependency>
  2.     <groupId>org.apache.spark</groupId>
  3.     <artifactId>spark-yarn_2.12</artifactId>
  4.     <version>3.0.0</version>
  5. </dependency>

2)在IDEA中全文查找(ctrl+n)org.apache.spark.deploy.yarn.YarnClusterApplication

3)Yarn客户端参数解析

Client.scala

  1. private[spark] class YarnClusterApplication extends SparkApplication {
  2.   override def start(args: Array[String], conf: SparkConf): Unit = {
  3.     ... ...
  4.     new Client(new ClientArguments(args), conf, null).run()
  5.   }
  6. }

ClientArguments.scala

  1. private[spark] class ClientArguments(args: Array[String]) {
  2.     ... ...
  3.     parseArgs(args.toList)
  4.     
     
  5.     private def parseArgs(inputArgs: List[String]): Unit = {
  6.         var args = inputArgs
  7.         while (!args.isEmpty) {
  8.             args match {
  9.                 case ("--jar") :: value :: tail =>
  10.                 userJar = value
  11.                 args = tail
  12.         
     
  13.                 case ("--class") :: value :: tail =>
  14.                 userClass = value
  15.                 args = tail
  16.                 ... ...
  17.                 case _ =>
  18.                 throw new IllegalArgumentException(getUsageMessage(args))
  19.             }
  20.         }
  21.     }
  22.     ... ...
  23. }

创建Yarn客户端

Client.scala

  1. private[spark] class Client(
  2.     val args: ClientArguments,
  3.     val sparkConf: SparkConf,
  4.     val rpcEnv: RpcEnv)
  5.     extends Logging {
  6.     // 创建yarnClient
  7.     private val yarnClient = YarnClient.createYarnClient
  8.     ... ...
  9. }

YarnClient.java

  1. public abstract class YarnClient extends AbstractService {
  2.  
  3.     @Public
  4.     public static YarnClient createYarnClient() {
  5.         YarnClient client = new YarnClientImpl();
  6.         return client;
  7.     }
  8.     ... ...
  9. }

YarnClientImpl.java

  1. public class YarnClientImpl extends YarnClient {
  2.     // yarnClient主要用来和RM通信
  3.     protected ApplicationClientProtocol rmClient;
  4.     ... ...
  5.     
     
  6.     public YarnClientImpl() {
  7.         super(YarnClientImpl.class.getName());
  8.     }
  9.     ... ...
  10. }

Yarn客户端创建并启动ApplicationMaster

Client.scala

  1. private[spark] class YarnClusterApplication extends SparkApplication {
  2.  
  3.   override def start(args: Array[String], conf: SparkConf): Unit = {
  4.     // SparkSubmit would use yarn cache to distribute files & jars in yarn mode,
  5.     // so remove them from sparkConf here for yarn mode.
  6.     conf.remove(JARS)
  7.     conf.remove(FILES)
  8.  
  9.     new Client(new ClientArguments(args), conf, null).run()
  10.   }
  11. }
  1. private[spark] class Client(
  2.     val args: ClientArguments,
  3.     val sparkConf: SparkConf,
  4.     val rpcEnv: RpcEnv)
  5.     extends Logging {
  6.  
  7.     def run(): Unit = {
  8.         this.appId = submitApplication()
  9.         ... ...
  10.     }
  11.     
     
  12.     def submitApplication(): ApplicationId = {
  13.         var appId: ApplicationId = null
  14.         try {
  15.             launcherBackend.connect()
  16.             yarnClient.init(hadoopConf)
  17.             yarnClient.start()
  18.     
     
  19.             val newApp = yarnClient.createApplication()
  20.             val newAppResponse = newApp.getNewApplicationResponse()
  21.             appId = newAppResponse.getApplicationId()
  22.         
     
  23.             ... ...
  24.             // 封装提交参数和命令
  25.             val containerContext = createContainerLaunchContext(newAppResponse)
  26.             val appContext = createApplicationSubmissionContext(newApp, containerContext)
  27.         
     
  28.             yarnClient.submitApplication(appContext)
  29.             ... ...
  30.             appId
  31.         } catch {
  32.             ... ...
  33.         }
  34.     }
  35. }
  36.  
  37. // 封装提交参数和命令
  38. private def createContainerLaunchContext(newAppResponse: GetNewApplicationResponse)
  39.     : ContainerLaunchContext = {
  40.     ... ...
  41.     val amClass =
  42.         // 如果是集群模式启动ApplicationMaster,如果是客户端模式启动ExecutorLauncher
  43.         if (isClusterMode) {
  44.             Utils.classForName("org.apache.spark.deploy.yarn.ApplicationMaster").getName
  45.         } else {
  46.             Utils.classForName("org.apache.spark.deploy.yarn.ExecutorLauncher").getName
  47.         }
  48.         
     
  49.     val amArgs =
  50.       Seq(amClass) ++ userClass ++ userJar ++ primaryPyFile ++ primaryRFile ++ userArgs ++
  51.       Seq("--properties-file",
  52.         buildPath(Environment.PWD.$$(), LOCALIZED_CONF_DIR, SPARK_CONF_FILE)) ++
  53.       Seq("--dist-cache-conf",
  54.         buildPath(Environment.PWD.$$(), LOCALIZED_CONF_DIR, DIST_CACHE_CONF_FILE))
  55.  
  56.     // Command for the ApplicationMaster
  57.     val commands = prefixEnv ++
  58.       Seq(Environment.JAVA_HOME.$$() + "/bin/java", "-server") ++
  59.       javaOpts ++ amArgs ++
  60.       Seq(
  61.         "1>", ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout",
  62.         "2>", ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr")
  63.         
     
  64.     val printableCommands = commands.map(s => if (s == null) "null" else s).toList
  65.     amContainer.setCommands(printableCommands.asJava)
  66.  
  67.     ... ...
  68.     val securityManager = new SecurityManager(sparkConf)
  69.     amContainer.setApplicationACLs(
  70.       YarnSparkHadoopUtil.getApplicationAclsForYarn(securityManager).asJava)
  71.     setupSecurityToken(amContainer)
  72.     amContainer
  73. }

ApplicationMaster任务

1)在IDEA中全局查找(ctrl + n)org.apache.spark.deploy.yarn.ApplicationMaster,点击对应的伴生对象

ApplicationMaster.scala

  1. def main(args: Array[String]): Unit = {
  2.    
     
  3.     // 1解析传递过来的参数
  4.     val amArgs = new ApplicationMasterArguments(args)
  5.     val sparkConf = new SparkConf()
  6.     ... ...
  7.  
  8.     val yarnConf = new YarnConfiguration(SparkHadoopUtil.newConfiguration(sparkConf))
  9.     // 2创建ApplicationMaster对象
  10.     master = new ApplicationMaster(amArgs, sparkConf, yarnConf)
  11.     ... ...
  12.     ugi.doAs(new PrivilegedExceptionAction[Unit]() {
  13.         // 3执行ApplicationMaster
  14.         override def run(): Unit = System.exit(master.run())
  15.     })
  16. }

解析传递过来的参数

ApplicationMasterArguments.scala

  1. class ApplicationMasterArguments(val args: Array[String]) {
  2.     ... ...
  3.     parseArgs(args.toList)
  4.     
     
  5.     private def parseArgs(inputArgs: List[String]): Unit = {
  6.         val userArgsBuffer = new ArrayBuffer[String]()
  7.         var args = inputArgs
  8.     
     
  9.         while (!args.isEmpty) {
  10.             args match {
  11.                 case ("--jar") :: value :: tail =>
  12.                 userJar = value
  13.                 args = tail
  14.         
     
  15.                 case ("--class") :: value :: tail =>
  16.                 userClass = value
  17.                 args = tail
  18.                 ... ...
  19.         
     
  20.                 case _ =>
  21.                 printUsageAndExit(1, args)
  22.             }
  23.         }
  24.         ... ...
  25.     }
  26.     ... ...
  27. }}

创建RMClient并启动Driver

ApplicationMaster.scala

  1. private[spark] class ApplicationMaster(
  2.     args: ApplicationMasterArguments,
  3.     sparkConf: SparkConf,
  4.     yarnConf: YarnConfiguration) extends Logging {
  5.     ... ...
  6.     // 1创建RMClient
  7.     private val client = new YarnRMClient()
  8.     ... ...
  9.     final def run(): Int = {
  10.         ... ...
  11.         if (isClusterMode) {
  12.             runDriver()
  13.         } else {
  14.             runExecutorLauncher()
  15.         }
  16.         ... ...
  17.     }
  18.  
  19.     private def runDriver(): Unit = {
  20.         addAmIpFilter(None, System.getenv(ApplicationConstants.APPLICATION_WEB_PROXY_BASE_ENV))
  21.         // 2根据输入参数启动Driver
  22.         userClassThread = startUserApplication()
  23.  
  24.         val totalWaitTime = sparkConf.get(AM_MAX_WAIT_TIME)
  25.         
     
  26.         try {
  27.             // 3等待初始化完毕
  28.             val sc = ThreadUtils.awaitResult(sparkContextPromise.future,
  29.                 Duration(totalWaitTime, TimeUnit.MILLISECONDS))
  30.            // sparkcontext初始化完毕
  31.             if (sc != null) {
  32.                 val rpcEnv = sc.env.rpcEnv
  33.  
  34.                 val userConf = sc.getConf
  35.                 val host = userConf.get(DRIVER_HOST_ADDRESS)
  36.                 val port = userConf.get(DRIVER_PORT)
  37.                 // 4 RM注册自己(AM)
  38.                 registerAM(host, port, userConf, sc.ui.map(_.webUrl), appAttemptId)
  39.  
  40.                 val driverRef = rpcEnv.setupEndpointRef(
  41.                 RpcAddress(host, port),
  42.                 YarnSchedulerBackend.ENDPOINT_NAME)
  43.                 // 5获取RM返回的可用资源列表
  44.                 createAllocator(driverRef, userConf, rpcEnv, appAttemptId, distCacheConf)
  45.             } else {
  46.                 ... ...
  47.             }
  48.             resumeDriver()
  49.             userClassThread.join()
  50.         } catch {
  51.             ... ...
  52.         } finally {
  53.             resumeDriver()
  54.         }
  55.     }
  56.  

ApplicationMaster.scala

  1. private def startUserApplication(): Thread = {
  2. ... ...
  3. // args.userClass来源于ApplicationMasterArguments.scala
  4.     val mainMethod = userClassLoader.loadClass(args.userClass)
  5.     .getMethod("main", classOf[Array[String]])
  6.     ... ...
  7.     val userThread = new Thread {
  8.         override def run(): Unit = {
  9.             ... ...
  10.             if (!Modifier.isStatic(mainMethod.getModifiers)) {
  11.                 logError(s"Could not find static main method in object ${args.userClass}")
  12.                 finish(FinalApplicationStatus.FAILED, ApplicationMaster.EXIT_EXCEPTION_USER_CLASS)
  13.             } else {
  14.                 mainMethod.invoke(null, userArgs.toArray)
  15.                 finish(FinalApplicationStatus.SUCCEEDED, ApplicationMaster.EXIT_SUCCESS)
  16.                 logDebug("Done running user class")
  17.             }  
  18.             ... ...  
  19.         }  
  20.     }
  21.     userThread.setContextClassLoader(userClassLoader)
  22.     userThread.setName("Driver")
  23.     userThread.start()
  24.     userThread
  25. }

向RM注册AM

  1. private def registerAM(
  2.     host: String,
  3.     port: Int,
  4.     _sparkConf: SparkConf,
  5.     uiAddress: Option[String],
  6.     appAttempt: ApplicationAttemptId): Unit = {
  7. … …
  8.  
  9.     client.register(host, port, yarnConf, _sparkConf, uiAddress, historyAddress)
  10.     registered = true
  11. }

获取RM返回可以资源列表

ApplicationMaster.scala

  1. private def createAllocator(
  2.     driverRef: RpcEndpointRef,
  3.     _sparkConf: SparkConf,
  4.     rpcEnv: RpcEnv,
  5.     appAttemptId: ApplicationAttemptId,
  6.     distCacheConf: SparkConf): Unit = {
  7.     
     
  8.     ... ...
  9.     // 申请资源 获得资源
  10.     allocator = client.createAllocator(
  11.     yarnConf,
  12.     _sparkConf,
  13.     appAttemptId,
  14.     driverUrl,
  15.     driverRef,
  16.     securityMgr,
  17.     localResources)
  18.  
  19.     ... ...
  20.     // 处理资源结果,启动Executor
  21.     allocator.allocateResources()
  22.     ... ...
  23. }

YarnAllocator.scala

  1. def allocateResources(): Unit = synchronized {
  2.     val progressIndicator = 0.1f
  3.  
  4.     val allocateResponse = amClient.allocate(progressIndicator)
  5.     // 获取可分配资源
  6.     val allocatedContainers = allocateResponse.getAllocatedContainers()
  7.     allocatorBlacklistTracker.setNumClusterNodes(allocateResponse.getNumClusterNodes)
  8.     // 可分配的资源大于0
  9.     if (allocatedContainers.size > 0) {
  10.         ......
  11.         // 分配规则
  12.         handleAllocatedContainers(allocatedContainers.asScala)
  13.     }
  14.     ... ...
  15. }
  16.  
  17. def handleAllocatedContainers(allocatedContainers: Seq[Container]): Unit = {
  18.     val containersToUse = new ArrayBuffer[Container](allocatedContainers.size)
  19.  
  20.     // 分配在同一台主机上资源
  21.     val remainingAfterHostMatches = new ArrayBuffer[Container]
  22.     for (allocatedContainer <- allocatedContainers) {
  23.         ... ...
  24.     }
  25.  
  26.     // 分配同一个机架上资源
  27.     val remainingAfterRackMatches = new ArrayBuffer[Container]
  28.     if (remainingAfterHostMatches.nonEmpty) {
  29.         ... ...
  30.     }
  31.  
  32.     // 分配既不是本地节点也不是机架本地的剩余部分
  33.     val remainingAfterOffRackMatches = new ArrayBuffer[Container]
  34.     for (allocatedContainer <- remainingAfterRackMatches) {
  35.         ... ...
  36. }
  37.  
  38.     // 运行已分配容器
  39.     runAllocatedContainers(containersToUse)
  40. }

根据可用资源创建NMClient

YarnAllocator.scala

  1. private def runAllocatedContainers(containersToUse: ArrayBuffer[Container]): Unit = {
  2.  
  3.     for (container <- containersToUse) {
  4.         ... ...
  5.         if (runningExecutors.size() < targetNumExecutors) {
  6.             numExecutorsStarting.incrementAndGet()
  7.             if (launchContainers) {
  8.                 launcherPool.execute(() => {
  9.                     try {
  10.                         new ExecutorRunnable(
  11.                             … …
  12.                         ).run()
  13.                         updateInternalState()
  14.                     } catch {
  15.                         ... ...
  16.                     }
  17.                 })
  18.             } else {
  19.                 // For test only
  20.                 updateInternalState()
  21.             }
  22.         } else {
  23.             … …
  24.         }
  25.     }
  26. }

ExecutorRunnable.scala

  1. private[yarn] class ExecutorRunnable(... ...) extends Logging {
  2.     var rpc: YarnRPC = YarnRPC.create(conf)
  3.     var nmClient: NMClient = _
  4.     
     
  5.     def run(): Unit = {
  6.         logDebug("Starting Executor Container")
  7.         nmClient = NMClient.createNMClient()
  8.         nmClient.init(conf)
  9.         nmClient.start()
  10.         startContainer()
  11.     }
  12.     ... ...
  13.     def startContainer(): java.util.Map[String, ByteBuffer] = {
  14.         ... ...
  15.         // 准备命令,封装到ctx环境中
  16.         val commands = prepareCommand()
  17.         ctx.setCommands(commands.asJava)
  18.         ... ...
  19.  
  20.         // 向指定的NM启动容器对象
  21.         try {
  22.             nmClient.startContainer(container.get, ctx)
  23.         } catch {
  24.             ... ...
  25.         }
  26.     }
  27.  
  28.     private def prepareCommand(): List[String] = {
  29.         ... ...
  30.         YarnSparkHadoopUtil.addOutOfMemoryErrorArgument(javaOpts)
  31.         val commands = prefixEnv ++
  32.         Seq(Environment.JAVA_HOME.$$() + "/bin/java", "-server") ++
  33.         javaOpts ++
  34.         Seq("org.apache.spark.executor.YarnCoarseGrainedExecutorBackend",
  35.             "--driver-url", masterAddress,
  36.             "--executor-id", executorId,
  37.             "--hostname", hostname,
  38.             "--cores", executorCores.toString,
  39.             "--app-id", appId,
  40.             "--resourceProfileId", resourceProfileId.toString) ++
  41.         ... ...
  42.     }
  43. }

Spark组件通信

Spark中通信框架的发展

  1. Spark早期版本中采用Akka作为内部通信部件。
  2. Spark1.3中引入Netty通信框架,为了解决Shuffle的大数据传输问题使用
  3. Spark1.6中Akka和Netty可以配置使用。Netty完全实现了Akka在Spark中的功能。
  4. Spark2.x系列中,Spark抛弃Akka,使用Netty。

那么Netty为什么可以取代Akka?

首先不容置疑的是Akka可以做到的,Netty也可以做到,但是Netty可以做到,Akka却无法做到,原因是什么?

在软件栈中,Akka相比Netty要高级一点,它专门针对RPC做了很多事情,而Netty相比更加基础一点,可以为不同的应用层通信协议(RPC,FTP,HTTP等)提供支持,在早期的Akka版本,底层的NIO通信就是用的Netty;其次一个优雅的工程师是不会允许一个系统中容纳两套通信框架,恶心!最后,虽然Netty没有Akka协程级的性能优势,但是Netty内部高效的Reactor线程模型,无锁化的串行设计,高效的序列化,零拷贝,内存池等特性也保证了Netty不会存在性能问题。

Endpoint有1个InBox和N个OutBox(N>=1,N取决于当前Endpoint与多少其他的Endpoint进行通信,一个与其通讯的其他Endpoint对应一个OutBox),Endpoint接收到的消息被写入InBox,发送出去的消息写入OutBox并被发送到其他Endpoint的InBox中。

三种通信方式 BIO NIO AIO

1)三种通信模式

BIO:阻塞式IO

NIO:非阻塞式IO

AIO:异步非阻塞式IO

Spark底层采用Netty

Netty:支持NIO和Epoll模式

默认采用NIO

2)举例说明:

比如去饭店吃饭,老板说你前面有4个人,需要等一会:

(1)那你在桌子前一直等着,就是阻塞式IO——BIO。

(2)如果你和老板说,饭先做着,我先去打会篮球。在打篮球的过程中你时不时的回来看一下饭是否做好,就是非阻塞式IO——NIO。

(3)先给老板说,我去打篮球,一个小时后给我送到指定位置,就是异步非阻塞式——AIO。

3)注意:

Linux对AIO支持的不够好,Windows支持AIO很好

Linux采用Epoll方式模仿AIO操作

Spark底层通信原理

  1. RpcEndpoint:RPC通信终端。Spark针对每个节点(Client/Master/Worker)都称之为一个RPC终端,且都实现RpcEndpoint接口,内部根据不同端点的需求,设计不同的消息和不同的业务处理,如果需要发送(询问)则调用Dispatcher。在Spark中,所有的终端都存在生命周期:
    1. Constructor =》onStart =》receive* =》onStop
  2. RpcEnv:RPC上下文环境,每个RPC终端运行时依赖的上下文环境称为RpcEnv;在当前Spark版本中使用的NettyRpcEnv
  3. Dispatcher:消息调度(分发)器,针对于RPC终端需要发送远程消息或者从远程RPC接收到的消息,分发至对应的指令收件箱(发件箱)。如果指令接收方是自己则存入收件箱,如果指令接收方不是自己,则放入发件箱;
  4. Inbox:指令消息收件箱。一个本地RpcEndpoint对应一个收件箱,Dispatcher在每次向Inbox存入消息时,都将对应EndpointData加入内部ReceiverQueue中,另外Dispatcher创建时会启动一个单独线程进行轮询ReceiverQueue,进行收件箱消息消费;
  5. RpcEndpointRef:RpcEndpointRef是对远程RpcEndpoint的一个引用。当我们需要向一个具体的RpcEndpoint发送消息时,一般我们需要获取到该RpcEndpoint的引用,然后通过该应用发送消息。
  6. OutBox:指令消息发件箱。对于当前RpcEndpoint来说,一个目标RpcEndpoint对应一个发件箱,如果向多个目标RpcEndpoint发送信息,则有多个OutBox。当消息放入Outbox后,紧接着通过TransportClient将消息发送出去。消息放入发件箱以及发送过程是在同一个线程中进行;
  7. RpcAddress:表示远程的RpcEndpointRef的地址,Host + Port。
  8. TransportClient:Netty通信客户端,一个OutBox对应一个TransportClient,TransportClient不断轮询OutBox,根据OutBox消息的receiver信息,请求对应的远程TransportServer;
  9. TransportServer:Netty通信服务端,一个RpcEndpoint对应一个TransportServer,接受远程消息后调用Dispatcher分发消息至对应收发件箱;

Executor通信终端

1)在IDEA中全局查找(ctrl + n)org.apache.spark.executor.YarnCoarseGrainedExecutorBackend,点击对应的伴生对象

2)YarnCoarseGrainedExecutorBackend.scala 继承CoarseGrainedExecutorBackend继承RpcEndpoint

  1. // constructor -> onStart -> receive* -> onStop
  2. private[spark] trait RpcEndpoint {
  3.  
  4.   val rpcEnv: RpcEnv
  5.  
  6.   final def self: RpcEndpointRef = {
  7.     require(rpcEnv != null, "rpcEnv has not been initialized")
  8.     rpcEnv.endpointRef(this)
  9.   }
  10.  
  11.   def receive: PartialFunction[Any, Unit] = {
  12.     case _ => throw new SparkException(self + " does not implement 'receive'")
  13.   }
  14.   
     
  15.   def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
  16.     case _ => context.sendFailure(new SparkException(self + " won't reply anything"))
  17.   }
  18.  
  19.   def onStart(): Unit = {
  20.     // By default, do nothing.
  21.   }
  22.  
  23.   def onStop(): Unit = {
  24.     // By default, do nothing.
  25.   }
  26. }
  27.  
  28. private[spark] abstract class RpcEndpointRef(conf: SparkConf)
  29.   extends Serializable with Logging {
  30.   ... ...
  31.   def send(message: Any): Unit
  32.   def ask[T: ClassTag](message: Any, timeout: RpcTimeout): Future[T]
  33.   ... ...
  34. }

Driver通信终端

ExecutorBackend发送向Driver发送请求后,Driver开始接收消息。全局查找(ctrl + n)SparkContext类

SparkContext.scala

  1. class SparkContext(config: SparkConf) extends Logging {
  2.     ... ...
  3.     private var _schedulerBackend: SchedulerBackend = _
  4.     ... ...
  5. }

点击SchedulerBackend进入SchedulerBackend.scala,查找实现类(ctrl+h),找到CoarseGrainedSchedulerBackend.scala,在该类内部创建DriverEndpoint对象。

  1. private[spark]
  2. class CoarseGrainedSchedulerBackend(scheduler: TaskSchedulerImpl, val rpcEnv: RpcEnv)
  3.     extends ExecutorAllocationClient with SchedulerBackend with Logging {
  4.   
     
  5.     class DriverEndpoint extends IsolatedRpcEndpoint with Logging {
  6.         override def receive: PartialFunction[Any, Unit] = {
  7.             ... ...
  8.             // 接收注册成功后的消息
  9.             case LaunchedExecutor(executorId) =>
  10.             executorDataMap.get(executorId).foreach { data =>
  11.                 data.freeCores = data.totalCores
  12.             }
  13.             makeOffers(executorId)
  14.         }
  15.         
     
  16.         // 接收ask消息,并回复
  17.         override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
  18.  
  19.           case RegisterExecutor(executorId, executorRef, hostname, cores, logUrls,
  20.               attributes, resources, resourceProfileId) =>
  21.             ... ...
  22.             context.reply(true)
  23.             ... ...
  24.         }
  25.         ... ...
  26.     }
  27.     
     
  28.     val driverEndpoint = rpcEnv.setupEndpoint(ENDPOINT_NAME, createDriverEndpoint())
  29.     
     
  30.     protected def createDriverEndpoint(): DriverEndpoint = new DriverEndpoint()
  31. }

DriverEndpoint继承IsolatedRpcEndpoint继承RpcEndpoint

  1. // constructor -> onStart -> receive* -> onStop
  2. private[spark] trait RpcEndpoint {
  3.  
  4.   val rpcEnv: RpcEnv
  5.  
  6.   final def self: RpcEndpointRef = {
  7.     require(rpcEnv != null, "rpcEnv has not been initialized")
  8.     rpcEnv.endpointRef(this)
  9.   }
  10.  
  11.   def receive: PartialFunction[Any, Unit] = {
  12.     case _ => throw new SparkException(self + " does not implement 'receive'")
  13.   }
  14.   
     
  15.   def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
  16.     case _ => context.sendFailure(new SparkException(self + " won't reply anything"))
  17.   }
  18.  
  19.   def onStart(): Unit = {
  20.     // By default, do nothing.
  21.   }
  22.  
  23.   def onStop(): Unit = {
  24.     // By default, do nothing.
  25.   }
  26. }
  27.  
  28. private[spark] abstract class RpcEndpointRef(conf: SparkConf)
  29.   extends Serializable with Logging {
  30.   ... ...
  31.   def send(message: Any): Unit
  32.   def ask[T: ClassTag](message: Any, timeout: RpcTimeout): Future[T]
  33.   ... ...
  34. }

Executor通信环境准备

创建RPC通信环境

1)在IDEA中全局查找(ctrl + n)org.apache.spark.executor.YarnCoarseGrainedExecutorBackend,点击对应的伴生对象

2)运行CoarseGrainedExecutorBackend

YarnCoarseGrainedExecutorBackend.scala

  1. private[spark] object YarnCoarseGrainedExecutorBackend extends Logging {
  2.  
  3.     def main(args: Array[String]): Unit = {
  4.         val createFn: (RpcEnv, CoarseGrainedExecutorBackend.Arguments, SparkEnv, ResourceProfile) =>
  5.         CoarseGrainedExecutorBackend = { case (rpcEnv, arguments, env, resourceProfile) =>
  6.         new YarnCoarseGrainedExecutorBackend(rpcEnv, arguments.driverUrl, arguments.executorId,
  7.             arguments.bindAddress, arguments.hostname, arguments.cores, arguments.userClassPath, env,
  8.             arguments.resourcesFileOpt, resourceProfile)
  9.         }
  10.         val backendArgs = CoarseGrainedExecutorBackend.parseArguments(args,
  11.         this.getClass.getCanonicalName.stripSuffix("$"))
  12.         CoarseGrainedExecutorBackend.run(backendArgs, createFn)
  13.         System.exit(0)
  14.     }
  15. }

CoarseGrainedExecutorBackend.scala

  1. def run(
  2.     arguments: Arguments,
  3.     backendCreateFn: (RpcEnv, Arguments, SparkEnv, ResourceProfile) =>
  4.         CoarseGrainedExecutorBackend): Unit = {
  5.  
  6.     SparkHadoopUtil.get.runAsSparkUser { () =>
  7.  
  8.         // Bootstrap to fetch the driver's Spark properties.
  9.         val executorConf = new SparkConf
  10.         val fetcher = RpcEnv.create(
  11.             "driverPropsFetcher",
  12.             arguments.bindAddress,
  13.             arguments.hostname,
  14.             -1,
  15.             executorConf,
  16.             new SecurityManager(executorConf),
  17.             numUsableCores = 0,
  18.             clientMode = true)
  19.         … …
  20.         driverConf.set(EXECUTOR_ID, arguments.executorId)
  21.         val env = SparkEnv.createExecutorEnv(driverConf, arguments.executorId, arguments.bindAddress,
  22.             arguments.hostname, arguments.cores, cfg.ioEncryptionKey, isLocal = false)
  23.  
  24.         env.rpcEnv.setupEndpoint("Executor",
  25.             backendCreateFn(env.rpcEnv, arguments, env, cfg.resourceProfile))
  26.         arguments.workerUrl.foreach { url =>
  27.             env.rpcEnv.setupEndpoint("WorkerWatcher", new WorkerWatcher(env.rpcEnv, url))
  28.         }
  29.         env.rpcEnv.awaitTermination()
  30.     }
  31. }

3)点击create,进入RpcEnv.Scala

  1. def create(
  2.     name: String,
  3.     bindAddress: String,
  4.     advertiseAddress: String,
  5.     port: Int,
  6.     conf: SparkConf,
  7.     securityManager: SecurityManager,
  8.     numUsableCores: Int,
  9.     clientMode: Boolean): RpcEnv = {
  10.     val config = RpcEnvConfig(conf, name, bindAddress, advertiseAddress, port, securityManager,
  11.       numUsableCores, clientMode)
  12.     new NettyRpcEnvFactory().create(config)
  13. }

NettyRpcEnv.scala

  1. private[rpc] class NettyRpcEnvFactory extends RpcEnvFactory with Logging {
  2.  
  3.     def create(config: RpcEnvConfig): RpcEnv = {
  4.         ... ...
  5.         val nettyEnv =
  6.             new NettyRpcEnv(sparkConf, javaSerializerInstance, config.advertiseAddress,
  7.                 config.securityManager, config.numUsableCores)
  8.         if (!config.clientMode) {
  9.             val startNettyRpcEnv: Int => (NettyRpcEnv, Int) = { actualPort =>
  10.                 nettyEnv.startServer(config.bindAddress, actualPort)
  11.                 (nettyEnv, nettyEnv.address.port)
  12.             }
  13.             try {
  14.                 Utils.startServiceOnPort(config.port, startNettyRpcEnv, sparkConf, config.name)._1
  15.             } catch {
  16.                 case NonFatal(e) =>
  17.                 nettyEnv.shutdown()
  18.                 throw e
  19.             }
  20.         }
  21.         nettyEnv
  22.     }
  23. }

创建多个发件箱

NettyRpcEnv.scala

  1. NettyRpcEnv.scala 
  2. private[netty] class NettyRpcEnv(
  3.     val conf: SparkConf,
  4.     javaSerializerInstance: JavaSerializerInstance,
  5.     host: String,
  6.     securityManager: SecurityManager,
  7.     numUsableCores: Int) extends RpcEnv(conf) with Logging {
  8.     ... ...
  9.     private val outboxes = new ConcurrentHashMap[RpcAddress, Outbox]()
  10.     ... ...
  11. }

启动TransportServer

NettyRpcEnv.scala

  1. def startServer(bindAddress: String, port: Int): Unit = {
  2.     ... ...
  3.     server = transportContext.createServer(bindAddress, port, bootstraps)
  4.     dispatcher.registerRpcEndpoint(
  5.         RpcEndpointVerifier.NAME, new RpcEndpointVerifier(this, dispatcher))
  6. }

TransportContext.scala

  1. public TransportServer createServer(
  2.     String host, int port, List<TransportServerBootstrap> bootstraps) {
  3.     return new TransportServer(this, host, port, rpcHandler, bootstraps);
  4. }

TransportServer.java

  1. public TransportServer(
  2.     TransportContext context,
  3.     String hostToBind,
  4.     int portToBind,
  5.     RpcHandler appRpcHandler,
  6.     List<TransportServerBootstrap> bootstraps) {
  7.     ... ...
  8.     init(hostToBind, portToBind);
  9.     ... ...
  10. }
  11.  
  12. private void init(String hostToBind, int portToBind) {
  13.     // 默认是NIO模式
  14.     IOMode ioMode = IOMode.valueOf(conf.ioMode());
  15.     
     
  16.     EventLoopGroup bossGroup = NettyUtils.createEventLoop(ioMode, 1,
  17.         conf.getModuleName() + "-boss");
  18.     EventLoopGroup workerGroup =  NettyUtils.createEventLoop(ioMode, conf.serverThreads(), conf.getModuleName() + "-server");
  19.     
     
  20.     bootstrap = new ServerBootstrap()
  21.         .group(bossGroup, workerGroup)
  22.         .channel(NettyUtils.getServerChannelClass(ioMode))
  23.         .option(ChannelOption.ALLOCATOR, pooledAllocator)
  24.         .option(ChannelOption.SO_REUSEADDR, !SystemUtils.IS_OS_WINDOWS)
  25.         .childOption(ChannelOption.ALLOCATOR, pooledAllocator);
  26.     ... ...
  27. }

NettyUtils.java

  1. public static Class<? extends ServerChannel> getServerChannelClass(IOMode mode) {
  2.     switch (mode) {
  3.         case NIO:
  4.             return NioServerSocketChannel.class;
  5.         case EPOLL:
  6.             return EpollServerSocketChannel.class;
  7.         default:
  8.             throw new IllegalArgumentException("Unknown io mode: " + mode);
  9.     }
  10. }

注册通信终端RpcEndpoint

NettyRpcEnv.scala

  1. def startServer(bindAddress: String, port: Int): Unit = {
  2.     ... ...
  3.     server = transportContext.createServer(bindAddress, port, bootstraps)
  4.     dispatcher.registerRpcEndpoint(
  5.         RpcEndpointVerifier.NAME, new RpcEndpointVerifier(this, dispatcher))
  6. }

创建TransportClient

Dispatcher.scala

  1. def registerRpcEndpoint(name: String, endpoint: RpcEndpoint): NettyRpcEndpointRef = {
  2.     ... ...
  3.     val endpointRef = new NettyRpcEndpointRef(nettyEnv.conf, addr, nettyEnv)
  4.     ... ...
  5. }
  6.  
  7. private[netty] class NettyRpcEndpointRef(... ...) extends RpcEndpointRef(conf) {
  8.     ... ...
  9.     @transient @volatile var client: TransportClient = _
  10.     // 创建TransportClient
  11.     private[netty] def createClient(address: RpcAddress): TransportClient = {
  12.       clientFactory.createClient(address.host, address.port)
  13.     }
  14.     
     
  15.     private val clientFactory = transportContext.createClientFactory(createClientBootstraps())
  16.     ... ...
  17. }

收发邮件箱

1)接收邮件箱1个

Dispatcher.scala

  1. def registerRpcEndpoint(name: String, endpoint: RpcEndpoint): NettyRpcEndpointRef = {
  2.         ... ...
  3.         var messageLoop: MessageLoop = null
  4.         try {
  5.             messageLoop = endpoint match {
  6.             case e: IsolatedRpcEndpoint =>
  7.                 new DedicatedMessageLoop(name, e, this)
  8.             case _ =>
  9.                 sharedLoop.register(name, endpoint)
  10.                 sharedLoop
  11.             }
  12.             endpoints.put(name, messageLoop)
  13.         } catch {
  14.             ... ...
  15.         }
  16.     }
  17.     endpointRef
  18. }

DedicatedMessageLoop.scala

  1. private class DedicatedMessageLoop(
  2.     name: String,
  3.     endpoint: IsolatedRpcEndpoint,
  4.     dispatcher: Dispatcher)
  5.   extends MessageLoop(dispatcher) {
  6.  
  7.     private val inbox = new Inbox(name, endpoint)
  8.     … …
  9. }

Inbox.scala

  1. private[netty] class Inbox(val endpointName: String, val endpoint: RpcEndpoint)
  2.   extends Logging {
  3.     ... ...
  4.     inbox.synchronized {
  5.         messages.add(OnStart)
  6.     }
  7.     ... ...
  8. }

Executor注册

CoarseGrainedExecutorBackend.scala

  1. // RPC生命周期: constructor -> onStart -> receive* -> onStop
  2. private[spark] class CoarseGrainedExecutorBackend(... ...)
  3.   extends IsolatedRpcEndpoint with ExecutorBackend with Logging {
  4.     ... ...
  5.     override def onStart(): Unit = {
  6.         … …
  7.         rpcEnv.asyncSetupEndpointRefByURI(driverUrl).flatMap { ref =>
  8.         // This is a very fast action so we can use "ThreadUtils.sameThread"
  9.         driver = Some(ref)
  10. // 1向Driver注册自己
  11.         ref.ask[Boolean](RegisterExecutor(executorId, self, hostname, cores, extractLogUrls, extractAttributes, _resources, resourceProfile.id))
  12.         }(ThreadUtils.sameThread).onComplete {
  13. // 2接收Driver返回成功的消息,并给自己发送注册成功消息
  14.         case Success(_) =>
  15.             self.send(RegisteredExecutor)
  16.         case Failure(e) =>
  17.             exitExecutor(1, s"Cannot register with driver: $driverUrl", e, notifyDriver = false)
  18.         }(ThreadUtils.sameThread)
  19.     }
  20.     ... ...
  21.  
  22.     override def receive: PartialFunction[Any, Unit] = {
  23. // 3收到注册成功的消息后,创建Executor,并启动Executor
  24.         case RegisteredExecutor =>
  25.         try {
  26.             // 创建Executor
  27.             executor = new Executor(executorId, hostname, env, userClassPath, isLocal = false, resources = _resources)
  28.             driver.get.send(LaunchedExecutor(executorId))
  29.         } catch {
  30.             case NonFatal(e) =>
  31.             exitExecutor(1, "Unable to create executor due to " + e.getMessage, e)
  32.         }
  33.         ... ...
  34.     }
  35. }

Driver接收消息并应答

ExecutorBackend发送向Driver发送请求后,Driver开始接收消息。全局查找(ctrl + n)SparkContext类

SparkContext.scala

  1. class SparkContext(config: SparkConf) extends Logging {
  2.     ... ...
  3.     private var _schedulerBackend: SchedulerBackend = _
  4.     ... ...
  5. }

点击SchedulerBackend进入SchedulerBackend.scala,查找实现类(ctrl+h),找到CoarseGrainedSchedulerBackend.scala

  1. private[spark]
  2. class CoarseGrainedSchedulerBackend(scheduler: TaskSchedulerImpl, val rpcEnv: RpcEnv)
  3.     extends ExecutorAllocationClient with SchedulerBackend with Logging {
  4.   
     
  5.     class DriverEndpoint extends IsolatedRpcEndpoint with Logging {
  6.         override def receive: PartialFunction[Any, Unit] = {
  7.             ... ...
  8.             // 接收注册成功后的消息
  9.             case LaunchedExecutor(executorId) =>
  10.             executorDataMap.get(executorId).foreach { data =>
  11.                 data.freeCores = data.totalCores
  12.             }
  13.             makeOffers(executorId)
  14.         }
  15.         
     
  16.         // 接收ask消息,并回复
  17.         override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {
  18.  
  19.           case RegisterExecutor(executorId, executorRef, hostname, cores, logUrls,
  20.               attributes, resources, resourceProfileId) =>
  21.             ... ...
  22.             context.reply(true)
  23.             ... ...
  24.         }
  25.         ... ...
  26.     }
  27.     
     
  28.     val driverEndpoint = rpcEnv.setupEndpoint(ENDPOINT_NAME, createDriverEndpoint())
  29.     
     
  30.     protected def createDriverEndpoint(): DriverEndpoint = new DriverEndpoint()
  31. }

Executor执行代码

SparkContext初始化完毕,通知执行后续代码

1)进入到ApplicationMaster

ApplicationMaster.scala

  1. private[spark] class ApplicationMaster(
  2.     args: ApplicationMasterArguments,
  3.     sparkConf: SparkConf,
  4.     yarnConf: YarnConfiguration) extends Logging {
  5.     
     
  6.     private def runDriver(): Unit = {
  7.         addAmIpFilter(None, System.getenv(ApplicationConstants.APPLICATION_WEB_PROXY_BASE_ENV))
  8.         userClassThread = startUserApplication()
  9.     
     
  10.         val totalWaitTime = sparkConf.get(AM_MAX_WAIT_TIME)
  11.         try {
  12.             val sc = ThreadUtils.awaitResult(sparkContextPromise.future,
  13.                 Duration(totalWaitTime, TimeUnit.MILLISECONDS))
  14.             if (sc != null) {
  15.                 val rpcEnv = sc.env.rpcEnv
  16.         
     
  17.                 val userConf = sc.getConf
  18.                 val host = userConf.get(DRIVER_HOST_ADDRESS)
  19.                 val port = userConf.get(DRIVER_PORT)
  20.                 registerAM(host, port, userConf, sc.ui.map(_.webUrl), appAttemptId)
  21.         
     
  22.                 val driverRef = rpcEnv.setupEndpointRef(
  23.                 RpcAddress(host, port),
  24.                 YarnSchedulerBackend.ENDPOINT_NAME)
  25.                 createAllocator(driverRef, userConf, rpcEnv, appAttemptId, distCacheConf)
  26.             } else {
  27.                 … …
  28.             }
  29.             // 执行程序
  30.             resumeDriver()
  31.             userClassThread.join()
  32.         } catch {
  33.             ... ...
  34.         } finally {
  35.             resumeDriver()
  36.         }
  37.     }
  38.     ... ...
  39.     private def resumeDriver(): Unit = {
  40.         sparkContextPromise.synchronized {
  41.             sparkContextPromise.notify()
  42.         }
  43.     }
  44. }

接收代码继续执行消息

在SparkContext.scala文件中查找_taskScheduler.postStartHook(),点击postStartHook,查找实现类(ctrl + h)

  1. private[spark] class YarnClusterScheduler(sc: SparkContext) extends YarnScheduler(sc) {
  2.  
  3.     logInfo("Created YarnClusterScheduler")
  4.     
     
  5.     override def postStartHook(): Unit = {
  6.         ApplicationMaster.sparkContextInitialized(sc)
  7.         super.postStartHook()
  8.         logInfo("YarnClusterScheduler.postStartHook done")
  9.     }
  10. }

点击super.postStartHook()

TaskSchedulerImpl.scala

  1. override def postStartHook(): Unit = {
  2.     waitBackendReady()
  3. }
  4.  
  5. private def waitBackendReady(): Unit = {
  6.     if (backend.isReady) {
  7.         return
  8.     }
  9.     while (!backend.isReady) { 
  10.         if (sc.stopped.get) {
  11.             throw new IllegalStateException("Spark context stopped while waiting for backend")
  12.         }
  13.         synchronized {
  14.             this.wait(100)
  15.         }
  16.     }
  17. }

任务的执行

概述

任务切分和任务调度原理

Stage任务划分

Task任务调度执行

本地化调度

任务分配原则:根据每个Task的优先位置,确定Task的Locality(本地化)级别,本地化一共有五种,优先级由高到低顺序:

移动数据不如移动计算。

名称

解析

PROCESS_LOCAL

进程本地化,task和数据在同一个Executor中,性能最好。

NODE_LOCAL

节点本地化,task和数据在同一个节点中,但是task和数据不在同一个Executor中,数据需要在进程间进行传输。

RACK_LOCAL

机架本地化,task和数据在同一个机架的两个节点上,数据需要通过网络在节点之间进行传输。

NO_PREF

对于task来说,从哪里获取都一样,没有好坏之分。

ANY

task和数据可以在集群的任何地方,而且不在一个机架中,性能最差。

失败重试与黑名单机制

除了选择合适的Task调度运行外,还需要监控Task的执行状态,前面也提到,与外部打交道的是SchedulerBackend,Task被提交到Executor启动执行后,Executor会将执行状态上报给SchedulerBackend,SchedulerBackend则告诉TaskScheduler,TaskScheduler找到该Task对应的TaskSetManager,并通知到该TaskSetManager,这样TaskSetManager就知道Task的失败与成功状态,对于失败的Task,会记录它失败的次数,如果失败次数还没有超过最大重试次数,那么就把它放回待调度的Task池子中,否则整个Application失败。

在记录Task失败次数过程中,会记录它上一次失败所在的Executor Id和Host,这样下次再调度这个Task时,会使用黑名单机制,避免它被调度到上一次失败的节点上,起到一定的容错作用。黑名单记录Task上一次失败所在的Executor Id和Host,以及其对应的"拉黑"时间,"拉黑"时间是指这段时间内不要再往这个节点上调度这个Task了。

阶段的划分

0)在WordCount程序中查看源码

  1. import org.apache.spark.rdd.RDD
  2. import org.apache.spark.{SparkConf, SparkContext}
  3.  
  4. object WordCount {
  5.  
  6.     def main(args: Array[String]): Unit = {
  7.         val conf: SparkConf = new SparkConf().setAppName("WC").setMaster("local[*]")
  8.         val sc: SparkContext = new SparkContext(conf)
  9.  
  10.         // 2 读取数据 hello atguigu spark spark
  11.         val lineRDD: RDD[String] = sc.textFile("input")
  12.  
  13.         // 3 一行变多行
  14.         val wordRDD: RDD[String] = lineRDD.flatMap((x: String) => x.split(" "))
  15.         // 4 变换结构  一行变一行
  16.         val wordToOneRDD: RDD[(String, Int)] = wordRDD.map((x: String) => (x, 1))
  17.         // 5  聚合key相同的单词
  18.         val wordToSumRDD: RDD[(String, Int)] = wordToOneRDD.reduceByKey((v1, v2) => v1 + v2)
  19.         // 6 收集打印
  20.         wordToSumRDD.collect().foreach(println)
  21.  
  22.         //7 关闭资源
  23.         sc.stop()
  24.     }
  25. }

1)在WordCount代码中点击collect

RDD.scala

  1. def collect(): Array[T] = withScope {
  2.     val results = sc.runJob(this, (iter: Iterator[T]) => iter.toArray)
  3.     Array.concat(results: _*)
  4. }

SparkContext.scala

  1. def runJob[T, U: ClassTag](rdd: RDD[T], func: Iterator[T] => U): Array[U] = {
  2.     runJob(rdd, func, 0 until rdd.partitions.length)
  3. }
  4.  
  5. def runJob[T, U: ClassTag](
  6.     rdd: RDD[T],
  7.     func: Iterator[T] => U,
  8.     partitions: Seq[Int]): Array[U] = {
  9.     val cleanedFunc = clean(func)
  10.     runJob(rdd, (ctx: TaskContext, it: Iterator[T]) => cleanedFunc(it), partitions)
  11. }
  12.  
  13. def runJob[T, U: ClassTag](
  14.     rdd: RDD[T],
  15.     func: (TaskContext, Iterator[T]) => U,
  16.     partitions: Seq[Int]): Array[U] = {
  17.     val results = new Array[U](partitions.size)
  18.     runJob[T, U](rdd, func, partitions, (index, res) => results(index) = res)
  19.     results
  20. }
  21.  
  22. def runJob[T, U: ClassTag](
  23.     rdd: RDD[T],
  24.     func: (TaskContext, Iterator[T]) => U,
  25.     partitions: Seq[Int],
  26.     resultHandler: (Int, U) => Unit): Unit = {
  27.     ... ...
  28.     dagScheduler.runJob(rdd, cleanedFunc, partitions, callSite, resultHandler, localProperties.get)
  29.     ... ...
  30. }

DAGScheduler.scala

  1. def runJob[T, U](
  2.     rdd: RDD[T],
  3.     func: (TaskContext, Iterator[T]) => U,
  4.     partitions: Seq[Int],
  5.     callSite: CallSite,
  6.     resultHandler: (Int, U) => Unit,
  7.     properties: Properties): Unit = {  
  8.     ... ... 
  9.     val waiter = submitJob(rdd, func, partitions, callSite, resultHandler, properties)
  10.     ... ...
  11. }
  12.  
  13. def submitJob[T, U](
  14.     rdd: RDD[T],
  15.     func: (TaskContext, Iterator[T]) => U,
  16.     partitions: Seq[Int],
  17.     callSite: CallSite,
  18.     resultHandler: (Int, U) => Unit,
  19.     properties: Properties): JobWaiter[U] = {
  20.     ... ...
  21.     val waiter = new JobWaiter[U](this, jobId, partitions.size, resultHandler)
  22.     eventProcessLoop.post(JobSubmitted(
  23.         jobId, rdd, func2, partitions.toArray, callSite, waiter,
  24.         Utils.cloneProperties(properties)))
  25.     waiter
  26. }

EventLoop.scala

  1. def post(event: E): Unit = {
  2.     if (!stopped.get) {
  3.         if (eventThread.isAlive) {
  4.             eventQueue.put(event)
  5.         } else {
  6.             ... ...
  7.         }
  8.     }
  9. }
  10.  
  11. private[spark] val eventThread = new Thread(name) {
  12.  
  13.     override def run(): Unit = {
  14.         while (!stopped.get) {
  15.             val event = eventQueue.take()
  16.             try {
  17.                 onReceive(event)
  18.             } catch {
  19.                 ... ...
  20.             }
  21.         }
  22.     }
  23. }

查找onReceive实现类(ctrl + h)

DAGScheduler.scala

  1. private[scheduler] class DAGSchedulerEventProcessLoop(dagScheduler: DAGScheduler)
  2.     extends EventLoop[DAGSchedulerEvent]("dag-scheduler-event-loop") with Logging {
  3.  
  4.     ... ...
  5.     override def onReceive(event: DAGSchedulerEvent): Unit = {
  6.         val timerContext = timer.time()
  7.         try {
  8.             doOnReceive(event)
  9.         } finally {
  10.             timerContext.stop()
  11.         }
  12.     }
  13.     
     
  14.     private def doOnReceive(event: DAGSchedulerEvent): Unit = event match {
  15.         case JobSubmitted(jobId, rdd, func, partitions, callSite, listener, properties) =>
  16.         dagScheduler.handleJobSubmitted(jobId, rdd, func, partitions, callSite, listener, properties)
  17.         ... ...
  18.     }
  19.     ... ...
  20.     private[scheduler] def handleJobSubmitted(jobId: Int,
  21.         finalRDD: RDD[_],
  22.         func: (TaskContext, Iterator[_]) => _,
  23.         partitions: Array[Int],
  24.         callSite: CallSite,
  25.         listener: JobListener,
  26.         properties: Properties): Unit = {
  27.           
     
  28.         var finalStage: ResultStage = null
  29.  
  30.         finalStage = createResultStage(finalRDD, func, partitions, jobId, callSite)
  31.         ... ...
  32.     }
  33.  
  34.     private def createResultStage(
  35.         rdd: RDD[_],
  36.         func: (TaskContext, Iterator[_]) => _,
  37.         partitions: Array[Int],
  38.         jobId: Int,
  39.         callSite: CallSite): ResultStage = {
  40.         … …
  41.         val parents = getOrCreateParentStages(rdd, jobId)
  42.         val id = nextStageId.getAndIncrement()
  43.         
     
  44.         val stage = new ResultStage(id, rdd, func, partitions, parents, jobId, callSite)
  45.         stageIdToStage(id) = stage
  46.         updateJobIdStageIdMaps(jobId, stage)
  47.         stage
  48.     }
  49.  
  50.     private def getOrCreateParentStages(rdd: RDD[_], firstJobId: Int): List[Stage] = {
  51.         getShuffleDependencies(rdd).map { shuffleDep =>
  52.             getOrCreateShuffleMapStage(shuffleDep, firstJobId)
  53.         }.toList
  54.     }
  55.  
  56.     private[scheduler] def getShuffleDependencies(
  57.         rdd: RDD[_]): HashSet[ShuffleDependency[_, _, _]] = {
  58.         
     
  59.             val parents = new HashSet[ShuffleDependency[_, _, _]]
  60.             val visited = new HashSet[RDD[_]]
  61.             val waitingForVisit = new ListBuffer[RDD[_]]
  62.             waitingForVisit += rdd
  63.             while (waitingForVisit.nonEmpty) {
  64.             val toVisit = waitingForVisit.remove(0)
  65.             
     
  66.             if (!visited(toVisit)) {
  67.                 visited += toVisit
  68.                 toVisit.dependencies.foreach {
  69.                 case shuffleDep: ShuffleDependency[_, _, _] =>
  70.                     parents += shuffleDep
  71.                 case dependency =>
  72.                     waitingForVisit.prepend(dependency.rdd)
  73.                 }
  74.             }
  75.         }
  76.         parents
  77.     }
  78.  
  79.     private def getOrCreateShuffleMapStage(
  80.         shuffleDep: ShuffleDependency[_, _, _],
  81.         firstJobId: Int): ShuffleMapStage = {
  82.         
     
  83.         shuffleIdToMapStage.get(shuffleDep.shuffleId) match {
  84.             case Some(stage) =>
  85.                 stage
  86.             
     
  87.             case None =>
  88.                 getMissingAncestorShuffleDependencies(shuffleDep.rdd).foreach { dep =>
  89.                 
     
  90.                     if (!shuffleIdToMapStage.contains(dep.shuffleId)) {
  91.                         createShuffleMapStage(dep, firstJobId)
  92.                     }
  93.                 }
  94.                 // Finally, create a stage for the given shuffle dependency.
  95.                 createShuffleMapStage(shuffleDep, firstJobId)
  96.         }
  97.     }
  98.  
  99.     def createShuffleMapStage[K, V, C](
  100.         shuffleDep: ShuffleDependency[K, V, C], jobId: Int): ShuffleMapStage = {
  101.         ... ...
  102.         val rdd = shuffleDep.rdd
  103.         val numTasks = rdd.partitions.length
  104.         val parents = getOrCreateParentStages(rdd, jobId)
  105.         val id = nextStageId.getAndIncrement()        
  106.         
     
  107.         val stage = new ShuffleMapStage(
  108.             id, rdd, numTasks, parents, jobId, rdd.creationSite, shuffleDep, mapOutputTracker)
  109.         ... ...      
  110.     }    
  111.     ... ...
  112. }

任务的切分

DAGScheduler.scala

  1. private[scheduler] def handleJobSubmitted(jobId: Int,
  2.     finalRDD: RDD[_],
  3.     func: (TaskContext, Iterator[_]) => _,
  4.     partitions: Array[Int],
  5.     callSite: CallSite,
  6.     listener: JobListener,
  7.     properties: Properties): Unit = {
  8.     
     
  9.     var finalStage: ResultStage = null
  10.     try {
  11.         finalStage = createResultStage(finalRDD, func, partitions, jobId, callSite)
  12.     } catch {
  13.         ... ...
  14.     }
  15.     
     
  16.     val job = new ActiveJob(jobId, finalStage, callSite, listener, properties)    
  17.     ... ...
  18.     submitStage(finalStage)
  19. }
  20.  
  21. private def submitStage(stage: Stage): Unit = {
  22.     val jobId = activeJobForStage(stage)
  23.     
     
  24.     if (jobId.isDefined) {        
  25.         if (!waitingStages(stage) && !runningStages(stage) && !failedStages(stage)) {
  26.             val missing = getMissingParentStages(stage).sortBy(_.id)
  27.  
  28.             if (missing.isEmpty) {
  29.                 submitMissingTasks(stage, jobId.get)
  30.             } else {
  31.                 for (parent <- missing) {
  32.                     submitStage(parent)
  33.                 }
  34.                 waitingStages += stage
  35.             }
  36.         }
  37.     } else {
  38.         abortStage(stage, "No active job for stage " + stage.id, None)
  39.     }
  40. }
  41.  
  42. private def submitMissingTasks(stage: Stage, jobId: Int): Unit = {
  43.  
  44.     val partitionsToCompute: Seq[Int] = stage.findMissingPartitions()
  45.     ... ...
  46.     val tasks: Seq[Task[_]] = try {
  47.         val serializedTaskMetrics = closureSerializer.serialize(stage.latestInfo.taskMetrics).array()
  48.         
     
  49.         stage match {
  50.         case stage: ShuffleMapStage =>        
  51.             stage.pendingPartitions.clear()
  52.             partitionsToCompute.map { id =>
  53.             val locs = taskIdToLocations(id)
  54.             val part = partitions(id)
  55.             stage.pendingPartitions += id            
  56.             new ShuffleMapTask(stage.id, stage.latestInfo.attemptNumber,
  57.                 taskBinary, part, locs, properties, serializedTaskMetrics, Option(jobId),
  58.                 Option(sc.applicationId), sc.applicationAttemptId, stage.rdd.isBarrier())
  59.             }
  60.         case stage: ResultStage =>
  61.             partitionsToCompute.map { id =>
  62.             val p: Int = stage.partitions(id)
  63.             val part = partitions(p)
  64.             val locs = taskIdToLocations(id)
  65.             new ResultTask(stage.id, stage.latestInfo.attemptNumber,
  66.                 taskBinary, part, locs, id, properties, serializedTaskMetrics,
  67.                 Option(jobId), Option(sc.applicationId), sc.applicationAttemptId,
  68.                 stage.rdd.isBarrier())
  69.             }
  70.         }
  71.     } catch {
  72.         ... ...
  73.     }
  74. }

Stage.scala

  1. private[scheduler] abstract class Stage(... ...)
  2.     extends Logging {
  3.     ... ...
  4.     def findMissingPartitions(): Seq[Int]
  5.     ... ...
  6. }

全局查找(ctrl + h)findMissingPartitions实现类。

ShuffleMapStage.scala

  1. private[spark] class ShuffleMapStage(... ...)
  2.     extends Stage(id, rdd, numTasks, parents, firstJobId, callSite) {
  3.  
  4.     private[this] var _mapStageJobs: List[ActiveJob] = Nil
  5.     ... ...
  6.     override def findMissingPartitions(): Seq[Int] = {
  7.         mapOutputTrackerMaster
  8.         .findMissingPartitions(shuffleDep.shuffleId)
  9.         .getOrElse(0 until numPartitions)
  10.     }
  11. }

ResultStage.scala

  1. private[spark] class ResultStage(... ...)
  2.     extends Stage(id, rdd, partitions.length, parents, firstJobId, callSite) {
  3.     ... ...
  4.     override def findMissingPartitions(): Seq[Int] = {
  5.         val job = activeJob.get(0 until job.numPartitions).filter(id => !job.finished(id))
  6.     }
  7.     ... ...
  8. }

任务的调度

1)提交任务

DAGScheduler.scala

  1. private def submitMissingTasks(stage: Stage, jobId: Int): Unit = {
  2.     ... ...
  3.     if (tasks.nonEmpty) {
  4.         taskScheduler.submitTasks(new TaskSet( tasks.toArray, stage.id, stage.latestInfo.attemptNumber, jobId, properties))
  5.     } else {
  6.         markStageAsFinished(stage, None)
  7.     
     
  8.         stage match {
  9.         case stage: ShuffleMapStage =>
  10.  
  11.             markMapStageJobsAsFinished(stage)
  12.         case stage : ResultStage =>
  13.             logDebug(s"Stage ${stage} is actually done; (partitions: ${stage.numPartitions})")
  14.         }
  15.         submitWaitingChildStages(stage)
  16.     }
  17. }

TaskScheduler.scala

def submitTasks(taskSet: TaskSet): Unit

全局查找submitTasks的实现类TaskSchedulerImpl

TaskSchedulerImpl.scala

  1. override def submitTasks(taskSet: TaskSet): Unit = {
  2.     val tasks = taskSet.tasks
  3.     this.synchronized {
  4.         val manager = createTaskSetManager(taskSet, maxTaskFailures)
  5.         val stage = taskSet.stageId
  6.         val stageTaskSets =
  7.         taskSetsByStageIdAndAttempt.getOrElseUpdate(stage, new HashMap[Int, TaskSetManager])
  8.         ... ...
  9.         stageTaskSets(taskSet.stageAttemptId) = manager
  10.         // 向队列里面设置任务
  11.         schedulableBuilder.addTaskSetManager(manager, manager.taskSet.properties) 
  12.         ... ...
  13.     }
  14.     // 取任务
  15.     backend.reviveOffers()
  16. }

2)FIFO和公平调度器

点击schedulableBuilder,查找schedulableBuilder初始化赋值的地方

  1. private var schedulableBuilder: SchedulableBuilder = null
  2.  
  3. def initialize(backend: SchedulerBackend): Unit = {
  4.     this.backend = backend
  5.     schedulableBuilder = {
  6.         schedulingMode match {
  7.         case SchedulingMode.FIFO =>
  8.             new FIFOSchedulableBuilder(rootPool)
  9.         case SchedulingMode.FAIR =>
  10.             new FairSchedulableBuilder(rootPool, conf)
  11.         case _ =>
  12.             throw new IllegalArgumentException(s"Unsupported $SCHEDULER_MODE_PROPERTY: " +
  13.             s"$schedulingMode")
  14.         }
  15.     }
  16.     schedulableBuilder.buildPools()
  17. }

点击schedulingMode,default scheduler is FIFO

  1. private val schedulingModeConf = conf.get(SCHEDULER_MODE)
  2. val schedulingMode: SchedulingMode =
  3.     ... ...
  4.       SchedulingMode.withName(schedulingModeConf.toUpperCase(Locale.ROOT))
  5.     ... ...
  6. }
  7. private[spark] val SCHEDULER_MODE =
  8. ConfigBuilder("spark.scheduler.mode")
  9.     .version("0.8.0")
  10.     .stringConf
  11.     .createWithDefault(SchedulingMode.FIFO.toString)

3)读取任务

SchedulerBackend.scala

  1. private[spark] trait SchedulerBackend {
  2.     ... ...
  3.     def reviveOffers(): Unit
  4.     ... ...
  5. }

全局查找reviveOffers实现类CoarseGrainedSchedulerBackend

CoarseGrainedSchedulerBackend.scala

  1. override def reviveOffers(): Unit = {
  2.     // 自己给自己发消息
  3.     driverEndpoint.send(ReviveOffers)
  4. }
  5. // 自己接收到消息
  6. override def receive: PartialFunction[Any, Unit] = {
  7.     ... ...
  8.     case ReviveOffers =>
  9.         makeOffers()
  10.     ... ...
  11. }
  12.  
  13. private def makeOffers(): Unit = {
  14.  
  15.     val taskDescs = withLock {
  16.         ... ...
  17.         // 取任务
  18.         scheduler.resourceOffers(workOffers)
  19.     }
  20.     if (taskDescs.nonEmpty) {
  21.         launchTasks(taskDescs)
  22.     }
  23. }

TaskSchedulerImpl.scala

  1. def resourceOffers(offers: IndexedSeq[WorkerOffer]): Seq[Seq[TaskDescription]] = synchronized {
  2.     ... ...
  3.     val sortedTaskSets = rootPool.getSortedTaskSetQueue.filterNot(_.isZombie)
  4.       
     
  5.     for (taskSet <- sortedTaskSets) {
  6.         val availableSlots = availableCpus.map(c => c / CPUS_PER_TASK).sum
  7.  
  8.         if (taskSet.isBarrier && availableSlots < taskSet.numTasks) {
  9.     
     
  10.         } else {
  11.             var launchedAnyTask = false
  12.             val addressesWithDescs = ArrayBuffer[(String, TaskDescription)]()
  13.  
  14.             for (currentMaxLocality <- taskSet.myLocalityLevels) {
  15.                 var launchedTaskAtCurrentMaxLocality = false
  16.                 do {
  17.                     launchedTaskAtCurrentMaxLocality = resourceOfferSingleTaskSet(taskSet,
  18.                         currentMaxLocality, shuffledOffers, availableCpus,
  19.                         availableResources, tasks, addressesWithDescs)
  20.                     launchedAnyTask |= launchedTaskAtCurrentMaxLocality
  21.                 } while (launchedTaskAtCurrentMaxLocality)
  22.             }
  23.             ... ...
  24.         }
  25.     }
  26.     ... ...
  27.     return tasks
  28. }
  29.  

Pool.scala

  1. override def getSortedTaskSetQueue: ArrayBuffer[TaskSetManager] = {
  2.     val sortedTaskSetQueue = new ArrayBuffer[TaskSetManager]
  3.     val sortedSchedulableQueue =
  4.         schedulableQueue.asScala.toSeq.sortWith(taskSetSchedulingAlgorithm.comparator)
  5.     
     
  6.     for (schedulable <- sortedSchedulableQueue) {
  7.         sortedTaskSetQueue ++= schedulable.getSortedTaskSetQueue
  8.     }
  9.     sortedTaskSetQueue
  10. }
  11.  
  12. private val taskSetSchedulingAlgorithm: SchedulingAlgorithm = {
  13.     schedulingMode match {
  14.         case SchedulingMode.FAIR =>
  15.             new FairSchedulingAlgorithm()
  16.         case SchedulingMode.FIFO =>
  17.             new FIFOSchedulingAlgorithm()
  18.         case _ =>
  19.             … …
  20.     }
  21. }

4)FIFO和公平调度器规则

SchedulingAlgorithm.scala

  1. private[spark] class FIFOSchedulingAlgorithm extends SchedulingAlgorithm {
  2.     override def comparator(s1: Schedulable, s2: Schedulable): Boolean = {
  3.         val priority1 = s1.priority
  4.         val priority2 = s2.priority
  5.         var res = math.signum(priority1 - priority2)
  6.         if (res == 0) {
  7.             val stageId1 = s1.stageId
  8.             val stageId2 = s2.stageId
  9.             res = math.signum(stageId1 - stageId2)
  10.         }
  11.         res < 0
  12.     }
  13. }
  14.  
  15. private[spark] class FairSchedulingAlgorithm extends SchedulingAlgorithm {
  16.     override def comparator(s1: Schedulable, s2: Schedulable): Boolean = {
  17.         val minShare1 = s1.minShare
  18.         val minShare2 = s2.minShare
  19.         val runningTasks1 = s1.runningTasks
  20.         val runningTasks2 = s2.runningTasks
  21.         val s1Needy = runningTasks1 < minShare1
  22.         val s2Needy = runningTasks2 < minShare2
  23.         val minShareRatio1 = runningTasks1.toDouble / math.max(minShare1, 1.0)
  24.         val minShareRatio2 = runningTasks2.toDouble / math.max(minShare2, 1.0)
  25.         val taskToWeightRatio1 = runningTasks1.toDouble / s1.weight.toDouble
  26.         val taskToWeightRatio2 = runningTasks2.toDouble / s2.weight.toDouble
  27.         … …
  28.     }
  29. }

5)发送给Executor端执行任务

CoarseGrainedSchedulerBackend.scala

  1. private def makeOffers(): Unit = {
  2.  
  3.     val taskDescs = withLock {
  4.         ... ...
  5.         // 取任务
  6.         scheduler.resourceOffers(workOffers)
  7.     }
  8.     if (taskDescs.nonEmpty) {
  9.         launchTasks(taskDescs)
  10.     }
  11. }
  12.  
  13. private def launchTasks(tasks: Seq[Seq[TaskDescription]]): Unit = {
  14.  
  15.     for (task <- tasks.flatten) {
  16.         val serializedTask = TaskDescription.encode(task)
  17.  
  18.         if (serializedTask.limit() >= maxRpcMessageSize) {
  19.             ... ...
  20.         }
  21.         else {
  22.             … …
  23.             // 序列化任务发往Executor远程终端
  24.             executorData.executorEndpoint.send(LaunchTask(new SerializableBuffer(serializedTask)))
  25.         }
  26.     }
  27. }

任务的执行

在CoarseGrainedExecutorBackend.scala中接收数据LaunchTask

  1. override def receive: PartialFunction[Any, Unit] = {
  2.     ... ...
  3.     case LaunchTask(data) =>
  4.       if (executor == null) {
  5.         exitExecutor(1, "Received LaunchTask command but executor was null")
  6.       } else {
  7.         val taskDesc = TaskDescription.decode(data.value)
  8.         logInfo("Got assigned task " + taskDesc.taskId)
  9.         taskResources(taskDesc.taskId) = taskDesc.resources
  10.         executor.launchTask(this, taskDesc)
  11.       }
  12.       ... ...
  13. }

Executor.scala

  1. def launchTask(context: ExecutorBackend, taskDescription: TaskDescription): Unit = {
  2.     val tr = new TaskRunner(context, taskDescription)
  3.     runningTasks.put(taskDescription.taskId, tr)
  4.     threadPool.execute(tr)
  5. }

Shuffle

Spark最初版本HashShuffle

Spark0.8.1版本以后优化后的HashShuffle

Spark1.1版本加入SortShuffle,默认是HashShuffle

Spark1.2版本默认是SortShuffle,但是可配置HashShuffle

Spark2.0版本删除HashShuffle只有SortShuffle

Shuffle的原理和执行过程

Shuffle一定会有落盘。

如果shuffle过程中落盘数据量减少,那么可以提高性能。

算子如果存在预聚合功能,可以提高shuffle的性能。

HashShuffle解析

未优化的HashShuffle

优化后的HashShuffle

优化的HashShuffle过程就是启用合并机制,合并机制就是复用buffer,开启合并机制的配置是spark.shuffle.consolidateFiles。该参数默认值为false,将其设置为true即可开启优化机制。通常来说,如果我们使用HashShuffleManager,那么都建议开启这个选项。

官网参数说明:http://spark.apache.org/docs/0.8.1/configuration.html

SortShuffle解析

SortShuffle

在该模式下,数据会先写入一个数据结构,reduceByKey写入Map,一边通过Map局部聚合,一边写入内存。Join算子写入ArrayList直接写入内存中。然后需要判断是否达到阈值,如果达到就会将内存数据结构的数据写入到磁盘,清空内存数据结构。

在溢写磁盘前,先根据key进行排序,排序过后的数据,会分批写入到磁盘文件中。默认批次为10000条,数据会以每批一万条写入到磁盘文件。写入磁盘文件通过缓冲区溢写的方式,每次溢写都会产生一个磁盘文件,也就是说一个Task过程会产生多个临时文件。

最后在每个Task中,将所有的临时文件合并,这就是merge过程,此过程将所有临时文件读取出来,一次写入到最终文件。意味着一个Task的所有数据都在这一个文件中。同时单独写一份索引文件,标识下游各个Task的数据在文件中的索引,start offset和end offset。

bypassShuffle

bypassShuffle和SortShuffle的区别就是不对数据排序。

bypass运行机制的触发条件如下:

1)shuffle reduce task数量小于等于spark.shuffle.sort.bypassMergeThreshold参数的值,默认为200。

2)不是聚合类的shuffle算子(比如reduceByKey不行)。

Shuffle写磁盘

shuffleWriterProcessor(写处理器)

DAGScheduler.scala

  1. private def submitMissingTasks(stage: Stage, jobId: Int): Unit = {
  2.     ... ...
  3.     val tasks: Seq[Task[_]] = try {
  4.         val serializedTaskMetrics = closureSerializer.serialize(stage.latestInfo.taskMetrics).array()
  5.         
     
  6.         stage match {
  7.         // shuffle写过程
  8.         case stage: ShuffleMapStage =>        
  9.             stage.pendingPartitions.clear()
  10.             partitionsToCompute.map { id =>
  11.             val locs = taskIdToLocations(id)
  12.             val part = partitions(id)
  13.             stage.pendingPartitions += id            
  14.             new ShuffleMapTask(stage.id, stage.latestInfo.attemptNumber,
  15.                 taskBinary, part, locs, properties, serializedTaskMetrics, Option(jobId),
  16.                 Option(sc.applicationId), sc.applicationAttemptId, stage.rdd.isBarrier())
  17.             }
  18.         // shuffle读过程
  19.         case stage: ResultStage =>
  20.         ... ...
  21.         }
  22.     } catch {
  23.         ... ...
  24.     }
  25. }

Task.scala

  1. private[spark] abstract class Task[T](... ...) extends Serializable {
  2.    
     
  3.     final def run(... ...): T = {      
  4.         runTask(context)
  5.     }
  6. }

Ctrl+h查找runTask 实现类ShuffleMapTask.scala

  1. private[spark] class ShuffleMapTask(... ...)
  2.   extends Task[MapStatus](... ...){
  3.   
     
  4.     override def runTask(context: TaskContext): MapStatus = {
  5.         ... ...
  6.         dep.shuffleWriterProcessor.write(rdd, dep, mapId, context, partition)
  7.     }
  8. }

ShuffleWriteProcessor.scala

  1. def write(... ...): MapStatus = {
  2.     
     
  3.     var writer: ShuffleWriter[Any, Any] = null
  4.     try {
  5.         val manager = SparkEnv.get.shuffleManager
  6.         writer = manager.getWriter[Any, Any](
  7.         dep.shuffleHandle,
  8.         mapId,
  9.         context,
  10.         createMetricsReporter(context))
  11.         
     
  12.         writer.write(
  13.         rdd.iterator(partition, context).asInstanceOf[Iterator[_ <: Product2[Any, Any]]])
  14.         writer.stop(success = true).get
  15.     } catch {
  16.         ... ...
  17.     }
  18. }

查找(ctrl + h)ShuffleManager的实现类,SortShuffleManager

SortShuffleManager.scala

  1. override def getWriter[K, V]( handle: ShuffleHandle,
  2.       mapId: Long,
  3.       context: TaskContext,
  4.       metrics: ShuffleWriteMetricsReporter): ShuffleWriter[K, V] =
  5.     ... ...
  6.     handle match {
  7.     case unsafeShuffleHandle: SerializedShuffleHandle[K @unchecked, V @unchecked] =>
  8.         new UnsafeShuffleWriter(... ...)
  9.     case bypassMergeSortHandle: BypassMergeSortShuffleHandle[K @unchecked, V @unchecked] =>
  10.         new BypassMergeSortShuffleWriter(... ...)
  11.     case other: BaseShuffleHandle[K @unchecked, V @unchecked, _] =>
  12.         new SortShuffleWriter(... ...)
  13.     }
  14. }

因为getWriter的第一个输入参数是dep.shuffleHandle,点击dep.shuffleHandle

Dependency.scala

val shuffleHandle: ShuffleHandle = _rdd.context.env.shuffleManager.registerShuffle(shuffleId, this)

ShuffleManager.scala

def registerShuffle[K, V, C](shuffleId: Int, dependency: ShuffleDependency[K, V, C]): ShuffleHandle

使用BypassShuffle条件

BypassMergeSortShuffleHandle使用条件:

1)不能使用预聚合

2)如果下游的分区数量小于等于200(可配置)

处理器

写对象

判断条件

SerializedShuffleHandle

UnsafeShuffleWriter

1.序列化规则支持重定位操作(java序列化不支持,Kryo支持)

2.不能使用预聚合

3.如果下游的分区数量小于或等于1677216

BypassMergeSortShuffleHandle

BypassMergeSortShuffleWriter

1.不能使用预聚合

2.如果下游的分区数量小于等于200(可配置)

BaseShuffleHandle

SortShuffleWriter

其他情况

查找(ctrl + h)registerShuffle 实现类,SortShuffleManager.scala

  1. override def registerShuffle[K, V, C](
  2.     shuffleId: Int,
  3.     dependency: ShuffleDependency[K, V, C]): ShuffleHandle = {
  4.     //使用BypassShuffle条件:不能使用预聚合功能;默认下游分区数据不能大于200
  5.     if (SortShuffleWriter.shouldBypassMergeSort(conf, dependency)) {
  6.         new BypassMergeSortShuffleHandle[K, V](
  7.             shuffleId, dependency.asInstanceOf[ShuffleDependency[K, V, V]])
  8.     } else if (SortShuffleManager.canUseSerializedShuffle(dependency)) {
  9.         new SerializedShuffleHandle[K, V](
  10.             shuffleId, dependency.asInstanceOf[ShuffleDependency[K, V, V]])
  11.     } else {
  12.         new BaseShuffleHandle(shuffleId, dependency)
  13.     }
  14. }

点击shouldBypassMergeSort

SortShuffleWriter.scala

  1. private[spark] object SortShuffleWriter {
  2.     def shouldBypassMergeSort(conf: SparkConf, dep: ShuffleDependency[_, _, _]): Boolean = {
  3.         // 是否有map阶段预聚合(支持预聚合不能用)
  4.         if (dep.mapSideCombine) {
  5.             false
  6.         } else {
  7. // SHUFFLE_SORT_BYPASS_MERGE_THRESHOLD = 200分区
  8.             val bypassMergeThreshold: Int = conf.get(config.SHUFFLE_SORT_BYPASS_MERGE_THRESHOLD)
  9.             // 如果下游分区器的数量,小于200(可配置),可以使用bypass
  10.             dep.partitioner.numPartitions <= bypassMergeThreshold
  11.         }
  12.     }
  13. }

使用SerializedShuffle条件

SerializedShuffleHandle使用条件:

1)序列化规则支持重定位操作(java序列化不支持,Kryo支持)

2)不能使用预聚合

3)如果下游的分区数量小于或等于1677216

点击canUseSerializedShuffle

SortShuffleManager.scala

  1. def canUseSerializedShuffle(dependency: ShuffleDependency[_, _, _]): Boolean = {
  2.     val shufId = dependency.shuffleId
  3.     val numPartitions = dependency.partitioner.numPartitions
  4.     
     
  5.     // 是否支持将两个独立的序列化对象 重定位,聚合到一起
  6.     // 1默认的java序列化不支持;Kryo序列化支持重定位(可以用)
  7.     if (!dependency.serializer.supportsRelocationOfSerializedObjects) {
  8.         false
  9.     } else if (dependency.mapSideCombine) { // 2支持预聚合也不能用
  10.         false
  11.     } else if (numPartitions > MAX_SHUFFLE_OUTPUT_PARTITIONS_FOR_SERIALIZED_MODE) {//3如果下游分区的数量大于16777216,也不能用
  12.         false
  13.     } else {
  14.         true
  15.     }
  16. }

使用BaseShuffle

点击SortShuffleWriter

SortShuffleWriter.scala

  1. override def write(records: Iterator[Product2[K, V]]): Unit = {
  2.  
  3.     // 判断是否有预聚合功能,支持会有aggregator和排序规则
  4.     sorter = if (dep.mapSideCombine) {
  5.         new ExternalSorter[K, V, C](
  6.         context, dep.aggregator, Some(dep.partitioner), dep.keyOrdering, dep.serializer)
  7.     } else {
  8.         new ExternalSorter[K, V, V](
  9.         context, aggregator = None, Some(dep.partitioner), ordering = None, dep.serializer)
  10.     }
  11.     // 插入数据
  12.     sorter.insertAll(records)
  13.     
     
  14.     val mapOutputWriter = shuffleExecutorComponents.createMapOutputWriter(
  15.         dep.shuffleId, mapId, dep.partitioner.numPartitions)
  16.     // 插入数据   
  17.     sorter.writePartitionedMapOutput(dep.shuffleId, mapId, mapOutputWriter)
  18.     
     
  19.     val partitionLengths = mapOutputWriter.commitAllPartitions()
  20.     
     
  21.     mapStatus = MapStatus(blockManager.shuffleServerId, partitionLengths, mapId)
  22. }

插入数据(缓存+溢写)

ExternalSorter.scala

  1. def insertAll(records: Iterator[Product2[K, V]]): Unit = {
  2.  
  3.     val shouldCombine = aggregator.isDefined
  4.  
  5.     // 判断是否支持预聚合,支持预聚合,采用map结构,不支持预聚合采用buffer结构
  6.     if (shouldCombine) {
  7.         val mergeValue = aggregator.get.mergeValue
  8.         val createCombiner = aggregator.get.createCombiner
  9.         var kv: Product2[K, V] = null
  10.         val update = (hadValue: Boolean, oldValue: C) => {
  11.             if (hadValue) mergeValue(oldValue, kv._2) else createCombiner(kv._2)
  12.         }
  13.         
     
  14.         while (records.hasNext) {
  15.             addElementsRead()
  16.             kv = records.next()
  17.             // 如果支持预聚合,在map阶段聚合,将相同key,的value聚合
  18.             map.changeValue((getPartition(kv._1), kv._1), update)
  19.             // 是否能够溢写
  20.             maybeSpillCollection(usingMap = true)
  21.         }
  22.     } else {
  23.         while (records.hasNext) {
  24.             addElementsRead()
  25.             val kv = records.next()
  26.             // 如果不支持预聚合,value不需要聚合 (key,(value1,value2))
  27.             buffer.insert(getPartition(kv._1), kv._1, kv._2.asInstanceOf[C])
  28.             maybeSpillCollection(usingMap = false)
  29.         }
  30.     }
  31. }
  32.  
  33. private def maybeSpillCollection(usingMap: Boolean): Unit = {
  34.     var estimatedSize = 0L
  35.     if (usingMap) {
  36.         estimatedSize = map.estimateSize()
  37.         if (maybeSpill(map, estimatedSize)) {
  38.             map = new PartitionedAppendOnlyMap[K, C]
  39.         }
  40.     } else {
  41.         estimatedSize = buffer.estimateSize()
  42.         if (maybeSpill(buffer, estimatedSize)) {
  43.             buffer = new PartitionedPairBuffer[K, C]
  44.         }
  45.     }
  46.     
     
  47.     if (estimatedSize > _peakMemoryUsedBytes) {
  48.         _peakMemoryUsedBytes = estimatedSize
  49.     }
  50. }

Spillable.scala

  1. protected def maybeSpill(collection: C, currentMemory: Long): Boolean = {
  2.     var shouldSpill = false
  3.     // myMemoryThreshold默认值内存门槛是5m
  4.     if (elementsRead % 32 == 0 && currentMemory >= myMemoryThreshold) {
  5.     
     
  6.         val amountToRequest = 2 * currentMemory - myMemoryThreshold
  7.         // 申请内存
  8.         val granted = acquireMemory(amountToRequest)
  9.         myMemoryThreshold += granted
  10.         // 当前内存大于(尝试申请的内存+门槛),就需要溢写了
  11.         shouldSpill = currentMemory >= myMemoryThreshold
  12.     }
  13.     // 强制溢写 读取数据的值 超过了Int的最大值
  14.     shouldSpill = shouldSpill || _elementsRead > numElementsForceSpillThreshold
  15.     
     
  16.     if (shouldSpill) {
  17.         _spillCount += 1
  18.         logSpillage(currentMemory)
  19.         // 溢写
  20.         spill(collection)
  21.         _elementsRead = 0
  22.         _memoryBytesSpilled += currentMemory
  23.         // 释放内存
  24.         releaseMemory()
  25.     }
  26.     shouldSpill
  27. }
  28.  
  29. protected def spill(collection: C): Unit

查找(ctrl +h)spill 的实现类ExternalSorter

ExternalSorter.scala

  1. override protected[this] def spill(collection: WritablePartitionedPairCollection[K, C]): Unit = {
  2.     val inMemoryIterator = collection.destructiveSortedWritablePartitionedIterator(comparator)
  3.     val spillFile = spillMemoryIteratorToDisk(inMemoryIterator)
  4.     spills += spillFile
  5. }
  6.  
  7. private[this] def spillMemoryIteratorToDisk(inMemoryIterator: WritablePartitionedIterator)
  8.      : SpilledFile = {
  9.    // 创建临时文件
  10.    val (blockId, file) = diskBlockManager.createTempShuffleBlock()
  11.  
  12.    var objectsWritten: Long = 0
  13.    val spillMetrics: ShuffleWriteMetrics = new ShuffleWriteMetrics
  14.    // 溢写文件前,fileBufferSize缓冲区大小默认32m
  15.    val writer: DiskBlockObjectWriter =
  16.      blockManager.getDiskWriter(blockId, file, serInstance, fileBufferSize, spillMetrics)
  17.  
  18.    … …
  19.  
  20.    SpilledFile(file, blockId, batchSizes.toArray, elementsPerPartition)
  21. }

merge合并

来到SortShuffleWriter.scala

  1. override def write(records: Iterator[Product2[K, V]]): Unit = {
  2.     sorter = if (dep.mapSideCombine) {
  3.         new ExternalSorter[K, V, C](
  4.         context, dep.aggregator, Some(dep.partitioner), dep.keyOrdering, dep.serializer)
  5.     } else {
  6.         new ExternalSorter[K, V, V](
  7.         context, aggregator = None, Some(dep.partitioner), ordering = None, dep.serializer)
  8.     }
  9.     sorter.insertAll(records)
  10.     
     
  11.     val mapOutputWriter = shuffleExecutorComponents.createMapOutputWriter(
  12.         dep.shuffleId, mapId, dep.partitioner.numPartitions)
  13.     // 合并
  14.     sorter.writePartitionedMapOutput(dep.shuffleId, mapId, mapOutputWriter)
  15.     
     
  16.     val partitionLengths = mapOutputWriter.commitAllPartitions()
  17.     
     
  18.     mapStatus = MapStatus(blockManager.shuffleServerId, partitionLengths, mapId)
  19. }

ExternalSorter.scala

  1. def writePartitionedMapOutput(
  2.     shuffleId: Int,
  3.     mapId: Long,
  4.     mapOutputWriter: ShuffleMapOutputWriter): Unit = {
  5.     var nextPartitionId = 0
  6.     // 如果溢写文件为空,只对内存中数据处理
  7.     if (spills.isEmpty) {
  8.         // Case where we only have in-memory data
  9.         ... ...
  10.     } else {
  11.         // We must perform merge-sort; get an iterator by partition and write everything directly.
  12.         //如果溢写文件不为空,需要将多个溢写文件合并
  13.         for ((id, elements) <- this.partitionedIterator) {
  14.             val blockId = ShuffleBlockId(shuffleId, mapId, id)
  15.             var partitionWriter: ShufflePartitionWriter = null
  16.             var partitionPairsWriter: ShufflePartitionPairsWriter = null
  17.             … …
  18.             } {
  19.                 if (partitionPairsWriter != null) {
  20.                     partitionPairsWriter.close()
  21.                 }
  22.             }
  23.             nextPartitionId = id + 1
  24.         }
  25.     }
  26.     … …
  27. }
  28.  
  29. def partitionedIterator: Iterator[(Int, Iterator[Product2[K, C]])] = {
  30.     val usingMap = aggregator.isDefined
  31.     val collection: WritablePartitionedPairCollection[K, C] = if (usingMap) map else buffer
  32.     
     
  33.     if (spills.isEmpty) {
  34.         if (ordering.isEmpty) {      
  35.             groupByPartition(destructiveIterator(collection.partitionedDestructiveSortedIterator(None)))
  36.         } else {
  37.             groupByPartition(destructiveIterator(
  38.             collection.partitionedDestructiveSortedIterator(Some(keyComparator))))
  39.         }
  40.     } else {
  41.         // 合并溢写文件和内存中数据
  42.         merge(spills, destructiveIterator(
  43.         collection.partitionedDestructiveSortedIterator(comparator)))
  44.     }
  45. }
  46.  
  47. private def merge(spills: Seq[SpilledFile], inMemory: Iterator[((Int, K), C)])
  48.     : Iterator[(Int, Iterator[Product2[K, C]])] = {
  49.     
     
  50.     val readers = spills.map(new SpillReader(_))
  51.     val inMemBuffered = inMemory.buffered
  52.     
     
  53.     (0 until numPartitions).iterator.map { p =>
  54.         val inMemIterator = new IteratorForPartition(p, inMemBuffered)
  55.         val iterators = readers.map(_.readNextPartition()) ++ Seq(inMemIterator)
  56.         if (aggregator.isDefined) {
  57.  
  58.             (p, mergeWithAggregation(
  59.             iterators, aggregator.get.mergeCombiners, keyComparator, ordering.isDefined))
  60.         } else if (ordering.isDefined) {
  61.         // 归并排序
  62.             (p, mergeSort(iterators, ordering.get))
  63.         } else {
  64.             (p, iterators.iterator.flatten)
  65.         }
  66.     }
  67. }

写磁盘

来到SortShuffleWriter.scala

  1. override def write(records: Iterator[Product2[K, V]]): Unit = {
  2.     sorter = if (dep.mapSideCombine) {
  3.         new ExternalSorter[K, V, C](
  4.         context, dep.aggregator, Some(dep.partitioner), dep.keyOrdering, dep.serializer)
  5.     } else {
  6.         new ExternalSorter[K, V, V](
  7.         context, aggregator = None, Some(dep.partitioner), ordering = None, dep.serializer)
  8.     }
  9.     sorter.insertAll(records)
  10.     
     
  11.     val mapOutputWriter = shuffleExecutorComponents.createMapOutputWriter(
  12.         dep.shuffleId, mapId, dep.partitioner.numPartitions)
  13.     // 合并
  14.     sorter.writePartitionedMapOutput(dep.shuffleId, mapId, mapOutputWriter)
  15.     // 写磁盘
  16.     val partitionLengths = mapOutputWriter.commitAllPartitions()
  17.     
     
  18.     mapStatus = MapStatus(blockManager.shuffleServerId, partitionLengths, mapId)
  19. }
  20. 查找(ctrl + h)commitAllPartitions实现类,来到LocalDiskShuffleMapOutputWriter.java
  21. public long[] commitAllPartitions() throws IOException {
  22.  
  23.     if (outputFileChannel != null && outputFileChannel.position() != bytesWrittenToMergedFile) {
  24.         ... ...
  25.     }
  26.     cleanUp();
  27.     File resolvedTmp = outputTempFile != null && outputTempFile.isFile() ? outputTempFile : null;
  28.     blockResolver.writeIndexFileAndCommit(shuffleId, mapId, partitionLengths, resolvedTmp);
  29.     return partitionLengths;
  30. }

查找(ctrl + h)commitAllPartitions实现类,来到LocalDiskShuffleMapOutputWriter.java

  1. public long[] commitAllPartitions() throws IOException {
  2.  
  3.     if (outputFileChannel != null && outputFileChannel.position() != bytesWrittenToMergedFile) {
  4.         ... ...
  5.     }
  6.     cleanUp();
  7.     File resolvedTmp = outputTempFile != null && outputTempFile.isFile() ? outputTempFile : null;
  8.     blockResolver.writeIndexFileAndCommit(shuffleId, mapId, partitionLengths, resolvedTmp);
  9.     return partitionLengths;
  10. }

IndexShuffleBlockResolver.scala

  1. def writeIndexFileAndCommit(
  2.     shuffleId: Int,
  3.     mapId: Long,
  4.     lengths: Array[Long],
  5.     dataTmp: File): Unit = {
  6.     
     
  7.     val indexFile = getIndexFile(shuffleId, mapId)
  8.     val indexTmp = Utils.tempFileWith(indexFile)
  9.     try {
  10.         val dataFile = getDataFile(shuffleId, mapId)
  11.     
     
  12.         synchronized {
  13.             val existingLengths = checkIndexAndDataFile(indexFile, dataFile, lengths.length)
  14.             if (existingLengths != null) {
  15.                 System.arraycopy(existingLengths, 0, lengths, 0, lengths.length)
  16.                 if (dataTmp != null && dataTmp.exists()) {
  17.                     dataTmp.delete()
  18.                 }
  19.             } else {
  20.                 val out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexTmp)))
  21.                 Utils.tryWithSafeFinally {
  22.                     var offset = 0L
  23.                     out.writeLong(offset)
  24.                     for (length <- lengths) {
  25.                         offset += length
  26.                         out.writeLong(offset)
  27.                     }
  28.                 } {
  29.                     out.close()
  30.                 }
  31.         
     
  32.                 if (indexFile.exists()) {
  33.                     indexFile.delete()
  34.                 }
  35.                 if (dataFile.exists()) {
  36.                     dataFile.delete()
  37.                 }
  38.                 if (!indexTmp.renameTo(indexFile)) {
  39.                     throw new IOException("fail to rename file " + indexTmp + " to " + indexFile)
  40.                 }
  41.                 if (dataTmp != null && dataTmp.exists() && !dataTmp.renameTo(dataFile)) {
  42.                     throw new IOException("fail to rename file " + dataTmp + " to " + dataFile)
  43.                 }
  44.             }
  45.         }
  46.     } finally {
  47.         ... ...
  48.     }
  49. }

Shuffle读取磁盘

DAGScheduler.scala

  1. private def submitMissingTasks(stage: Stage, jobId: Int): Unit = {
  2.     ... ...
  3.     val tasks: Seq[Task[_]] = try {
  4.         val serializedTaskMetrics = closureSerializer.serialize(stage.latestInfo.taskMetrics).array()
  5.         
     
  6.         stage match {
  7.         case stage: ShuffleMapStage =>        
  8.         ... ...
  9.         case stage: ResultStage =>
  10.             partitionsToCompute.map { id =>
  11.             val p: Int = stage.partitions(id)
  12.             val part = partitions(p)
  13.             val locs = taskIdToLocations(id)
  14.             new ResultTask(stage.id, stage.latestInfo.attemptNumber,
  15.                 taskBinary, part, locs, id, properties, serializedTaskMetrics,
  16.                 Option(jobId), Option(sc.applicationId), sc.applicationAttemptId,
  17.                 stage.rdd.isBarrier())
  18.             }
  19.         }
  20.     } catch {
  21.         ... ...
  22.     }
  23. }

ResultTask.scala

  1. private[spark] class ResultTask[T, U](... ...)
  2.   extends Task[U](... ...)
  3.   with Serializable {
  4.   
     
  5.     override def runTask(context: TaskContext): U = {
  6.         func(context, rdd.iterator(partition, context))
  7.     }  
  8. }

RDD.scala

  1. final def iterator(split: Partition, context: TaskContext): Iterator[T] = {
  2.     if (storageLevel != StorageLevel.NONE) {
  3.         getOrCompute(split, context)
  4.     } else {
  5.         computeOrReadCheckpoint(split, context)
  6.     }
  7. }
  8.  
  9. private[spark] def getOrCompute(partition: Partition, context: TaskContext): Iterator[T] = {
  10.     ... ...
  11.     computeOrReadCheckpoint(partition, context) 
  12.     ... ...
  13. }
  14.  
  15. def computeOrReadCheckpoint(split: Partition, context: TaskContext): Iterator[T] ={
  16.     if (isCheckpointedAndMaterialized) {
  17.         firstParent[T].iterator(split, context)
  18.     } else {
  19.         compute(split, context)
  20.     }
  21. }
  22.  
  23. def compute(split: Partition, context: TaskContext): Iterator[T]

全局查找compute,由于我们是ShuffledRDD,所以点击ShuffledRDD.scala,搜索compute

  1. override def compute(split: Partition, context: TaskContext): Iterator[(K, C)] = {
  2.     val dep = dependencies.head.asInstanceOf[ShuffleDependency[K, V, C]]
  3.     val metrics = context.taskMetrics().createTempShuffleReadMetrics()
  4.     SparkEnv.get.shuffleManager.getReader(
  5.     dep.shuffleHandle, split.index, split.index + 1, context, metrics)
  6.     .read()
  7.     .asInstanceOf[Iterator[(K, C)]]
  8. }

ShuffleManager.scala文件

def getReader[K, C](... ...): ShuffleReader[K, C]

查找(ctrl + h)getReader 的实现类,SortShuffleManager.scala

  1. override def getReader[K, C](... ...): ShuffleReader[K, C] = {
  2.     val blocksByAddress = SparkEnv.get.mapOutputTracker.getMapSizesByExecutorId(
  3.         handle.shuffleId, startPartition, endPartition)
  4.     new BlockStoreShuffleReader(
  5.         handle.asInstanceOf[BaseShuffleHandle[K, _, C]], blocksByAddress, context, metrics,
  6.         shouldBatchFetch = canUseBatchFetch(startPartition, endPartition, context))
  7. }

在BlockStoreShuffleReader.scala文件中查找read方法

  1. override def read(): Iterator[Product2[K, C]] = {
  2.     val wrappedStreams = new ShuffleBlockFetcherIterator(
  3.         ... ...
  4.         // 读缓冲区大小 默认 48m
  5.         SparkEnv.get.conf.get(config.REDUCER_MAX_SIZE_IN_FLIGHT) * 1024 * 1024,
  6.         SparkEnv.get.conf.get(config.REDUCER_MAX_REQS_IN_FLIGHT),
  7.         ... ...
  8. }

Spark内存管理

堆内和堆外内存

概念

Spark支持堆内内存也支持堆外内存

1)堆内内存:程序在运行时动态地申请某个大小的内存空间

2)堆外内存:直接向操作系统进行申请的内存,不受JVM控制

堆内内存和对外内存优缺点

1)堆外内存,相比于堆内内存有几个优势: 

(1)减少了垃圾回收的工作,因为垃圾回收会暂停其他的工作

(2)加快了复制的速度。因为堆内在Flush到远程时,会先序列化,然后在发送;而堆外内存本身是序列化的相当于省略掉了这个工作。

说明:堆外内存是序列化的,其占用的内存大小可直接计算。堆内内存是非序列化的对象,其占用的内存是通过周期性地采样近似估算而得,即并不是每次新增的数据项都会计算一次占用的内存大小,这种方法降低了时间开销但是有可能误差较大,导致某一时刻的实际内存有可能远远超出预期。此外,在被Spark标记为释放的对象实例,很有可能在实际上并没有被JVM回收,导致实际可用的内存小于Spark记录的可用内存。所以 Spark并不能准确记录实际可用的堆内内存,从而也就无法完全避免内存溢出OOM的异常。

2)堆外内存,相比于堆内内存有几个缺点: 

(1)堆外内存难以控制,如果内存泄漏,那么很难排查

(2)堆外内存相对来说,不适合存储很复杂的对象。一般简单的对象或者扁平化的比较适合。

如何配置

1)堆内内存大小设置:–executor-memory 或 spark.executor.memory

2)在默认情况下堆外内存并不启用,spark.memory.offHeap.enabled 参数启用,并由 spark.memory.offHeap.size 参数设定堆外空间的大小。

官网配置地址:http://spark.apache.org/docs/3.0.0/configuration.html

堆内内存空间分配

堆内内存包括:存储(Storage)内存执行(Execution)内存其他内存

静态内存管理

Spark最初采用的静态内存管理机制下,存储内存、执行内存和其他内存的大小在Spark应用程序运行期间均为固定的,但用户可以应用程序启动前进行配置,堆内内存的分配如图所示:

可以看到,可用的堆内内存的大小需要按照下列方式计算:

可用的存储内存 = systemMaxMemory * spark.storage.memoryFraction * spark.storage.safety Fraction

可用的执行内存 = systemMaxMemory * spark.shuffle.memoryFraction * spark.shuffle.safety Fraction

其中systemMaxMemory取决于当前JVM堆内内存的大小,最后可用的执行内存或者存储内存要在此基础上与各自的memoryFraction 参数和safetyFraction 参数相乘得出。上述计算公式中的两个 safetyFraction 参数,其意义在于在逻辑上预留出 1-safetyFraction 这么一块保险区域,降低因实际内存超出当前预设范围而导致 OOM 的风险(上文提到,对于非序列化对象的内存采样估算会产生误差)。值得注意的是,这个预留的保险区域仅仅是一种逻辑上的规划,在具体使用时 Spark 并没有区别对待,和"其它内存"一样交给了 JVM 去管理。

Storage内存和Execution内存都有预留空间,目的是防止OOM,因为Spark堆内内存大小的记录是不准确的,需要留出保险区域。

堆外的空间分配较为简单,只有存储内存和执行内存,如下图所示。可用的执行内存和存储内存占用的空间大小直接由参数spark.memory.storageFraction 决定,由于堆外内存占用的空间可以被精确计算,所以无需再设定保险区域。

静态内存管理机制实现起来较为简单,但如果用户不熟悉Spark的存储机制,或没有根据具体的数据规模和计算任务或做相应的配置,很容易造成"一半海水,一半火焰"的局面,即存储内存和执行内存中的一方剩余大量的空间,而另一方却早早被占满,不得不淘汰或移出旧的内容以存储新的内容。由于新的内存管理机制的出现,这种方式目前已经很少有开发者使用,出于兼容旧版本的应用程序的目的,Spark 仍然保留了它的实现。

统一内存管理

Spark1.6 之后引入的统一内存管理机制,与静态内存管理的区别在于存储内存和执行内存共享同一块空间,可以动态占用对方的空闲区域,统一内存管理的堆内内存结构如图所示:

统一内存管理的堆外内存结构如下图所示:

其中最重要的优化在于动态占用机制,其规则如下:

  1. 设定基本的存储内存和执行内存区域(spark.storage.storageFraction参数),该设定确定了双方各自拥有的空间的范围;
  2. 双方的空间都不足时,则存储到硬盘;若己方空间不足而对方空余时,可借用对方的空间;(存储空间不足是指不足以放下一个完整的Block)
  3. 执行内存的空间被对方占用后,可让对方将占用的部分转存到硬盘,然后"归还"借用的空间;
  4. 存储内存的空间被对方占用后,无法让对方"归还",因为需要考虑 Shuffle过程中的很多因素,实现起来较为复杂。

统一内存管理的动态占用机制如图所示:

凭借统一内存管理机制,Spark在一定程度上提高了堆内和堆外内存资源的利用率,降低了开发者维护Spark内存的难度,但并不意味着开发者可以高枕无忧。如果存储内存的空间太大或者说缓存的数据过多,反而会导致频繁的全量垃圾回收,降低任务执行时的性能,因为缓存的RDD数据通常都是长期驻留内存的。所以要想充分发挥Spark的性能,需要开发者进一步了解存储内存和执行内存各自的管理方式和实现原理。

4.2.3 内存空间分配

全局查找(ctrl + n)SparkEnv,并找到create方法

SparkEnv.scala

  1. private def create(
  2.     conf: SparkConf,
  3.     executorId: String,
  4.     bindAddress: String,
  5.     advertiseAddress: String,
  6.     port: Option[Int],
  7.     isLocal: Boolean,
  8.     numUsableCores: Int,
  9.     ioEncryptionKey: Option[Array[Byte]],
  10.     listenerBus: LiveListenerBus = null,
  11.     mockOutputCommitCoordinator: Option[OutputCommitCoordinator] = None): SparkEnv = {
  12.     
     
  13.     ... ...
  14.     val memoryManager: MemoryManager = UnifiedMemoryManager(conf, numUsableCores)
  15.     ... ...
  16. }

UnifiedMemoryManager.scala

  1. def apply(conf: SparkConf, numCores: Int): UnifiedMemoryManager = {
  2.     // 获取最大的可用内存为总内存的0.6
  3.     val maxMemory = getMaxMemory(conf)
  4.     // 最大可用内存的0.5 MEMORY_STORAGE_FRACTION=0.5
  5.     new UnifiedMemoryManager(
  6.         conf,
  7.         maxHeapMemory = maxMemory,
  8.         onHeapStorageRegionSize =
  9.         (maxMemory * conf.get(config.MEMORY_STORAGE_FRACTION)).toLong,
  10.         numCores = numCores)
  11. }
  12.  
  13. private def getMaxMemory(conf: SparkConf): Long = {
  14.     // 获取系统内存
  15.     val systemMemory = conf.get(TEST_MEMORY)
  16.     
     
  17.     // 获取系统预留内存,默认300m(RESERVED_SYSTEM_MEMORY_BYTES = 300 * 1024 * 1024)
  18.     val reservedMemory = conf.getLong(TEST_RESERVED_MEMORY.key,
  19.         if (conf.contains(IS_TESTING)) 0 else RESERVED_SYSTEM_MEMORY_BYTES)
  20.     val minSystemMemory = (reservedMemory * 1.5).ceil.toLong
  21.     
     
  22.     if (systemMemory < minSystemMemory) {
  23.         throw new IllegalArgumentException(s"System memory $systemMemory must " +
  24.         s"be at least $minSystemMemory. Please increase heap size using the --driver-memory " +
  25.         s"option or ${config.DRIVER_MEMORY.key} in Spark configuration.")
  26.     }
  27.  
  28.     if (conf.contains(config.EXECUTOR_MEMORY)) {
  29.         val executorMemory = conf.getSizeAsBytes(config.EXECUTOR_MEMORY.key)
  30.         if (executorMemory < minSystemMemory) {
  31.         throw new IllegalArgumentException(s"Executor memory $executorMemory must be at least " +
  32.             s"$minSystemMemory. Please increase executor memory using the " +
  33.             s"--executor-memory option or ${config.EXECUTOR_MEMORY.key} in Spark configuration.")
  34.         }
  35.     }
  36.     val usableMemory = systemMemory - reservedMemory
  37.     val memoryFraction = conf.get(config.MEMORY_FRACTION)
  38.     (usableMemory * memoryFraction).toLong
  39. }

config\package.scala

  1. private[spark] val MEMORY_FRACTION = ConfigBuilder("spark.memory.fraction")
  2.     ... ...
  3.     .createWithDefault(0.6)

点击UnifiedMemoryManager.apply()中的UnifiedMemoryManager

  1. private[spark] class UnifiedMemoryManager(
  2.     conf: SparkConf,
  3.     val maxHeapMemory: Long,
  4.     onHeapStorageRegionSize: Long,
  5.     numCores: Int)
  6.   extends MemoryManager(
  7.     conf,
  8.     numCores,
  9.     onHeapStorageRegionSize,
  10.     maxHeapMemory - onHeapStorageRegionSize) {// 执行内存0.6 -0.3 = 0.3
  11.     
     
  12. }

点击MemoryManager

MemoryManager.scala

  1. private[spark] abstract class MemoryManager(
  2.     conf: SparkConf,
  3.     numCores: Int,
  4.     onHeapStorageMemory: Long,
  5.     onHeapExecutionMemory: Long) extends Logging {// 执行内存0.6 -0.3 = 0.3
  6.     ... ...
  7.     // 堆内存储内存
  8.     protected val onHeapStorageMemoryPool = new StorageMemoryPool(this, MemoryMode.ON_HEAP)
  9.     // 堆外存储内存
  10.     protected val offHeapStorageMemoryPool = new StorageMemoryPool(this, MemoryMode.OFF_HEAP)
  11.     // 堆内执行内存
  12.     protected val onHeapExecutionMemoryPool = new ExecutionMemoryPool(this, MemoryMode.ON_HEAP)
  13.     // 堆外执行内存
  14.     protected val offHeapExecutionMemoryPool = new ExecutionMemoryPool(this, MemoryMode.OFF_HEAP)
  15.  
  16.     protected[this] val maxOffHeapMemory = conf.get(MEMORY_OFFHEAP_SIZE)
  17.     // 堆外内存MEMORY_STORAGE_FRACTION = 0.5 
  18.     protected[this] val offHeapStorageMemory =
  19.         (maxOffHeapMemory * conf.get(MEMORY_STORAGE_FRACTION)).toLong
  20.     ... ...
  21. }

存储内存管理

RDD的持久化机制

弹性分布式数据集(RDD)作为 Spark 最根本的数据抽象,是只读的分区记录(Partition)的集合,只能基于在稳定物理存储中的数据集上创建,或者在其他已有的RDD上执行转换(Transformation)操作产生一个新的RDD。转换后的RDD与原始的RDD之间产生的依赖关系,构成了血统(Lineage)。凭借血统,Spark 保证了每一个RDD都可以被重新恢复。但RDD的所有转换都是惰性的,即只有当一个返回结果给Driver的行动(Action)发生时,Spark才会创建任务读取RDD,然后真正触发转换的执行。

Task在启动之初读取一个分区时,会先判断这个分区是否已经被持久化,如果没有则需要检查Checkpoint 或按照血统重新计算。所以如果一个 RDD 上要执行多次行动,可以在第一次行动中使用 persist或cache 方法,在内存或磁盘中持久化或缓存这个RDD,从而在后面的行动时提升计算速度。

事实上,cache 方法是使用默认的 MEMORY_ONLY 的存储级别将 RDD 持久化到内存,故缓存是一种特殊的持久化。 堆内和堆外存储内存的设计,便可以对缓存RDD时使用的内存做统一的规划和管理。

RDD的持久化由 Spark的Storage模块负责,实现了RDD与物理存储的解耦合。Storage模块负责管理Spark在计算过程中产生的数据,将那些在内存或磁盘、在本地或远程存取数据的功能封装了起来。在具体实现时Driver端和 Executor 端的Storage模块构成了主从式的架构,即Driver端的BlockManager为Master,Executor端的BlockManager 为 Slave。

Storage模块在逻辑上以Block为基本存储单位,RDD的每个Partition经过处理后唯一对应一个 Block(BlockId 的格式为rdd_RDD-ID_PARTITION-ID )。Driver端的Master负责整个Spark应用程序的Block的元数据信息的管理和维护,而Executor端的Slave需要将Block的更新等状态上报到Master,同时接收Master 的命令,例如新增或删除一个RDD。

在对RDD持久化时,Spark规定了MEMORY_ONLY、MEMORY_AND_DISK 等7种不同的存储级别,而存储级别是以下5个变量的组合:

  1. class StorageLevel private(
  2. private var _useDisk: Boolean, //磁盘
  3. private var _useMemory: Boolean, //这里其实是指堆内内存
  4. private var _useOffHeap: Boolean, //堆外内存
  5. private var _deserialized: Boolean, //是否为非序列化
  6. private var _replication: Int = 1 //副本个数
  7. )

Spark中7种存储级别如下:

持久化级别

含义

MEMORY_ONLY

以非序列化的Java对象的方式持久化在JVM内存中。如果内存无法完全存储RDD所有的partition,那么那些没有持久化的partition就会在下一次需要使用它们的时候,重新被计算

MEMORY_AND_DISK

同上,但是当某些partition无法存储在内存中时,会持久化到磁盘中。下次需要使用这些partition时,需要从磁盘上读取

MEMORY_ONLY_SER

同MEMORY_ONLY,但是会使用Java序列化方式,将Java对象序列化后进行持久化。可以减少内存开销,但是需要进行反序列化,因此会加大CPU开销

MEMORY_AND_DISK_SER

同MEMORY_AND_DISK,但是使用序列化方式持久化Java对象

DISK_ONLY

使用非序列化Java对象的方式持久化,完全存储到磁盘上

MEMORY_ONLY_2

MEMORY_AND_DISK_2

等等

如果是尾部加了2的持久化级别,表示将持久化数据复用一份,保存到其他节点,从而在数据丢失时,不需要再次计算,只需要使用备份数据即可

通过对数据结构的分析,可以看出存储级别从三个维度定义了RDD的 Partition(同时也就是Block)的存储方式:

存储位置:磁盘/堆内内存/堆外内存。如MEMORY_AND_DISK是同时在磁盘和堆内内存上存储,实现了冗余备份。OFF_HEAP 则是只在堆外内存存储,目前选择堆外内存时不能同时存储到其他位置。

存储形式:Block 缓存到存储内存后,是否为非序列化的形式。如 MEMORY_ONLY是非序列化方式存储,OFF_HEAP 是序列化方式存储。

副本数量:大于1时需要远程冗余备份到其他节点。如DISK_ONLY_2需要远程备份1个副本。

  1. RDD的缓存过程

RDD 在缓存到存储内存之前,Partition中的数据一般以迭代器(Iterator)的数据结构来访问,这是Scala语言中一种遍历数据集合的方法。通过Iterator可以获取分区中每一条序列化或者非序列化的数据项(Record),这些Record的对象实例在逻辑上占用了JVM堆内内存的other部分的空间,同一Partition的不同 Record 的存储空间并不连续。

RDD 在缓存到存储内存之后,Partition 被转换成Block,Record在堆内或堆外存储内存中占用一块连续的空间。将Partition由不连续的存储空间转换为连续存储空间的过程,Spark称之为"展开"(Unroll)。

Block 有序列化和非序列化两种存储格式,具体以哪种方式取决于该 RDD 的存储级别。非序列化的Block以一种 DeserializedMemoryEntry 的数据结构定义,用一个数组存储所有的对象实例,序列化的Block则以SerializedMemoryEntry的数据结构定义,用字节缓冲区(ByteBuffer)来存储二进制数据。每个 Executor 的 Storage模块用一个链式Map结构(LinkedHashMap)来管理堆内和堆外存储内存中所有的Block对象的实例,对这个LinkedHashMap新增和删除间接记录了内存的申请和释放。

因为不能保证存储空间可以一次容纳 Iterator 中的所有数据,当前的计算任务在 Unroll 时要向 MemoryManager 申请足够的Unroll空间来临时占位,空间不足则Unroll失败,空间足够时可以继续进行。

对于序列化的Partition,其所需的Unroll空间可以直接累加计算,一次申请。

对于非序列化的 Partition 则要在遍历 Record 的过程中依次申请,即每读取一条 Record,采样估算其所需的Unroll空间并进行申请,空间不足时可以中断,释放已占用的Unroll空间。

如果最终Unroll成功,当前Partition所占用的Unroll空间被转换为正常的缓存 RDD的存储空间,如下图所示。

在静态内存管理时,Spark 在存储内存中专门划分了一块 Unroll 空间,其大小是固定的,统一内存管理时则没有对 Unroll 空间进行特别区分,当存储空间不足时会根据动态占用机制进行处理。

淘汰与落盘

由于同一个Executor的所有的计算任务共享有限的存储内存空间,当有新的 Block 需要缓存但是剩余空间不足且无法动态占用时,就要对LinkedHashMap中的旧Block进行淘汰(Eviction),而被淘汰的Block如果其存储级别中同时包含存储到磁盘的要求,则要对其进行落盘(Drop),否则直接删除该Block。

存储内存的淘汰规则为:

被淘汰的旧Block要与新Block的MemoryMode相同,即同属于堆外或堆内内存;

新旧Block不能属于同一个RDD,避免循环淘汰;

旧Block所属RDD不能处于被读状态,避免引发一致性问题;

遍历LinkedHashMap中Block,按照最近最少使用(LRU)的顺序淘汰,直到满足新Block所需的空间。其中LRU是LinkedHashMap的特性。

落盘的流程则比较简单,如果其存储级别符合_useDisk为true的条件,再根据其_deserialized判断是否是非序列化的形式,若是则对其进行序列化,最后将数据存储到磁盘,在Storage模块中更新其信息。

执行内存管理

执行内存主要用来存储任务在执行Shuffle时占用的内存,Shuffle是按照一定规则对RDD数据重新分区的过程,我们来看Shuffle的Write和Read两阶段对执行内存的使用:

1)Shuffle Write

若在map端选择普通的排序方式,会采用ExternalSorter进行外排,在内存中存储数据时主要占用堆内执行空间。

若在map端选择 Tungsten 的排序方式,则采用ShuffleExternalSorter直接对以序列化形式存储的数据排序,在内存中存储数据时可以占用堆外或堆内执行空间,取决于用户是否开启了堆外内存以及堆外执行内存是否足够。

2)Shuffle Read

在对reduce端的数据进行聚合时,要将数据交给Aggregator处理,在内存中存储数据时占用堆内执行空间。

如果需要进行最终结果排序,则要将再次将数据交给ExternalSorter 处理,占用堆内执行空间。

在ExternalSorter和Aggregator中,Spark会使用一种叫AppendOnlyMap的哈希表在堆内执行内存中存储数据,但在 Shuffle 过程中所有数据并不能都保存到该哈希表中,当这个哈希表占用的内存会进行周期性地采样估算,当其大到一定程度,无法再从MemoryManager 申请到新的执行内存时,Spark就会将其全部内容存储到磁盘文件中,这个过程被称为溢存(Spill),溢存到磁盘的文件最后会被归并(Merge)。

Shuffle Write 阶段中用到的Tungsten是Databricks公司提出的对Spark优化内存和CPU使用的计划(钨丝计划),解决了一些JVM在性能上的限制和弊端。Spark会根据Shuffle的情况来自动选择是否采用Tungsten排序。

Tungsten 采用的页式内存管理机制建立在MemoryManager之上,即 Tungsten 对执行内存的使用进行了一步的抽象,这样在 Shuffle 过程中无需关心数据具体存储在堆内还是堆外。

每个内存页用一个MemoryBlock来定义,并用 Object obj 和 long offset 这两个变量统一标识一个内存页在系统内存中的地址。

堆内的MemoryBlock是以long型数组的形式分配的内存,其obj的值为是这个数组的对象引用,offset是long型数组的在JVM中的初始偏移地址,两者配合使用可以定位这个数组在堆内的绝对地址;堆外的 MemoryBlock是直接申请到的内存块,其obj为null,offset是这个内存块在系统内存中的64位绝对地址。Spark用MemoryBlock巧妙地将堆内和堆外内存页统一抽象封装,并用页表(pageTable)管理每个Task申请到的内存页。

Tungsten 页式管理下的所有内存用64位的逻辑地址表示,由页号和页内偏移量组成:

页号:占13位,唯一标识一个内存页,Spark在申请内存页之前要先申请空闲页号。

页内偏移量:占51位,是在使用内存页存储数据时,数据在页内的偏移地址。

有了统一的寻址方式,Spark 可以用64位逻辑地址的指针定位到堆内或堆外的内存,整个Shuffle Write排序的过程只需要对指针进行排序,并且无需反序列化,整个过程非常高效,对于内存访问效率和CPU使用效率带来了明显的提升。

Spark的存储内存和执行内存有着截然不同的管理方式:对于存储内存来说,Spark用一个LinkedHashMap来集中管理所有的Block,Block由需要缓存的 RDD的Partition转化而成;而对于执行内存,Spark用AppendOnlyMap来存储 Shuffle过程中的数据,在Tungsten排序中甚至抽象成为页式内存管理,开辟了全新的JVM内存管理机制。

Spark详解(08) - Spark(3.0)内核解析和源码欣赏的更多相关文章

  1. Java源码详解系列(十二)--Eureka的使用和源码

    eureka 是由 Netflix 团队开发的针对中间层服务的负载均衡器,在微服务项目中被广泛使用.相比 SLB.ALB 等负载均衡器,eureka 的服务注册是无状态的,扩展起来非常方便. 在这个系 ...

  2. Java基础进阶:时间类要点摘要,时间Date类实现格式化与解析源码实现详解,LocalDateTime时间类格式化与解析源码实现详解,Period,Duration获取时间间隔与源码实现,程序异常解析与处理方式

    要点摘要 课堂笔记 日期相关 JDK7 日期类-Date 概述 表示一个时间点对象,这个时间点是以1970年1月1日为参考点; 作用 可以通过该类的对象,表示一个时间,并面向对象操作时间; 构造方法 ...

  3. 详解Mybatis拦截器(从使用到源码)

    详解Mybatis拦截器(从使用到源码) MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能. 本文从配置到源码进行分析. 一.拦截器介绍 MyBatis 允许你在 ...

  4. Eureka详解系列(五)--Eureka Server部分的源码和配置

    简介 按照原定的计划,我将分三个部分来分析 Eureka 的源码: Eureka 的配置体系(已经写完,见Eureka详解系列(三)--探索Eureka强大的配置体系): Eureka Client ...

  5. Tensorflow源码解析1 -- 内核架构和源码结构

    1 主流深度学习框架对比 当今的软件开发基本都是分层化和模块化的,应用层开发会基于框架层.比如开发Linux Driver会基于Linux kernel,开发Android app会基于Android ...

  6. 《Netty5.0架构剖析和源码解读》【PDF】下载

    <Netty5.0架构剖析和源码解读>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230062545 内容简介 Netty 是个异步的 ...

  7. Spark详解

    原文连接 http://xiguada.org/spark/ Spark概述 当前,MapReduce编程模型已经成为主流的分布式编程模型,它极大地方便了编程人员在不会分布式并行编程的情况下,将自己的 ...

  8. TCP协议详解7层和4层解析(美团,阿里) 尤其是三次握手,四次挥手 具体发送的报文和状态都要掌握

    如果想了解HTTP的协议结构,原理,post,get的区别(阿里面试题目),请参考:HTTP协议 结构,get post 区别(阿里面试) 这里有个大白话的解说,可以参考:TCP/IP协议三次握手和四 ...

  9. Eureka详解系列(四)--Eureka Client部分的源码和配置

    简介 按照原定的计划,我将分三个部分来分析 Eureka 的源码: Eureka 的配置体系(已经写完,见Eureka详解系列(三)--探索Eureka强大的配置体系): Eureka Client ...

  10. 18个示例详解 Spring 事务传播机制(附测试源码)

    什么是事务传播机制 事务的传播机制,顾名思义就是多个事务方法之间调用,事务如何在这些方法之间传播. 举个例子,方法 A 是一个事务的方法,方法 A 执行的时候调用了方法 B,此时方法 B 有无事务以及 ...

随机推荐

  1. 9. RabbitMQ系列之消息发布确认

    Publisher Confirms发布确认是用于实现可靠发布的RabbitMQ扩展. 我们将使用发布确认来确保已发布的消息已安全到达代理.我们将介绍几种使用publisher确认的策略,并解释其优缺 ...

  2. Blazor组件自做十一 : File System Access 文件系统访问 组件

    Blazor File System Access 文件系统访问 组件 Web 应用程序与用户本地设备上的文件进行交互 File System Access API(以前称为 Native File ...

  3. 第一个微信小程序的初始化过程、小程序微信开发平台的下载、如何注册一个微信小程序的账号

    文章目录 1.注册微信小程序账号 1.1 小程序的注册流程 1.2 登录小程序账号 2.下载微信小程序开发者平台 3.新建一个小程序 3.1 点击加号 3.2 填写项目目录和小程序ID 3.3 点击确 ...

  4. k8s集权IP更换

    -.背景描述 背景:在场内进行部署完成后标准版产品,打包服务器到客户现场后服务不能正常使用,因为客户现场的IP地址不能再使用场内的IP,导致部署完的产品环境在客户现场无法使用:此方案就是针对这一问题撰 ...

  5. Azure Devops Create Project TF400711问题分析解决

    前几天,团队使用Azure Devops创建团队项目出了一个奇怪的错误: TF400797: 作业扩展具有一个未处理的错误: Microsoft.TeamFoundation.Framework.Se ...

  6. Java注解与原理分析

    目录 一.注解基础 二.注解原理 三.常用注解 1.JDK注解 2.Lombok注解 四.自定义注解 1.同步控制 2.类型引擎 五.参考源码 使用的太多,被忽略的理所当然: 一.注解基础 注解即标注 ...

  7. 16、有n个正数,使得前面每个数依次后移m个位置,最后m个数变成最前面m个数

    /* 有n个正数,使得前面每个数依次后移m个位置,最后m个数变成最前面m个数 */ #include <stdio.h> #include <stdlib.h> #define ...

  8. Seata 1.5.2 源码学习(事务执行)

    关于全局事务的执行,虽然之前的文章中也有所涉及,但不够细致,今天再深入的看一下事务的整个执行过程是怎样的. 1. TransactionManager io.seata.core.model.Tran ...

  9. bugku web基础$_GET

    让我们通过url传入what的值,让其等于flag 直接构造url就得到flag了

  10. Axios 类似于for循环发送批量请求{:axios.all axios.spread}。

    Axios的请求都是异步的!不能用for循环遍历去批量发送请求 那如果我们需要类似与这样的请求怎么办呢 for(let i =0;i<array.length;i++){ axios.post( ...