深入理解Spark 2.1 Core (十三):sparkEnv类源码分析

来源:互联网 发布:仿真软件培训 编辑:程序博客网 时间:2024/05/19 18:13

sparkEnv为运行的Spark实例(master,worker,executor等)持有运行环境相关的对象,sparkenv管理serializer, Akka actor system, block manager, map output tracker等对象。sparkEnv主要被内部使用,后面可能仅供内部使用。sparkEnv最重要的方法是createDriverEnv方法,该方法有三个参数: conf: SparkConf,;isLocal:Boolean; listenerBus: LiveListenerBus。LiveListenerBus以监听器方式监听各种事件并处理。

[java] view plain copy
  1. private[spark] def createDriverEnv(  
  2.     conf: SparkConf,  
  3.     isLocal: Boolean,  
  4.     listenerBus: LiveListenerBus,  
  5.     mockOutputCommitCoordinator: Option[OutputCommitCoordinator] = None): SparkEnv = {  
  6.   assert(conf.contains("spark.driver.host"), "spark.driver.host is not set on the driver!")  
  7.   assert(conf.contains("spark.driver.port"), "spark.driver.port is not set on the driver!")  
  8.   val hostname = conf.get("spark.driver.host")  
  9.   val port = conf.get("spark.driver.port").toInt  
  10.   create(  
  11.     conf,  
  12.     SparkContext.DRIVER_IDENTIFIER,  
  13.     hostname,  
  14.     port,  
  15.     isDriver = true,  
  16.     isLocal = isLocal,  
  17.     listenerBus = listenerBus,  
  18.     mockOutputCommitCoordinator = mockOutputCommitCoordinator  
  19.   )  
  20. }  

