Github user tgravescs commented on a diff in the pull request:

    https://github.com/apache/spark/pull/2020#discussion_r16684794
  
    --- Diff: 
yarn/common/src/main/scala/org/apache/spark/deploy/yarn/ApplicationMaster.scala 
---
    @@ -0,0 +1,426 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one or more
    + * contributor license agreements.  See the NOTICE file distributed with
    + * this work for additional information regarding copyright ownership.
    + * The ASF licenses this file to You under the Apache License, Version 2.0
    + * (the "License"); you may not use this file except in compliance with
    + * the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.spark.deploy.yarn
    +
    +import java.io.IOException
    +import java.net.Socket
    +import java.util.concurrent.atomic.AtomicReference
    +
    +import scala.collection.JavaConversions._
    +import scala.util.Try
    +
    +import akka.actor._
    +import akka.remote._
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs.{FileSystem, Path}
    +import org.apache.hadoop.util.ShutdownHookManager
    +import org.apache.hadoop.yarn.api._
    +import org.apache.hadoop.yarn.api.records._
    +import org.apache.hadoop.yarn.conf.YarnConfiguration
    +
    +import org.apache.spark.{Logging, SecurityManager, SparkConf, SparkContext}
    +import org.apache.spark.deploy.SparkHadoopUtil
    +import org.apache.spark.scheduler.cluster.CoarseGrainedSchedulerBackend
    +import 
