SparkContext是Spark的入口,负责连接Spark集群,创建RDD,累积量和广播量等,向集群申请资源与分配任务并监控任务的状态与执行情况。在Yarn-Cluster 模式中Spark任务运行的的整体流程为:
- Spark客户端向Yarn集群提交应用程序。
- ResourceManager 收到请求后,在集群中选择一个 NodeManager,并为该应用程序分配一个 Container,在这个 Container 中启动应用程序的 ApplicationMaster, ApplicationMaster 进行 SparkContext 等的初始化。
- ApplicationMaster 向 ResourceManager 注册,这样用户可以直接通过 ResourceManager 查看应用程序的运行状态,然后它将采用轮询的方式通过RPC协议为各个任务申请资源,并监控它们的运行状态直到运行结束。
- ApplicationMaster 申请到资源(也就是Container)后,便与对应的 NodeManager 通信,并在获得的 Container 中启动 CoarseGrainedExecutorBackend,启动后会向 ApplicationMaster 中的 SparkContext 注册并申请 Task。
- ApplicationMaster 中的 SparkContext 分配 Task 给 CoarseGrainedExecutorBackend 执行,CoarseGrainedExecutorBackend 运行 Task 并向ApplicationMaster 汇报运行的状态和进度,以让 ApplicationMaster 随时掌握各个任务的运行状态,从而可以在任务失败时重新启动任务。
- 应用程序运行完成后,ApplicationMaster 向 ResourceManager申请注销并关闭自己。
由此可以看出SparkContext是整个任务的核心,我们在任何一个spark程序中,首先需要做的是构造一个SparkContext,然后需要通过SparkContext来创建RDD,然后进行计算。
一、SparkContext的主构造器
SparkContext的主构造器参数为SparkConf, 其实现如下:
/**
* Main entry point for Spark functionality. A SparkContext represents the connection to a Spark
* cluster, and can be used to create RDDs, accumulators and broadcast variables on that cluster.
* SparkContext为Spark功能的主要入口。一个SparkContext代表一个Spark集群的连接,
* 可以在集群中创建RDD、累加器和广播变量。
* @note Only one `SparkContext` should be active per JVM. You must `stop()` the
* active `SparkContext` before creating a new one.
* 注意:在每个JVM中只能有一个活跃的SparkContext,你必须在创建新的SparkContext前停掉已有的活跃实例。
* @param config a Spark Config object describing the application configuration. Any settings in
* this config overrides the default configs as well as system properties.
* 参数:SparkConf是Spark任务的配置对象。程序中的对SparkConf的任何设置会覆盖默认配置以及系统属性。
*/
class SparkContext(config: SparkConf) extends Logging {