上述方法最后调用create方法来创建:主要创建securityManager、ActorSystem、mapOutputTracker、ShuffleManager、ShuffleMemoryManger、BlockTranferService、BlockManagerMaster,BlockManager、BroadCastManager、CacheManager、HttpFileServer、metricssystem:
[java] view plain copy
  1. private def create(  
  2.     conf: SparkConf,  
  3.     executorId: String,  
  4.     hostname: String,  
  5.     port: Int,  
  6.     isDriver: Boolean,  
  7.     isLocal: Boolean,  
  8.     listenerBus: LiveListenerBus = null,  
  9.     numUsableCores: Int = 0,  
  10.     mockOutputCommitCoordinator: Option[OutputCommitCoordinator] = None): SparkEnv = {  
  11.   
  12.   // Listener bus is only used on the driver  
  13.   if (isDriver) {  
  14.     assert(listenerBus != null"Attempted to create driver SparkEnv with null listener bus!")  
  15.   }  
  16.   //创建安全管理器  
  17.   val securityManager = new SecurityManager(conf)  
  18.   
  19.   // Create the ActorSystem for Akka and get the port it binds to.  
  20.   //创建基于akka的分布式消息系统ActorSystem  
  21.   val (actorSystem, boundPort) = {  
  22.     val actorSystemName = if (isDriver) driverActorSystemName else executorActorSystemName  
  23.     AkkaUtils.createActorSystem(actorSystemName, hostname, port, conf, securityManager)  
  24.   }  
  25.   
  26.   // Figure out which port Akka actually bound to in case the original port is 0 or occupied.  
  27.   if (isDriver) {  
  28.     conf.set("spark.driver.port", boundPort.toString)  
  29.   } else {  
  30.     conf.set("spark.executor.port", boundPort.toString)  
  31.   }  
  32.   
  33.   // Create an instance of the class with the given name, possibly initializing it with our conf  
  34.   def instantiateClass[T](className: String): T = {  
  35.     val cls = Class.forName(className, true, Utils.getContextOrSparkClassLoader)  
  36.     // Look for a constructor taking a SparkConf and a boolean isDriver, then one taking just  
  37.     // SparkConf, then one taking no arguments  
  38.     try {  
  39.       cls.getConstructor(classOf[SparkConf], java.lang.Boolean.TYPE)  
  40.         .newInstance(conf, new java.lang.Boolean(isDriver))  
  41.         .asInstanceOf[T]  
  42.     } catch {  
  43.       case _: NoSuchMethodException =>  
  44.         try {  
  45.           cls.getConstructor(classOf[SparkConf]).newInstance(conf).asInstanceOf[T]  
  46.         } catch {  
  47.           case _: NoSuchMethodException =>  
  48.             cls.getConstructor().newInstance().asInstanceOf[T]  
  49.         }  
  50.     }  
  51.   }  
  52.   
  53.   // Create an instance of the class named by the given SparkConf property, or defaultClassName  
  54.   // if the property is not set, possibly initializing it with our conf  
  55.   def instantiateClassFromConf[T](propertyName: String, defaultClassName: String): T = {  
  56.     instantiateClass[T](conf.get(propertyName, defaultClassName))  
  57.   }  
  58.   
  59.   val serializer = instantiateClassFromConf[Serializer](  
  60.     "spark.serializer""org.apache.spark.serializer.JavaSerializer")  
  61.   logDebug(s"Using serializer: ${serializer.getClass}")  
  62.   
  63.   val closureSerializer = instantiateClassFromConf[Serializer](  
  64.     "spark.closure.serializer""org.apache.spark.serializer.JavaSerializer")  
  65.   
  66.   def registerOrLookup(name: String, newActor: => Actor): ActorRef = {  
  67.     if (isDriver) {  
  68.       logInfo("Registering " + name)  
  69.       actorSystem.actorOf(Props(newActor), name = name)  
  70.     } else {  
  71.       AkkaUtils.makeDriverRef(name, conf, actorSystem)  
  72.     }  
  73.   }  
  74.   //创建mapOutputTracker  
  75.   val mapOutputTracker =  if (isDriver) {  
  76.     new MapOutputTrackerMaster(conf)  
  77.   } else {  
  78.     new MapOutputTrackerWorker(conf)  
  79.   }  
  80.   
  81.   // Have to assign trackerActor after initialization as MapOutputTrackerActor  
  82.   // requires the MapOutputTracker itself  
  83.   mapOutputTracker.trackerActor = registerOrLookup(  
  84.     "MapOutputTracker",  
  85.     new MapOutputTrackerMasterActor(mapOutputTracker.asInstanceOf[MapOutputTrackerMaster], conf))  
  86.   
  87.   // Let the user specify short names for shuffle managers  
  88.   val shortShuffleMgrNames = Map(  
  89.     "hash" -> "org.apache.spark.shuffle.hash.HashShuffleManager",  
  90.     "sort" -> "org.apache.spark.shuffle.sort.SortShuffleManager")  
  91.   val shuffleMgrName = conf.get("spark.shuffle.manager""sort")  
  92.   val shuffleMgrClass = shortShuffleMgrNames.getOrElse(shuffleMgrName.toLowerCase, shuffleMgrName)  
  93.   val shuffleManager = instantiateClass[ShuffleManager](shuffleMgrClass)  
  94.   
  95.   val shuffleMemoryManager = new ShuffleMemoryManager(conf)  
  96.   
  97.   val blockTransferService =  
  98.     conf.get("spark.shuffle.blockTransferService""netty").toLowerCase match {  
  99.       case "netty" =>  
  100.         new NettyBlockTransferService(conf, securityManager, numUsableCores)  
  101.       case "nio" =>  
  102.         new NioBlockTransferService(conf, securityManager)  
  103.     }  
  104.   
  105.   val blockManagerMaster = new BlockManagerMaster(registerOrLookup(  
  106.     "BlockManagerMaster",  
  107.     new BlockManagerMasterActor(isLocal, conf, listenerBus)), conf, isDriver)  
  108.   
  109.   // NB: blockManager is not valid until initialize() is called later.  
  110.   val blockManager = new BlockManager(executorId, actorSystem, blockManagerMaster,  
  111.     serializer, conf, mapOutputTracker, shuffleManager, blockTransferService, securityManager,  
  112.     numUsableCores)  
  113.   
  114.   val broadcastManager = new BroadcastManager(isDriver, conf, securityManager)  
  115.   
  116.   val cacheManager = new CacheManager(blockManager)  
  117.   
  118.   val httpFileServer =  
  119.     if (isDriver) {  
  120.       val fileServerPort = conf.getInt("spark.fileserver.port"0)  
  121.       val server = new HttpFileServer(conf, securityManager, fileServerPort)  
  122.       server.initialize()  
  123.       conf.set("spark.fileserver.uri",  server.serverUri)  
  124.       server  
  125.     } else {  
  126.       null  
  127.     }  
  128.   
  129.   val metricsSystem = if (isDriver) {  
  130.     // Don't start metrics system right now for Driver.  
  131.     // We need to wait for the task scheduler to give us an app ID.  
  132.     // Then we can start the metrics system.  
  133.     MetricsSystem.createMetricsSystem("driver", conf, securityManager)  
  134.   } else {  
  135.     // We need to set the executor ID before the MetricsSystem is created because sources and  
  136.     // sinks specified in the metrics configuration file will want to incorporate this executor's  
  137.     // ID into the metrics they report.  
  138.     conf.set("spark.executor.id", executorId)  
  139.     val ms = MetricsSystem.createMetricsSystem("executor", conf, securityManager)  
  140.     ms.start()  
  141.     ms  
  142.   }  
  143.   
  144.   // Set the sparkFiles directory, used when downloading dependencies.  In local mode,  
  145.   // this is a temporary directory; in distributed mode, this is the executor's current working  
  146.   // directory.  
  147.   val sparkFilesDir: String = if (isDriver) {  
  148.     Utils.createTempDir(Utils.getLocalDir(conf), "userFiles").getAbsolutePath  
  149.   } else {  
  150.     "."  
  151.   }  
  152.   
  153.   // Warn about deprecated spark.cache.class property  
  154.   if (conf.contains("spark.cache.class")) {  
  155.     logWarning("The spark.cache.class property is no longer being used! Specify storage " +  
  156.       "levels using the RDD.persist() method instead.")  
  157.   }  
  158.   
  159.   val outputCommitCoordinator = mockOutputCommitCoordinator.getOrElse {  
  160.     new OutputCommitCoordinator(conf)  
  161.   }  
  162.   val outputCommitCoordinatorActor = registerOrLookup("OutputCommitCoordinator",  
  163.     new OutputCommitCoordinatorActor(outputCommitCoordinator))  
  164.   outputCommitCoordinator.coordinatorActor = Some(outputCommitCoordinatorActor)  
  165.   
  166.   new SparkEnv(  
  167.     executorId,  
  168.     actorSystem,  
  169.     serializer,  
  170.     closureSerializer,  
  171.     cacheManager,  
  172.     mapOutputTracker,  
  173.     shuffleManager,  
  174.     broadcastManager,  
  175.     blockTransferService,  
  176.     blockManager,  
  177.     securityManager,  
  178.     httpFileServer,  
  179.     sparkFilesDir,  
  180.     metricsSystem,  
  181.     shuffleMemoryManager,  
  182.     outputCommitCoordinator,  
  183.     conf)  

阅读全文
0 0