org.apache.spark.scheduler.cluster.CoarseGrainedClusterMessages.AddWebUIFilter
    +import org.apache.spark.util.{AkkaUtils, SignalLogger, Utils}
    +
    +/**
    + * Common application master functionality for Spark on Yarn.
    + */
    +private[spark] class ApplicationMaster(args: ApplicationMasterArguments,
    +  client: YarnRMClient) extends Logging {
    +  // TODO: Currently, task to container is computed once (TaskSetManager) 
- which need not be
    +  // optimal as more containers are available. Might need to handle this 
better.
    +  private val ALLOCATE_HEARTBEAT_INTERVAL = 100
    +
    +  private val sparkConf = new SparkConf()
    +  private val yarnConf: YarnConfiguration = new YarnConfiguration(new 
Configuration())
    +  private val isDriver = args.userClass != null
    +
    +  // Default to numExecutors * 2, with minimum of 3
    +  private val maxNumExecutorFailures = 
sparkConf.getInt("spark.yarn.max.executor.failures",
    +    sparkConf.getInt("spark.yarn.max.worker.failures", 
math.max(args.numExecutors * 2, 3)))
    +
    +  @volatile private var finished = false
    +  @volatile private var finalStatus = FinalApplicationStatus.UNDEFINED
    +
    +  private var reporterThread: Thread = _
    +  private var allocator: YarnAllocator = _
    +
    +  // Fields used in client mode.
    +  private var actorSystem: ActorSystem = null
    +  private var actor: ActorRef = _
    +
    +  // Fields used in cluster mode.
    +  private val sparkContextRef = new AtomicReference[SparkContext](null)
    +
    +  final def run(): Int = {
    +    if (isDriver) {
    +      // Set the web ui port to be ephemeral for yarn so we don't conflict 
with
    +      // other spark processes running on the same box
    +      System.setProperty("spark.ui.port", "0")
    +
    +      // Set the master property to match the requested mode.
    +      System.setProperty("spark.master", "yarn-cluster")
    +    }
    +
    +    logInfo("ApplicationAttemptId: " + client.getAttemptId())
    +
    +    val cleanupHook = new Runnable {
    +      override def run() {
    +        // If the SparkContext is still registered, shut it down as a best 
case effort in case
    +        // users do not call sc.stop or do System.exit().
    +        val sc = sparkContextRef.get()
    +        if (sc != null) {
    +          logInfo("Invoking sc stop from shutdown hook")
    +          sc.stop()
    +          finish(FinalApplicationStatus.SUCCEEDED)
    +        }
    +
    +        // Cleanup the staging dir after the app is finished, or if it's 
the last attempt at
    +        // running the AM.
    +        val maxAppAttempts = client.getMaxRegAttempts(yarnConf)
    +        val isLastAttempt = client.getAttemptId().getAttemptId() >= 
maxAppAttempts
    +        if (finished || isLastAttempt) {
    +          cleanupStagingDir()
    +        }
    +      }
    +    }
    +    // Use priority 30 as it's higher than HDFS. It's the same priority 
MapReduce is using.
    +    ShutdownHookManager.get().addShutdownHook(cleanupHook, 30)
    +
    +    // Call this to force generation of secret so it gets populated into 
the
    +    // Hadoop UGI. This has to happen before the startUserClass which does 
a
    +    // doAs in order for the credentials to be passed on to the executor 
containers.
    +    val securityMgr = new SecurityManager(sparkConf)
    +
    +    if (isDriver) {
    +      runDriver()
    +    } else {
    +      runExecutorLauncher(securityMgr)
    +    }
    +
    +    if (finalStatus != FinalApplicationStatus.UNDEFINED) {
    +      finish(finalStatus)
    +      0
    +    } else {
    +      1
    +    }
    +  }
    +
    +  final def finish(status: FinalApplicationStatus, diagnostics: String = 
null) = synchronized {
    +    if (!finished) {
    +      logInfo(s"Finishing ApplicationMaster with $status"  +
    +        Option(diagnostics).map(msg => s" (diag message: 
$msg)").getOrElse(""))
    +      finished = true
    +      finalStatus = status
    +      reporterThread.interrupt()
    +      try {
    +        if (Thread.currentThread() != reporterThread) {
    +          reporterThread.join()
    +        }
    +      } finally {
    +        client.shutdown(status, Option(diagnostics).getOrElse(""))
    +      }
    +    }
    +  }
    +
    +  private def sparkContextInitialized(sc: SparkContext) = {
    +    sparkContextRef.synchronized {
    +      sparkContextRef.compareAndSet(null, sc)
    +      sparkContextRef.notifyAll()
    +    }
    +  }
    +
    +  private def sparkContextStopped(sc: SparkContext) = {
    +    sparkContextRef.compareAndSet(sc, null)
    +  }
    +
    +  private def registerAM(uiAddress: String, uiHistoryAddress: String) = {
    +    val sc = sparkContextRef.get()
    +    allocator = client.register(yarnConf,
    +      if (sc != null) sc.getConf else sparkConf,
    +      if (sc != null) sc.preferredNodeLocationData else Map(),
    +      uiAddress,
    +      uiHistoryAddress)
    +
    +    allocator.allocateResources()
    +    reporterThread = launchReporterThread()
    +  }
    +
    +  private def runDriver(): Unit = {
    +    addAmIpFilter()
    +    val userThread = startUserClass()
    +
    +    // This a bit hacky, but we need to wait until the spark.driver.port 
property has
    +    // been set by the Thread executing the user class.
    +    val sc = waitForSparkContextInitialized()
    +
    +    // If there is no SparkContext at this point, just fail the app.
    +    if (sc == null) {
    +      finish(FinalApplicationStatus.FAILED, "Timed out waiting for 
SparkContext.")
    +    } else {
    +      registerAM(sc.ui.appUIHostPort, 
YarnSparkHadoopUtil.getUIHistoryAddress(sc, sparkConf))
    +      try {
    +        userThread.join()
    +      } finally {
    +        // In cluster mode, ask the reporter thread to stop since the user 
app is finished.
    +        reporterThread.interrupt()
    +      }
    +    }
    +  }
    +
    +  private def runExecutorLauncher(securityMgr: SecurityManager): Unit = {
    +    actorSystem = AkkaUtils.createActorSystem("sparkYarnAM", 
Utils.localHostName, 0,
    +      conf = sparkConf, securityManager = securityMgr)._1
    +    actor = waitForSparkDriver()
    +    addAmIpFilter()
    +    registerAM(sparkConf.get("spark.driver.appUIAddress", ""),
    +      sparkConf.get("spark.driver.appUIHistoryAddress", ""))
    +
    +    // In client mode the actor will stop the reporter thread.
    +    reporterThread.join()
    +    finalStatus = FinalApplicationStatus.SUCCEEDED
    +  }
    +
    +  private def launchReporterThread(): Thread = {
    +    // Ensure that progress is sent before 
YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS elapses.
    +    val expiryInterval = 
yarnConf.getInt(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, 120000)
    +
    +    // we want to be reasonably responsive without causing too many 
requests to RM.
    +    val schedulerInterval =
    +      sparkConf.getLong("spark.yarn.scheduler.heartbeat.interval-ms", 5000)
    +
    +    // must be <= expiryInterval / 2.
    +    val interval = math.max(0, math.min(expiryInterval / 2, 
schedulerInterval))
    +
    +    val t = new Thread {
    +      override def run() {
    +        while (!finished) {
    +          checkNumExecutorsFailed()
    +          logDebug("Sending progress")
    +          allocator.allocateResources()
    +          try {
    +            Thread.sleep(interval)
    +          } catch {
    +            case e: InterruptedException =>
    +          }
    +        }
    +      }
    +    }
    +    // setting to daemon status, though this is usually not a good idea.
    +    t.setDaemon(true)
    +    t.setName("Reporter")
    +    t.start()
    +    logInfo("Started progress reporter thread - sleep time : " + interval)
    +    t
    +  }
    +
    +  /**
    +   * Clean up the staging directory.
    +   */
    +  private def cleanupStagingDir() {
    +    val fs = FileSystem.get(yarnConf)
    +    var stagingDirPath: Path = null
    +    try {
    +      val preserveFiles = 
sparkConf.get("spark.yarn.preserve.staging.files", "false").toBoolean
    +      if (!preserveFiles) {
    +        stagingDirPath = new Path(System.getenv("SPARK_YARN_STAGING_DIR"))
    +        if (stagingDirPath == null) {
    +          logError("Staging directory is null")
    +          return
    +        }
    +        logInfo("Deleting staging directory " + stagingDirPath)
    +        fs.delete(stagingDirPath, true)
    +      }
    +    } catch {
    +      case ioe: IOException =>
    +        logError("Failed to cleanup staging dir " + stagingDirPath, ioe)
    +    }
    +  }
    +
    +  // Note: this needs to happen before allocateExecutors.
    --- End diff --
    
    nit, comment not valid anymore


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to